Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat: entity mention index; the entity card lists every page that names it (v0.61.1.0)

garrytana3246dea8f8b
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index bae12eb663..125eea6d92 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 126a098877..7f1bcfd26c 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index deb02fd956..81cec98428 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.60.48.0 -->
+<!-- gbrain-runbook-stamp: 0.61.1.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 32213b24fd..932d041e95 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,87 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.61.1.0] - 2026-10-04
+
+**Ask your brain about an account and it now hands back every ticket, meeting and email that names it, not just the few a search happens to rank first.**
+
+Before this release, a ticket that said `Customer: QUCO` or a meeting titled `QUCO renewal prep` was not connected to the account it was about. Your agent had to search, and search returns the best-matching handful. Nine near-identical tickets look alike to it, so the open one often never showed up. Now the brain links every page that names a person, company or account, by its name, by the name inside a record title (`CRM record: Acme Example`), or by a code the record declares (`Account code: ACMX`). Ask for the account and the card lists all of those pages by type, newest first, each with a one-line preview, plus the exact call to page through the rest. It costs nothing to run: no model calls, no API key.
+
+### How to use it
+
+```bash
+gbrain extract --stale --catch-up # once after upgrading; autopilot keeps it current
+gbrain entity ACMX # the card, with "referenced by N page(s)"
+gbrain backlinks crm/acme-example --type ticket --group page
+gbrain extract mentions --explain acmx --page meetings/2026-04-03 # why a name did not link
+```
+
+Over MCP, the `entity` card adds `referenced_by`, `referenced_by_count` and `coverage`; `get_backlinks` takes `type`, `group: "page"`, `limit` and `cursor`. Guide with a two-minute keyless tutorial: `docs/guides/entity-recall.md`.
+
+### The numbers that matter
+
+| Measure | Before | Now |
+|---|---|---|
+| Cat 40 account briefs (family E), development world | TODO(cat40 round 1 / round 2) | TODO |
+| Cat 40 held-out world, paired gain vs v0.60.44.0 | n/a | TODO(cat40 A3) |
+| Links from documents to the account they name (dev brain, 3,973 pages) | 0 | TODO(cat40 slot build) |
+| First full mention pass, 52,000-document world, PGLite, no embeddings | n/a | 7-16 s (52,956 links; 0.2 s when nothing changed) |
+| `entity` p99 with references, 20K pages, a 10,000-link hub | n/a | 61-71 ms (budget 100 ms) |
+| Keyless tutorial on a fresh install | n/a | 8 s |
+| Tool list the model receives (starter surface) | 24,100 chars | 24,324 chars (cap 25,000) |
+
+### Things to watch
+
+- `extract --stale` reads every page once after the upgrade. `gbrain post-upgrade` prints the command and an estimate while pages are due; autopilot does the same work over several cycles if you skip it.
+- A one-word code links only as written: `ACMX` links, `acmx` in prose does not. Names under 4 characters, generic words, a first word shared by two accounts, and names inside private facts or takes fences never link.
+- `entity("Acme Example")` stays the company page when a `CRM record: Acme Example` page also exists: an exact title always wins over a derived name.
+- `get_backlinks` without the new parameters returns the same link list as before.
+- Off switch: `gbrain config set mentions.auto_link false` removes mention links and derived names on the next sweep (typed links from `extract --ner` stay).
+
+## To take advantage of v0.61.1.0
+
+`gbrain upgrade` should do this automatically. If it didn't, or if `gbrain doctor` warns about a partial migration:
+
+1. **Run the orchestrator manually:**
+ ```bash
+ gbrain apply-migrations --yes
+ ```
+2. **Your agent reads `skills/migrations/v0.61.1.0.md` the next time you interact with it.** It runs the first mention pass (`gbrain extract --stale --catch-up`, free) or leaves it to autopilot.
+3. **Verify the outcome:**
+ ```bash
+ gbrain extract --stale --dry-run --json # mention_due_pages: 0
+ gbrain entity "<an account or person in your brain>"
+ ```
+4. **If any step fails or the numbers look wrong,** please file an issue:
+ https://github.com/garrytan/gbrain/issues with:
+ - output of `gbrain doctor`
+ - contents of `~/.gbrain/upgrade-errors.jsonl` if it exists
+ - which step broke
+
+ This feedback loop is how the gbrain maintainers find fragile upgrade paths. Thank you.
+
+### Itemized changes
+
+- **Linkable types follow the schema pack** (`src/core/mentions/policy.ts`): person, company, organization and entity, plus every type the source's pack marks `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`, `-type`). The entity card's exact-title preference uses the same set.
+- **`gbrain-base-v2` 1.3.0** adds the `account` page type (alias `crm`, `accounts/` and `crm/` folders, not routed to expert lookup).
+- **Derived names** (`src/core/mentions/aliases.ts`): an entity page's title subject and the codes it declares (`account code`, `also known as`, `aka`, `short name`, `ticker`, `code name`) are stored in `page_aliases` with `origin` `subject` or `declared`, read from text with private fences stripped. A one-word declared code is case-sensitive. Import, `gbrain reindex --aliases` and the stale sweep write the same rows; on managed brains through the coordinated writer. Frontmatter aliases are never touched by them.
+- **Precedence everywhere aliases are read**: frontmatter > declared > subject within a source, and a derived alias never answers for another page's exact title (`readAliases`, used by `resolveEntitySlug`, the retrieval reflex, the search alias hop, intent weights and `search-diagnose`).
+- **The mention pass** (`src/core/mentions/pass.ts`) runs after link work in `gbrain extract --stale`, autopilot's stale drain and the managed stale path (sync's inline extraction stays link-only). It has its own per-page state and extractor version, so it never reruns link or timeline extraction. A changed name rescans only pages that link to the old target or match the new name; an edit or a name change during a scan leaves the page due instead of publishing a stale result; a failed index build writes nothing and records `failed`; only plain mention links are reconciled (`typed_ner` links stay). Page titles are scanned too; frontmatter `mention_ignore` and `mentions.ignore` skip names. A budgeted cycle gives the mention pass half its time while pages are due.
+- **Gazetteer guards** (`src/core/by-mention.ts`): an alias claimed by two pages is dropped, a same-source title wins over an alias, a one-word alias equal to the first word of another multi-word entity name is dropped, and the generic-word list applies to every one-word alias (titles keep the person-only rule).
+- **`entity` card**: `referenced_by_count`, `referenced_by` (groups by pack-canonical type, newest first by `COALESCE(effective_date, updated_at)`, 10 rows per group, 50 per card, 160-character previews, `next` continuation) and `coverage` (`complete`, `pending`, `disabled`, `type_not_linkable`, `failed`); misses carry `coverage` too. Remote callers never see or count private or derived-private referrers. `context_pack` and `delta` do not compute them.
+- **`get_backlinks`** (`src/core/ops/backlinks-paged.ts`): `type`, `limit` (max 500), and `group: "page"` returning `{rows, total, truncated, cursor, coverage}` with a keyset cursor; an unknown `type` or out-of-range `limit` is an error naming the valid values. No new parameters, no change.
+- **`gbrain extract mentions --explain <name|slug> [--page <slug>]`** reports the matched name and origin, or one of 11 reason codes.
+- **Notices and doctor**: a non-complete coverage adds a `[gbrain notice mention_index]` block; `links_extraction_lag` reports mention-due pages; `gbrain post-upgrade` prints an `[AGENT]` catch-up line; `extract --stale --dry-run` reports `mention_due_pages` and `mention_last_pass_at`.
+- **Schema**: migration v201 adds `page_aliases.origin`, `case_sensitive` and `alias_text` (unique key widened to include `origin`) and the `page_mention_state`, `mention_gazetteer_entries` and `mention_index_status` tables. No existing row is rewritten.
+- **Config**: `mentions.auto_link` (default on), `mentions.entity_types`, `mentions.ignore`.
+- **Faster private-page filtering for remote callers** (`src/core/search/private-visibility.ts`): the declared-lineage check runs only for pages that carry `derived_from`, so remote reads no longer probe the source's private pages once per candidate row. Results are unchanged.
+- **Tool descriptions**: `entity` and `get_backlinks` describe the new fields within the unchanged schema ceilings; `query` and `search` descriptions are shorter to pay for it.
+
+### For contributors
+
+- Tests: `test/mentions-*.test.ts`, `test/e2e/mentions-parity.test.ts` (PGLite and Postgres produce the same rows), and a 10,000-link hub gate in `test/entity-card-perf.slow.test.ts`.
+- Catalog, upgrade-replay and doctor goldens regenerated for migration v201 and the pack version.
+
## [0.60.48.0] - 2026-10-04
**A managed Postgres brain now catches up a big sync backlog in one `gbrain sync` run, about 4.6 times faster, and the run tells your agent exactly what happened and what to do next (#5984).**
diff --git a/README.md b/README.md
index e3e098bdcd..f8ae277715 100644
--- a/README.md
+++ b/README.md
@@ -410,7 +410,7 @@ flowchart LR
**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).
-**Why the graph matters.** Vector search finds semantic similarity; graph retrieval follows stored relationships. Extracted edges are evidence to inspect, not proof that a relationship is true. Graph freshness depends on the write path and maintenance described in [memory boundaries](docs/guides/memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Deep dive: [retrieval architecture](docs/architecture/RETRIEVAL.md).
+**Why the graph matters.** Vector search finds similar text; graph retrieval follows stored relationships. Extracted edges are evidence to inspect, not proof that a relationship is true. Graph freshness depends on the write path and maintenance described in [memory boundaries](docs/guides/memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Deep dive: [retrieval architecture](docs/architecture/RETRIEVAL.md); [entity recall](docs/guides/entity-recall.md).
## Troubleshooting
diff --git a/VERSION b/VERSION
index 34d19106af..87d753fa4e 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.60.48.0
+0.61.1.0
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 25ff219388..fa2ba916d3 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -112,7 +112,7 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S
|---|---|---|---|---|
| `add_link` | Create a typed link (edge) from one page to another in the same source. | write | | |
| `find_orphans` | Find disconnected pages. | read | | |
-| `get_backlinks` | List links pointing to a page. | read | yes | |
+| `get_backlinks` | Links to a page; group:"page" pages newest first with total and cursor. | read | yes | |
| `get_links` | List a page's outgoing links (typed edges to other pages). | read | | |
| `list_link_sources` | Link provenances in the brain (e.g. | read | yes | |
| `remove_link` | Remove a link between two pages (optionally only one link_type or link_source). | write | | |
@@ -140,7 +140,7 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S
|---|---|---|---|---|
| `context_pack` | MEMORY VERB (v1): budget-packed cards, open threads and hot facts for up to 8 entities, zero LLM. | read | yes | |
| `delta` | MEMORY VERB (v1): what changed since a time (pages, facts, thread events), zero LLM. | read | yes | |
-| `entity` | MEMORY VERB (v1): one known person/company/project card, zero LLM. | read | yes | |
+| `entity` | MEMORY VERB (v1): person/company/account card, zero LLM. | read | yes | |
| `forget` | MEMORY VERB (v1): expire a remembered fact by its fact_id (never a page slug). | write | yes | |
| `recall` | MEMORY VERB (v1): read saved facts by entity, since or session_id; `query` also searches pages. | read | yes | |
| `remember` | MEMORY VERB (v1): save one fact; provenance required. | write | yes | |
@@ -197,7 +197,7 @@ Every non-localOnly operation on the MCP surface: 137 tools across 23 areas. **S
|---|---|---|---|---|
| `assemble_evidence` | Deliver whole evidence for an ordered list of search hits (each {source_id, slug, chunk_id} from a prior search/query result): the same windows, sections or pages `query` returns with return_unit, packed into token_budget. | read | | |
| `cache_stats` | Semantic query-cache introspection: resolved knobs (enabled, similarity threshold, TTL) plus row counts and total hits. | admin | | |
-| `query` | Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. | read | yes | |
+| `query` | Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). | read | yes | |
| `search` | Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. | read | yes | |
| `search_by_image` | Image-as-query retrieval. | read | | |
| `search_modes` | Read-only search-mode dashboard: active mode, EVERY mode-bundle knob resolved with attribution (mode default vs config override), the three frozen bundles, and a reranker_readiness verdict (whether the resolved reranker will actually run; remote callers get the verdict without the host key inventory). | read | | |
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 2efc5ebe76..212a402e29 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -58,6 +58,7 @@ boundary and add its link here rather than raising the cap.
| [Files And Sync (1/2)](key-files/files-and-sync-1.md) | `src/core/audit-week-file.ts` through `src/core/sync-git.ts:resolveSlugByPathOrSourcePath` |
| [Files And Sync (2/2)](key-files/files-and-sync-2.md) | `src/core/sync-policy.ts` through `src/core/write-through.ts` |
| [Graph And Facts](key-files/graph-and-facts.md) | `src/core/check-resolvable.ts` through `src/core/trajectory-format.ts` |
+| [Entity recall](key-files/entity-recall.md) | `src/core/mentions/*`, `src/core/ops/backlinks-paged.ts`, `extract mentions --explain`, migration v201 |
| [Mcp](key-files/mcp.md) | `src/mcp/dispatch.ts` through `src/mcp/validate-params.ts` |
| [Providers](key-files/providers.md) | `src/core/anthropic-pricing.ts` through `src/core/transcription.ts` |
| [Runtime](key-files/runtime.md) | `src/core/abort-check.ts` through `src/core/zombie-reap.ts` |
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 764f72e6d3..dc59cdc2a7 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -169,6 +169,7 @@ src/core/shared-skills/setup.ts 1 engine_guard Trusted preactivation empty-sourc
src/core/shared-skills/optimizer.ts 0 coordinator Shared optimization preserves the exact approved closure and original grants in private staging; only accepted body changes reach put_skill with the original revision and stable request UUID.
src/core/persistence/import-prepare.ts 2 coordinator The prepared local import updates source_path only inside canonical publication; owner, input and target hashes, source confinement and knowledge-versus-skill boundary revalidate before apply. Its importFromContent calls carry prepare and run inside the coordinator publication.
src/core/persistence/grandfather.ts 2 coordinator Private migration intents preserve exact page/source/incarnation/revision identity and rollback snapshots; frontmatter/hash and existing text seals change only inside canonical file publication, without new embedding or fact-backstop effects.
+src/core/mentions/pass.ts 7 coordinator Derived page_aliases rows (origin declared/subject) are replaced per page; on a managed brain the mention pass runs each alias batch inside withCoordinatedWrite for its source after re-reading page revisions, import writes them inside the caller's coordinated import transaction, and reindex --aliases holds the coordinated write itself. Frontmatter alias rows are never touched; unmanaged brains keep the SQL guard.
src/core/page-state/rename-alias.ts 8 engine_guard Rename aliases (slug_aliases) and moveSlugBindings (facts entity/fence slugs, page_aliases, withdrawal subjects) run inside the updateSlug transaction; the canonical table SQL trigger requires coordinator capability, so legacy calls fail before publication.
src/core/timeline-extract.ts 1 engine_guard Retracting removed markdown timeline rows is canonical table SQL; the trigger requires coordinator capability, so legacy calls fail before canonical DB publication.
src/core/persistence/connector-google-receipts.ts 1 coordinator Account and message-owned Gmail receipt metadata changes only under canonical source/page locks, identity/revision and file guards; guarded projection installation preserves withdrawal overlays without replaying bodies or extracting facts.
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index 369d7af1de..16723321bc 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -9,7 +9,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.
- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).
- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).
-- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.
+- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope, per client) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner). Test: `test/notice-ledger.test.ts`.
- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).
- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.serial.test.ts`.
- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated.serial.test.ts`.
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index a3c29f2dfb..1af3f12ff3 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `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; a page's frontmatter `conversation_segment_gap_minutes`, an integer from 1 to 10080, overrides the gap for that page, and any other value is ignored with a stderr warning naming the accepted range), 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` (a DEFAULT cap is dropped with a warning when the extraction or parser chat model is unpriced, via `src/core/facts/conversation-budget.ts` `conversationFactsCostCap` (#5823); explicit CLI/caller/cycle caps stay fail-closed and a `no_pricing` stop reports `budget_reason`/`budget_model`, exits 1 and names `pricing.overrides`); **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`); **`--background` via `maybeBackground`**; and **speaker-shaped-fold decline** — when the parse reports `unrecognized_headings` containing a speaker-shaped label (1-2 title-cased words, not in the doc-heading stoplist — the stoplist gates the DECLINE only, so a miss is warn-noise, never data loss) AND the parse produced fewer than two distinct speakers, the page is declined instead of extracted under wrong attribution: counted in `pages_skipped_unrecognized_speaker` (Result/CLI/cycle surfaces), warned to stderr with the folding pattern id, and deliberately NON-terminal (no durable audit row and no orphan cleanup, so a future parser/pattern fix retries the page); multi-speaker pages with folds proceed warn-only. 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`. `--workers N` for LLM-bound fact extraction over conversation pages, with a per-page advisory lock via `src/core/db-lock.ts:withRefreshingLock` (lock id `extract-conversation-facts:<source>:<slug>`, TTL `PER_PAGE_LOCK_TTL_MINUTES=2` with 20s refresh via `Math.max(15s, 120s/6)`; `LockUnavailableError` triggers skip-and-continue with rate-limited log per (source, minute) + `pages_lock_skipped` counter + CLI exits 3 when non-zero AND no hard failures). `deleteOrphanFactsForPage(engine, sourceId, slug)` provides delete-orphans-first replay safety — wipes facts from a prior crashed run for this (sourceId, slug) before re-extracting, so a terminal audit row can never certify a partial insertFacts failure. `assertFactsEmbeddingDimMatchesConfig(engine)` is the startup preflight (throws `FactsEmbeddingDimMismatchError` with paste-ready ALTER hint BEFORE the first insert; cached per engine via WeakMap). Result type carries `pages_lock_skipped` + `orphan_facts_cleaned`. Additive `pages_skipped_unparsed`, `pages_skipped_type_mismatch`, `pages_skipped_insufficient_turns`, and `pages_skipped_since` explain the unchanged `pages_skipped` aggregate across core, CLI, workers, and cycle sources; durable completion remains separate. `--dry-run` stops after segmentation, with no parser-fallback, extractor, or embedding calls and no durable knowledge/checkpoint/receipt/rollup writes. The narrow `python-dict-utterance` registry format and its quoted/nested-example rejection are documented in [conversation parser patterns](../conversation-parser-patterns.md). Checkpoint state is a shared `cpMap: Map<slug, endIso>` (NOT a per-page-mutated `cpEntries: string[]`) so atomic `Map.set` survives parallel workers. Minion handler `extract-conversation-facts` in `src/commands/jobs.ts` round-trips `workers` via `job.data.workers` for `--background --workers 20`. Cycle config key `cycle.conversation_facts_backfill.workers` (default 1; opt-in concurrency under brain-wide cost + walltime caps). Pinned by `test/extract-conversation-facts-diagnostics.serial.test.ts` (pool workers, per-page lock skip + exit 3, delete-orphans-first replay, D15 preflight, `--workers` round-trip) + the existing extract-conversation-facts behavioral tests. with `src/commands/doctor.ts` durable outcome authority: page completion survives operation-checkpoint GC through versioned terminal audit rows (`cli:extract-conversation-facts:terminal:v2`), while recognized pages with no eligible segment use the separate `cli:extract-conversation-facts:non-extractable:v2` source. Each outcome is bound to the exact parsed snapshot: regular pages use `content_hash` plus the UTC effective date; raw-conversation sidecars and legacy null-hash pages use a canonical SHA-256 over every parser-relevant input. Selection checks the token before locking, refetches under the lock, and verifies it again before writing the outcome, so an edit cannot be certified by stale work. The strict extraction path treats provider, refusal, truncation, malformed/schema-invalid output, segment-write, cleanup, and terminal-write failures as unfinished work; bulk failures increment `pages_failed`, affect CLI/cycle receipts and exit status, and never advance the legacy checkpoint. Checkpoints are only a scheduling hint: a slug without a matching v2 outcome is replayed delete-first. `no_match`, errors, cancellation, and dry runs never become durable negatives. Result, CLI, cycle, and doctor surfaces keep completed, scanned-not-extractable, unfinished, failed, and lock-skipped counts separate. See [Conversation backfill durable outcomes](../../operations/conversation-backfill-outcomes.md) for the operator and maintainer contract. Pinned by `test/extract-conversation-facts.test.ts` and `test/doctor-conversation-facts-backlog.test.ts`. On a managed brain the core runs `managedDerivedFactsPreflight` (local writer, active source) before any provider work, and a page's facts and terminal (or non-extractable) audit row are buffered, then replace the prior extractor batch in one `replaceDerivedFactsForPage` transaction after source activity, page id, revision and parser-input snapshot are rechecked under the page lock, so a failed or raced re-extraction keeps the prior batch; the CLI no longer refuses up front and receipt pages are skipped. Tests: `test/managed-facts-writers.test.ts`, `test/managed-unsupported-preflight.serial.test.ts` (refusal before spend for an unaccepted writer).
-- `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). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `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`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale. Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result; standalone CLI output is unchanged. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. 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 `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). `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. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. 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`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.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`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, 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` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + 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 case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
+- `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). The full fs walk replaces each page's own markdown-derived links through `replacePageFileLinks` (the per-slug contract below; a file with no page row is skipped and not stamped); the db link walk and `extract --stale` replace through `replaceDerivedLinks`. Timeline rows are inserted in batches of 100 via `addTimelineEntriesBatch` (`ON CONFLICT DO NOTHING`; `created` counts real inserts) after every path — fs walk, db walk, per-slug, sync hooks, `--stale` — runs `retractRemovedTimelineEntries` for the page. `ExtractOpts.slugs?: string[]` enables incremental extract via `extractForSlugs()` (single combined links+timeline pass); the cycle path threads sync's `pagesAffected` through. Every per-slug extractor — `extractForSlugs` (the cycle's incremental pass) and the two sync hooks `extractLinksForSlugs` / `extractTimelineForSlugs` — resolves each requested slug through `resolveSlugRelPath`: the `buildSlugPathIndex(walkMarkdownFiles(dir))` index first, then — only on an index miss — the legacy `join(dir, slug + '.md')` existence check. The index is the primary because `pathToSlug` lowercases and slugifies, so a reconstructed path only finds files whose names are already slugs, and every other file looked deleted and was skipped in silence; the legacy fallback stays because sync ADMITS files the walker never emits (`_`-prefixed names, dot-dirs waived via `sync.include_hidden`) and those slugs still round-trip to their real path — without it such a page imports with no edges. On a slug collision the index prefers the file whose name IS the slug (else the first walked entry), so resolution never depends on directory-read order. The per-slug extractors reconcile like `put_page`: each page's own markdown-derived links are replaced through `replacePageFileLinks` (`src/core/link-reconciliation.ts`, `replaceDerivedLinks` with `preserveExisting`; other producers survive, a page with no row counts as processed with no links, and a failed replacement is reported on stderr and leaves the page stale), and `retractRemovedTimelineEntries` (`src/core/timeline-extract.ts`) deletes the non-event rows whose (date, source, summary) any stored `page_versions` text of the page produced (under either timeline parser) and its current text no longer does; rows no version produced (enrichment, meeting fan-out, `--infer-dates` anchors) are kept, and the version scan only runs when the page holds a row the current text does not produce. `gbrain extract timeline --prune-orphans [--source-id] [--dry-run] [--json]` (`pruneTimelineOrphans`) runs that reconciliation over every page with timeline rows, without inserting — the one-time prune for rows orphaned while extraction was insert-only (managed brains retract each page's rows in a page-locked `withCoordinatedWrite` transaction; these rows are removals, so `gbrain repair timeline` / `timeline_history` exclude them; pinned in `test/persistence-managed-lifecycle.test.ts`); the read-only `timeline_orphans` doctor check (`src/commands/doctor/checks/timeline-orphans.ts`) samples 500 pages and points at it. Pinned by `test/timeline-reconcile-all-paths.test.ts`. `loadSlugAliasTargets` adds renamed pages' old slugs (`slug_aliases`) to `allSlugs` so links written before a rename resolve to the current slug. `extractLinksForSlugs` reads the requested files first, then loads page metadata only for those pages and their link endpoints (`fileLinkOwnership(engine, sourceId, { slugs })`); the unscoped whole-brain load happens only when a DB meeting or attendance origin needs `replaceFileLinks`. Both return `ExtractForSlugsResult { created, processed, errors? }`; `errors` names pages whose read or write failed, and sync reports them as `extract_error` (stderr line plus the `SyncResult` field) instead of swallowing them. `processed` is the subset actually read, and the shared `slugsSafeToStamp(links, timeline)` intersection is what every caller may stamp. Stamping the full requested set marks a silently-skipped page fresh and hides it from `extract --stale` permanently. All three call sites (`src/commands/sync.ts`, `src/core/github-source.ts`, `src/core/google/google-source.ts`) stamp the intersection. `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`; on a managed brain it hands the sweep to `extractManagedStaleLinks` in `src/core/persistence/links-maintenance.ts` for every caller, CLI, cycle, jobs and maintain, and a live PGLite owner runs it through `src/commands/extract-stale-delegate.ts`) — incremental DB-source link+timeline sweep over pages whose `pages.links_extracted_at` watermark is stale, then the mention pass ([entity recall](entity-recall.md)). Embedded callers (the cycle) pass `quiet: true` so the helper writes nothing to stdout, including its JSON result. In `jsonMode` every fs path, `extractForSlugs` included, reports a dropped flush as a `{event:'batch_error'}` stderr line rather than going silent. 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 `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). `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. On a managed-persistence brain each page publishes its derived links (`prepareAutomaticLinks`), the coordinator's unrecorded canonical timeline tuples (`unrecordedCanonicalTimeline`, insert-only) and its watermark in one revision-bound `withCoordinatedWrite` transaction; a page edited since the read is skipped and stays stale. Tests: `test/extract-stale-managed.test.ts`, `test/persistence-managed-lifecycle.test.ts`. 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`. Fresh-install schema in `src/schema.sql` (both generated blobs follow via `bun run build:schema`) + `REQUIRED_BOOTSTRAP_COVERAGE`. `src/commands/doctor/checks/extraction-sync.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`; pages whose attendance marker (`links_attendance_blocked_revision`, migration v180) equals their current `knowledge_revision` are left out of the lag count and reported as `details.attendance_blocked` (both `extract --stale` sweeps set the marker on an unresolved-attendance skip; pre-v180 brains fall back to the unfiltered count); strictly a SQL COUNT (safe on remote/thin-client). `src/commands/sync.ts` carries `--no-extract` (threaded through single-source + `--all` + `syncOneSource`), stamps `links_extracted_at` at the inline-extract call site for the slugs the extractors actually read, 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` lists `'extract.stale'` in `BATCH_AUDIT_SITES`; `src/core/doctor-categories.ts` lists `links_extraction_lag` in `BRAIN_CHECK_NAMES`. Pinned by `test/extract-stale.test.ts` (incl. edited-after-stamp + 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 case in `test/extract-stale.test.ts` injects a µs `updated_at`, runs `--stale`, and asserts the lag is 0 and stays 0.
- `src/commands/extract-timeline-db.ts` — the `extract timeline --source db` walk (`extractTimelineFromDB`), also used by `runExtractCore` for a timeline-only pass on a managed brain. Managed brains (every fresh `gbrain init` brain) publish each page that needs a change as one database-only maintenance request (`managed_maintenance_timeline_extract`, owner-checked by `maintenancePreflight`, request id bound to the page revision; `prepareTimelineExtract` is dispatched from `prepareMaintenanceMutation`): under the page lock it retracts rows the current text no longer produces and inserts the canonical tuples with no stored row (`unrecordedCanonicalTimeline`); a page with nothing to change admits no request, and a page edited meanwhile is skipped. Unmanaged brains batch raw inserts. A refused write prints `refused: <code>; nothing written; existing timeline rows are untouched`, the summary counts written versus refused (a request still pending counts as not confirmed) with `gbrain extract --stale` and the `write-refusals.md#extract-timeline-refused` anchor, and the CLI exits 1 (the `extract` job throws). Pinned by `test/extract-timeline-db-managed.test.ts`, `test/e2e/extract-timeline-db-postgres.test.ts`, `test/fresh-init-db-extract.serial.test.ts`.
- Extract CLI help — `EXTRACT_HELP` in `src/commands/extract.ts` is the canonical detailed usage shared by `--help` and invalid-subcommand errors. `src/cli.ts` routes `extract --help` before engine connection so help works on unconfigured installs; the top-level TOOLS block advertises every mode-specific flag. Pinned by `test/cli-help-discoverability.test.ts`.
diff --git a/docs/architecture/key-files/commands-4-continued.md b/docs/architecture/key-files/commands-4-continued.md
index 713c44e15c..67367ae65f 100644
--- a/docs/architecture/key-files/commands-4-continued.md
+++ b/docs/architecture/key-files/commands-4-continued.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/recall.ts` — the `gbrain recall` CLI (facts-first by default; local engine or thin-client). Optional `--budget-policy facts_first|query_first` routes a one-shot read through the shared operation, forwarding fact filters and using remote recall on thin clients. Enum validation uses the shared operation definition; option order does not affect budget parsing. Only query-first with a nonblank query preserves numeric fractions until server packing; omitted/explicit facts-first keeps legacy integer parsing. The new option rejects watch/cursor/rollup/as-context combinations rather than silently ignoring them. Opt-in selector failures use stamped v1 errors; JSON mode emits structured local and remote errors on stdout with a nonzero exit, preserving remote read-error details without requiring a mutation receipt. Omitted-policy validation and fallback remain unchanged. Entity→text fallback: a bare positional without verb options is entity-first, but when the entity arm matches ZERO facts (and no `--grep`/`--supersessions`/`--session-id` narrows the read), the query retries as SQL-level fact-text grep with a stderr note. One predicate and note formatter are shared by the local path and thin-client mirror; explicit grep callers keep exact semantics. `--since` composes with entity and session in one query before LIMIT, on event time unless `--since-last-run`. Local `--grep` is passed to every engine arm (ILIKE with escaped metacharacters, before LIMIT); only `--supersessions` keeps the client-side filter. Pinned by `test/recall-grep-local-cli.test.ts`. Pinned by `test/facts-recall-since-composition.test.ts`, `test/recall-budget-policy-transports.test.ts`, `test/recall-budget-policy-thin-cli.test.ts`, and `test/recall-budget-policy-thin.serial.test.ts`.
-- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.
+- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:` (written via `engine.setPageAliases`) and, for linkable entity pages, rewrites the derived title-subject and declared rows (`writeDerivedAliases`, coordinated on managed brains). Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.
- `src/commands/projections.ts` + `src/cli/commands/projections.ts` — `gbrain projections drain [--limit <n>] [--json]` (#5401). Trusted-local CLI, not an operation. Rebuilds queued Markdown and code projections in-process in batches of up to 100 until every row queued at the run start has been tried once (it waits for the database clock to pass the run start, so a page that fails in the run is not retried); `--limit` caps pages tried. Exit 0 (nothing tried failed), 1 (a page failed; each failure prints source, slug, reason and next action), 2 (did not run: bad usage, or `projection_owner_resident` when a process holds the selected PGLite brain, checked with `persistenceConfigForBrain` before any engine opens, so a mounted PGLite brain on a Postgres host is refused too). On Postgres it runs beside a resident owner (per-page locks plus the revision recheck). `residentDrainSteps` gives the stop-drain-restart commands for the serve service, autopilot and a manual serve, shared with doctor. Tests: `projection-drain.test.ts` (both engines via `test/e2e/projection-drain-postgres.test.ts`), `projections-drain-cli.serial.test.ts`.
- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). Consent (C2): the cost preview feeds `consentGate` (effect `paid`); `--yes`, `--max-cost <usd>`, a preapproval or tokenmax authorize it, otherwise exit 3 with the consent payload. Without a user cap the run gets the derived cap, except under tokenmax (`tokenmaxUncappedEnv`: stays uncapped); `--max-cost off` is the explicit uncapped choice. The owner-delegated path asks the same way (default cap). Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source). --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index bbfed08f5c..1bfce15ae2 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -34,7 +34,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.
-- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`). Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`.
+- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`.
- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`.
- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index dc2a68ff38..bbdbd1b43c 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -11,6 +11,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.
-- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, canonical entity types (`person`, `company`, `organization`, `entity`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints.
+- `src/core/verbs/entity-card.ts` — `buildEntityCard(engine, sourceId, name, {remote})`: the zero-LLM sub-100ms card behind the `entity` verb. Resolution reuses the Retrieval Reflex precision arms (alias > exact slug > exact title > slug-suffix; exact-slug candidates include the RAW input because slugify flattens slashes in namespaced slugs). Within exact-title collisions, linkable entity types (the source pack's set, `mentions/policy.ts`) outrank note/conversation containers, then GREATEST(updated_at, last_retrieved_at) breaks same-shape ties; a lone non-entity exact-title page remains a valid fallback. Per-arm degradation: a pre-page_aliases brain still resolves via arm 2 (aka returns empty, never throws). Card assembly is a parallel Promise.all of depth-1 indexed reads (page row, alias reverse lookup, getLinks+getBacklinks mentions-excluded cap 10, getBacklinkCounts, getTimeline(5), listFactsByEntity world-only-when-remote); deliberately NOT the recursive-CTE traversePaths — the card is a latency contract (CI gate: test/entity-card-perf.slow.test.ts, p99 < 100ms × GBRAIN_PERF_BUDGET_MULTIPLIER + 50× getPage-p50 ratio guard on a 20K corpus). `summary` runs through the exported `safeSynopsis` (the get_page fence boundary). Miss → keyword near-miss suggestions with create_safety hints. With `includeReferences` (the `entity` verb only; context_pack and delta leave it off) the card adds `referenced_by_count`, `referenced_by` groups with `next` continuations (`requires_surface: 'starter'` on a verbs ceiling) and `coverage`, and a miss carries `coverage` (see [entity recall](entity-recall.md)).
- `src/core/verbs/usage-log.ts` — observability sidecar: one JSONL line per verb call at `~/.gbrain/integrations/memory-verbs/usage.jsonl` (gbrainPath — GBRAIN_HOME honored; `brainId()` = the resolved gbrain home). LOCAL ONLY, never uploaded, stats-only (lock-free 10MB rotation may drop lines; O_APPEND line-atomic, best-effort on Windows). `logVerbUsage` is fire-and-forget (never awaited, never throws); written from the DISPATCH layer so param-validation failures count. `readVerbUsage`/`earliestVerbUsageTs` feed `gbrain protocol stats` (incl. measured TTHW vs the init-stamped `protocol_installed_at`) and the doctor `memory_verbs_usage` check.
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
new file mode 100644
index 0000000000..b3ddcbc15b
--- /dev/null
+++ b/docs/architecture/key-files/entity-recall.md
@@ -0,0 +1,19 @@
+# Key files — entity recall (mention index)
+
+The mention index links every page that names an entity (by title, title
+subject, frontmatter alias or declared code) to that entity page, keeps the
+links current from `gbrain extract --stale`, and serves them on the `entity`
+card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
+
+- `src/core/mentions/policy.ts` — the one linkable-type resolver. `linkableTypesFor(pack, policy)`: `person`, `company`, `organization`, `entity` (`ALWAYS_LINKABLE_TYPES`, never removable) plus every pack type with `primitive: entity` and its type aliases (`product` excluded), adjusted by `mentions.entity_types` (`+type`/`type` adds, `-type` removes). `readMentionPolicy` reads `auto_link`, `mentions.auto_link`, `mentions.entity_types`, `mentions.ignore` (JSON array or comma list, `parseNameList`). `canonicalTypeOf` / `typeAliasPairs` map a stored type through the pack's type aliases (`untyped` for none); pairs are bound as two `text[]`. `loadSourcePack(engine, sourceId, {strict})` returns null on a resolution failure unless strict. Tests: `test/mentions-policy-aliases.test.ts`.
+- `src/core/mentions/aliases.ts` — derived names of an entity page. `titleSubject` (text after the last `: `), `declaredNames` (the `account code` / `also known as` / `a.k.a.` / `aka` / `short name` / `ticker` / `code name` parser shared with search's `aliasDeclarations`), `deriveEntityAliases` (subject `origin='subject'`, declarations `origin='declared'`, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`). `aliasRejection`: under 4 characters, a generic word, or the first word of the page's own multi-word name. Rejections are returned for explain. Tests: `test/mentions-policy-aliases.test.ts`.
+- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list) marks every page due; `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, pending count and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.
+- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (due pages and newest `last_pass_at`, for `--dry-run`, doctor `links_extraction_lag` and post-upgrade), `linkPhaseDeadline` (a budgeted sweep gives link work half its budget while mention-due pages exist), `formatMentionSummary`, `mentionJsonFields`.
+- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.
+- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. Tests: `test/mentions-card-backlinks.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate).
+- `src/core/mentions/upgrade-notice.ts` — `gbrain post-upgrade` prints an `[AGENT]` block naming `gbrain extract --stale --catch-up` with a time estimate (`MENTION_PASS_PAGES_PER_SECOND`) while mention-due pages exist.
+- `src/core/ops/backlinks-paged.ts` — `get_backlinks`' `type` / `group` / `limit` / `cursor`. With none, `ops/links.ts` returns the legacy `Link[]`. `group: "page"` → `{rows, total, truncated, cursor, coverage}` (target = the first source in scope holding the slug; referrers from the read scope). Array mode filters by referrer type and cuts at `limit` with a `listing_truncated` notice naming the paged call. `limit` outside 1..500, a foreign cursor, or an unknown type (not a pack type, alias, observed referrer type or `untyped`) is `invalid_params` naming the valid values.
+- `src/commands/extract-mentions-explain.ts` — `gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]` (dispatched from `extract-explain.ts`): the matched entries with origin and case flag, or one reason code (`ambiguous_first_word`, `below_min_length`, `generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`, `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`, `not_a_known_name`); only `pending` names a sweep. Tests: `test/mentions-explain.test.ts`.
+- `src/core/schema-migrations/v201-entity-mention-index.ts` — additive: `page_aliases.origin` (`frontmatter` default, `declared`, `subject`), `case_sensitive`, `alias_text`, unique key `(source_id, alias_norm, slug, origin)`; tables `page_mention_state`, `mention_gazetteer_entries`, `mention_index_status` (RLS on when the role bypasses RLS). `GUARDED_TABLE_COLUMNS` lists the new `page_aliases` columns.
+
+Alias readers apply precedence frontmatter > declared > subject per source, and a derived alias never answers for another live page's exact title (`readAliases` in `src/core/search/read-enrichment.ts`, shared by both engines' `resolveAliases`), so `resolveEntitySlug`, the retrieval reflex, the alias hop, intent weights and `search-diagnose` rank an exact title first. `buildGazetteer` (`src/core/by-mention.ts`) applies the same precedence, drops an alias claimed by two pages at its best origin, yields to a same-source title, drops a single-word alias equal to the first word of another multi-word entity name, applies the generic-word list to every single-word name, and carries `caseTokens` for case-sensitive entries; `opts.dropped` records every dropped name with its reason.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index cab0f99526..184817e988 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -22,7 +22,7 @@
- **`src/core/persistence/sync-holds.ts`** + **`sync-screen.ts`** + **`sync-blobs.ts`** — Git holds (#5988). One `op_checkpoints` row per held file (`sync-hold`, fingerprint `source:incarnation:path`) plus a per-source `sync-hold-summary` row (`count`, and `stale`: holds whose page exists); `writeGitHold` / `clearGitHold` lock the summary row and are conditional on the writing run's discovery time (`observed_at`), so an older run never replaces or clears a newer hold. Managed and legacy sync write the same rows; `readGitSourceHolds` (current incarnation only) feeds `retry-held` and legacy sync, and `readGitHoldListing` (count from the summary row, rows limited per source in SQL) feeds `sources status`, never `readAllSourceHolds`. `recordSyncConversion` logs each blocked request a managed run converted in place (`sync-conversions`, newest 20 per source, in the transaction that saves the converted cursor); `sources status` shows the newest 5. `gitHoldItem` gives every surface code, reason, key, line, location-only message, `fix` Action and `docs` anchor. Policy keys: `sync.holds` (`hold`/`fail`), `sync.hold_cap` (detail shown, default 500), `sync.hold_escalate_count` (50), `sync.hold_escalate_pct` (5, from 40 screened imports), `sync.parser_regression` (`stop`/`hold`). `screenFrozenImport` turns a refusal into a hold, or throws `sync_parser_regression` only when `sync-import-provenance` proves a validating gbrain imported the same bytes. `sync-blobs.ts` reads blob ids/sizes with chunked `ls-tree -l` and contents with `cat-file --batch`. `held-reads.ts` is the read side: `get_page.file_held`, `stale` on search/query hits and the `held_files` retrieval meta and notice, from one lookup by page id (`op_checkpoints_sync_hold_page_idx`, migration v200) and one summary read per call, cached per request; remote callers get codes and counts, never paths, and a fix addressed to the brain host operator. Tests: `test/sync-holds-store.test.ts`, `test/persistence-sync-holds.test.ts`, `test/sync-all-hold-notes.test.ts`, `test/held-read-signals.test.ts`.
- **`src/core/persistence/file-repair.ts`** — `managed_file_repair` (#5988), the owner-internal `put_page` kind `gbrain repair frontmatter --apply` submits (accepted only from the trusted local CLI with `managedFileImport`; MCP is refused by the reserved-field gate, remote authority by the preparer). The preparer confines the path (`isWriteTargetContained` plus a component-wise `lstat` walk, no symlinks), requires the file's sha256 to equal the previewed `beforeHash` (`changed_since_preview` otherwise), recomputes `prepareRepairPublication` (the `screenSyncImport` + `importFromContent` preparation a managed sync import gets) and refuses a different result digest or a canonical overlay. It publishes the exact bytes as `file` (`expectedBeforeHash` = previewed hash; no `file_database_drift` check), applies the import (a held new file creates its page, a `renameFrom` moves the page with `updateSlug`), clears the Git hold and records `sync-import-provenance` in the same transaction; the file write queues the Git target effect. Tests: `test/repair-frontmatter.test.ts`.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. A filename-derived slug mismatch is accepted on every platform only when the page's stored canonical path is this file and the parsed slug is that page's slug; a different declared slug still refuses. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Markdown imports pass `screenSyncImport` (the already-published working-tree exemption, then `screenImportContent` with the expected slug and recorded-origin exemption), the same screen the freeze-time hold screen runs, so a file is held exactly when publication would refuse it. Each import, deletion and no-op apply clears the path's Git hold (`holdObservedAt`), the checkpoint clears `releasedHolds` and ignores `supersededRequests` (failed content refusals the run converted in place), and every Markdown import records `sync-import-provenance` (raw sha256, blob, gbrain version, quoting recoveries) and reports `recovered_frontmatter` / `comment_value` in its outcome. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
-- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
+- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` (then the mention pass unless `mentions: false`, which sync passes) derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
- **`src/core/persistence/sync-authority.ts`** — trusted CLI or original remote generic job authority; rejects stdio bulk privilege promotion and runtime option expansion, intersects original grants with current principal/source policy.
- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
diff --git a/docs/guides/entity-recall.md b/docs/guides/entity-recall.md
new file mode 100644
index 0000000000..4227c9e704
--- /dev/null
+++ b/docs/guides/entity-recall.md
@@ -0,0 +1,188 @@
+# Entity recall: everything the brain says about an account
+
+GBrain links every page that names an entity to that entity's page: by its
+title, by the subject of a record title (`CRM record: Acme Example` → "Acme
+Example"), by a frontmatter alias, or by a code the page declares (`Account
+code: ACMX`). The `entity` card then lists those pages grouped by type, newest
+first, with a short preview, and `get_backlinks` pages through the rest. An
+agent briefing on an account sees all of its tickets, meetings and mail
+instead of whichever few a search ranks first.
+
+**Say to your agent:** *"brief me on the Acme Example account"* —
+*"list every open ticket for ACMX"* — *"why isn't this meeting linked to Acme?"*
+
+## Try it (keyless, under a minute)
+
+Nothing here calls a model or needs an API key.
+
+```bash
+mkdir -p brain/crm brain/tickets brain/meetings
+cat > brain/crm/acme-example.md <<'EOF'
+---
+type: crm
+title: "CRM record: Acme Example"
+---
+Account code: ACMX
+Owner: Alice Example
+EOF
+for i in 1 2 3; do cat > brain/tickets/ticket-$i.md <<EOF
+---
+type: ticket
+title: "Ticket $i"
+date: 2026-0$i-15
+---
+Customer: ACMX Opened: 2026-0$i-15
+Status: $([ $i = 3 ] && echo Open || echo Closed)
+EOF
+done
+cat > brain/meetings/2026-04-03.md <<'EOF'
+---
+type: meeting
+title: "Meeting: Acme Example renewal prep"
+---
+Renewal blocker: the security review. acmx in lowercase is not the code.
+EOF
+
+gbrain init --pglite --no-embedding
+gbrain import brain --no-embed
+gbrain extract --stale
+gbrain entity ACMX
+```
+
+`gbrain extract --stale` reports `Mentions: 4 link(s) added, 0 removed from 5 page(s).` and the card reads:
+
+```
+CRM record: Acme Example (crm/acme-example) [crm]
+ Account code: ACMX
+ aka: acme example, acmx
+ backlinks: 0 | active facts: 0
+ referenced by 4 page(s):
+ meeting (1): meetings/2026-04-03
+ ticket (3): tickets/ticket-3, tickets/ticket-2, tickets/ticket-1
+```
+
+Over MCP (or `gbrain entity ACMX --json`) the card carries the rows:
+
+```json
+"referenced_by_count": 4,
+"referenced_by": [
+ { "canonical_type": "ticket", "total": 3, "rows": [
+ { "slug": "tickets/ticket-3", "title": "Ticket 3", "type": "ticket", "canonical_type": "ticket",
+ "date": "2026-03-15T00:00:00.000000Z", "date_source": "date",
+ "preview": "Customer: ACMX Opened: 2026-03-15 Status: Open" } ] }
+],
+"coverage": { "state": "complete", "pending_pages": 0, "last_pass_at": "2026-10-04T18:59:54.807Z" }
+```
+
+`backlink_count` counts explicit links only; `referenced_by_count` counts every
+page that links here, mentions included. A preview is a hint, not evidence:
+fetch the page before stating a status or a date.
+
+## Paging a big group
+
+A group shows at most 10 rows and a card at most 50. A truncated group carries
+the exact call for the rest:
+
+```json
+"next": { "tool": "get_backlinks", "arguments": { "slug": "crm/acme-example", "source_id": "default",
+ "type": "ticket", "group": "page", "limit": 50, "cursor": "WyIy..." } }
+```
+
+```bash
+gbrain backlinks crm/acme-example --type ticket --group page --limit 2
+```
+
+returns `{rows, total, truncated, cursor, coverage}`, newest first by
+`(date, source, slug)`; pass `cursor` back to continue. Without `group`,
+`get_backlinks` returns the link rows it always did (`type` and `limit` filter
+them). `type` takes a schema-pack type, one of its aliases (`crm` and
+`account` both mean the account group), a type seen on a referring page
+(`ticket`), or `untyped`.
+
+## Coverage
+
+`coverage.state` says whether the list can be trusted as complete for names the
+brain recognizes in your source:
+
+| State | Meaning | What to do |
+|---|---|---|
+| `complete` | Every page is scanned at its current content. | Nothing. |
+| `pending` | Pages were written since the last pass, or no pass ran yet. | `gbrain extract --stale --catch-up` (free). |
+| `failed` | The last pass could not build the name index. | Read `gbrain doctor --only links_extraction_lag --json`, fix, rerun. |
+| `disabled` | `auto_link` or `mentions.auto_link` is `false`. | The user's choice; `gbrain config set mentions.auto_link true` reverses it. |
+| `type_not_linkable` | Nothing links to this page type by name. | `gbrain config set mentions.entity_types +<type>`. |
+
+Any state but `complete` adds a `[gbrain notice mention_index]` block, so an
+agent never reads a short list as "nothing else exists".
+
+## Make your records findable by name
+
+- Give a record page a linkable type. Under the default `gbrain-base-v2` pack
+ those are `person`, `company` (and its aliases such as `startup`), `account`
+ (alias `crm`), `organization` and `entity`. Other packs add their own
+ `primitive: entity` types.
+- Put the name in the title, or after a prefix: `CRM record: Acme Example`.
+- Declare codes in the body: `Account code: ACMX`, `also known as`, `aka`,
+ `short name`, `ticker`, `code name`. A one-word code links only as written
+ (`ACMX`, not `acmx`).
+- Or list names in frontmatter `aliases: [Acme, Acme Inc]`.
+
+Names are never linked when they are shorter than 4 characters, a generic word
+("Will", "Team"), the first word of a longer entity name ("Quormiro" alone when
+"Quormiro Capital" and "Quormiro Labs" both exist), claimed by two pages, or
+inside a private facts or takes fence. Contracts and other non-entity pages
+that repeat a code do not claim it.
+
+## When a name does not link
+
+```bash
+gbrain extract mentions --explain acmx --page meetings/2026-04-03
+```
+
+```
+acmx (source default): case_mismatch
+ entry: "ACMX" → crm/acme-example (declared, case-sensitive)
+ page meetings/2026-04-03: linked
+ This alias is case-sensitive (a single-word declared code) and the text uses a different case.
+```
+
+The reason codes are `ambiguous_first_word`, `below_min_length`,
+`generic_token`, `alias_collision`, `case_mismatch`, `type_not_linkable`,
+`linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config` and
+`not_a_known_name`. Only `pending` is fixed by running `gbrain extract --stale`.
+
+## Settings
+
+| Key | Default | Effect |
+|---|---|---|
+| `mentions.auto_link` | `true` | `false` removes mention links and derived names on the next sweep; `true` relinks everything on the next sweep. `auto_link=false` also turns it off. |
+| `mentions.entity_types` | none | `+type` adds a linkable type, `-type` removes one (person, company, organization and entity always stay). |
+| `mentions.ignore` | none | Names never linked, comma-separated or a JSON array. |
+| frontmatter `mention_ignore: [names]` | none | Names not linked from that one page. |
+
+## How it stays current
+
+`gbrain extract --stale` (and the autopilot cycle, and the managed-brain stale
+path) runs the mention pass after link extraction. It rescans only pages whose
+content changed, plus pages a new, removed or renamed entity name can affect,
+and it never reruns link or timeline extraction. Sync's own inline extraction
+stays link-only. A budgeted cycle gives the mention pass half its time while
+pages are due. `gbrain extract --stale --dry-run` shows `mention_due_pages` and
+the last pass time.
+
+## Upgrading an existing brain
+
+| Brain | What changes |
+|---|---|
+| `gbrain-base-v2` (the `init` default) | `account` (alias `crm`) is a new linkable type; CRM rows link by name and code. |
+| Legacy `gbrain-base` | Its entity types (person, company, yc, civic, ...) link; no `account` type. Switch packs or add types with `mentions.entity_types`. |
+| Custom pack | Every type marked `primitive: entity`, plus its aliases, links. |
+
+After upgrading, `gbrain post-upgrade` names the one command to run:
+
+```bash
+gbrain extract --stale --catch-up
+```
+
+It reads every page once (free, no model calls). The pass also runs from
+autopilot cycles if you skip it.
diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index 548221f732..92c383673f 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -287,8 +287,11 @@ Optional response fields; clients must ignore any they do not know.
One known person/company/project card. NEVER errors on a miss.
Resolution (frozen precedence): alias > exact slug > exact title > slug-suffix.
-When multiple pages share an exact title, canonical entity types (`person`,
-`company`, `organization`, `entity`) outrank note/conversation containers;
+A derived alias (a title subject such as `X` in `CRM record: X`, or a code the
+page declares) never answers for another live page's exact title. When
+multiple pages share an exact title, linkable entity types (the source pack's
+entity types, at least `person`, `company`, `organization`, `entity`) outrank
+note/conversation containers;
most-recently-touched breaks ties within the same match shape. A non-entity
exact-title page remains a valid fallback. Multi-hit ⇒ best match's card +
runners-up in `suggestions`. Miss ⇒ `found: false` + keyword near-misses with
@@ -301,6 +304,29 @@ backlink_count, active_fact_count }`.
- `summary` passes the same privacy fences as `get_page` (takes + private
facts stripped); remote callers never see private facts in the card.
+
+#### entity references and coverage (additive)
+
+The `entity` verb adds three optional card fields (ambient callers,
+`context_pack` and `delta`, do not compute them):
+
+- `referenced_by_count` — distinct pages with any inbound link to the entity,
+ every link source included (`backlink_count` keeps excluding mentions).
+- `referenced_by[]` — those pages grouped by pack-canonical type:
+ `{ canonical_type, total, rows[], next? }`, groups ordered by their newest
+ row. Each row: `{ slug, title, type, canonical_type, date, date_source,
+ preview }`; `date` is `COALESCE(effective_date, updated_at)`, rows newest
+ first, at most 10 per group and 50 per card. `preview` is the first 160
+ characters of body text with private fences stripped; it is not evidence.
+ A truncated group's `next` is `{ tool: "get_backlinks", arguments: { slug,
+ source_id, type, group: "page", limit, cursor } }` and returns exactly the
+ rest of the group; on a verbs-only connection it carries
+ `requires_surface: "starter"`.
+- `coverage` — `{ state, pending_pages, last_pass_at, degraded? }` with
+ `state` one of `complete`, `pending`, `disabled`, `type_not_linkable`,
+ `failed`. A miss carries `coverage` at the top level. Any state but
+ `complete` sets `degraded: true` and adds a `[gbrain notice mention_index]`
+ block. Coverage means recognized names within the caller's source.
- `open_threads` (best-effort in v1): active commitment-kind facts + timeline
entries from the last 90 days, capped at 3.
diff --git a/llms-full.txt b/llms-full.txt
index 57bab91e74..1dae5ee000 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -4755,7 +4755,7 @@ flowchart LR
**Two organizational axes (brain ⊥ source).** A *brain* is a database (your personal brain, a team mount you joined). A *source* is a repo inside that brain (wiki, gstack, an essay, a knowledge base). Routing lives in `.gbrain-source` dotfiles and resolves via a documented 6-tier precedence chain. Full diagrams in [`docs/architecture/brains-and-sources.md`](docs/architecture/brains-and-sources.md).
-**Why the graph matters.** Vector search finds semantic similarity; graph retrieval follows stored relationships. Extracted edges are evidence to inspect, not proof that a relationship is true. Graph freshness depends on the write path and maintenance described in [memory boundaries](docs/guides/memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Deep dive: [retrieval architecture](docs/architecture/RETRIEVAL.md).
+**Why the graph matters.** Vector search finds similar text; graph retrieval follows stored relationships. Extracted edges are evidence to inspect, not proof that a relationship is true. Graph freshness depends on the write path and maintenance described in [memory boundaries](docs/guides/memory-boundaries.md#page-writes-and-the-graph-are-separate-outcomes). Deep dive: [retrieval architecture](docs/architecture/RETRIEVAL.md); [entity recall](docs/guides/entity-recall.md).
## Troubleshooting
@@ -8789,8 +8789,11 @@ Optional response fields; clients must ignore any they do not know.
One known person/company/project card. NEVER errors on a miss.
Resolution (frozen precedence): alias > exact slug > exact title > slug-suffix.
-When multiple pages share an exact title, canonical entity types (`person`,
-`company`, `organization`, `entity`) outrank note/conversation containers;
+A derived alias (a title subject such as `X` in `CRM record: X`, or a code the
+page declares) never answers for another live page's exact title. When
+multiple pages share an exact title, linkable entity types (the source pack's
+entity types, at least `person`, `company`, `organization`, `entity`) outrank
+note/conversation containers;
most-recently-touched breaks ties within the same match shape. A non-entity
exact-title page remains a valid fallback. Multi-hit ⇒ best match's card +
runners-up in `suggestions`. Miss ⇒ `found: false` + keyword near-misses with
@@ -8803,6 +8806,29 @@ backlink_count, active_fact_count }`.
- `summary` passes the same privacy fences as `get_page` (takes + private
facts stripped); remote callers never see private facts in the card.
+
+#### entity references and coverage (additive)
+
+The `entity` verb adds three optional card fields (ambient callers,
+`context_pack` and `delta`, do not compute them):
+
+- `referenced_by_count` — distinct pages with any inbound link to the entity,
+ every link source included (`backlink_count` keeps excluding mentions).
+- `referenced_by[]` — those pages grouped by pack-canonical type:
+ `{ canonical_type, total, rows[], next? }`, groups ordered by their newest
+ row. Each row: `{ slug, title, type, canonical_type, date, date_source,
+ preview }`; `date` is `COALESCE(effective_date, updated_at)`, rows newest
+ first, at most 10 per group and 50 per card. `preview` is the first 160
+ characters of body text with private fences stripped; it is not evidence.
+ A truncated group's `next` is `{ tool: "get_backlinks", arguments: { slug,
+ source_id, type, group: "page", limit, cursor } }` and returns exactly the
+ rest of the group; on a verbs-only connection it carries
+ `requires_surface: "starter"`.
+- `coverage` — `{ state, pending_pages, last_pass_at, degraded? }` with
+ `state` one of `complete`, `pending`, `disabled`, `type_not_linkable`,
+ `failed`. A miss carries `coverage` at the top level. Any state but
+ `complete` sets `degraded: true` and adds a `[gbrain notice mention_index]`
+ block. Coverage means recognized names within the caller's source.
- `open_threads` (best-effort in v1): active commitment-kind facts + timeline
entries from the last 90 days, capped at 3.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 3cf3086649..2be7980040 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index a91018fb95..79f685d4ad 100644
--- a/package.json
+++ b/package.json
@@ -212,7 +212,7 @@
"bun": ">=1.4.0"
},
"license": "MIT",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.56",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 533aa47a53..639f94b670 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 43c1351a75..f5ccd95a5d 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index f42eb7b0bf..55b377f223 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.48.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.61.1.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 45cc87ad3a..69048d7d96 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 042a7ecce9..7ff77df272 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.48.0",
+ "version": "0.61.1.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 0fcb73a8ce..094b7a9a8a 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.48.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.61.1.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index c7ea253562..736e438114 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.48.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.61.1.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/scripts/e2e-backend-matrix.txt b/scripts/e2e-backend-matrix.txt
index 5743eb9492..1c24e900f1 100644
--- a/scripts/e2e-backend-matrix.txt
+++ b/scripts/e2e-backend-matrix.txt
@@ -49,3 +49,4 @@ test/e2e/apply-migrations-orchestration-lock.test.ts
test/e2e/postgres-poisoned-connection.test.ts
test/e2e/write-attribution-postgres.test.ts
test/e2e/write-attribution-read-parity.test.ts
+test/e2e/mentions-parity.test.ts
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index 722f3dd6f3..f9b77b0ae1 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -24,6 +24,9 @@ const MIGRATION_WAVE_TESTS = [
];
export const E2E_TEST_MAP: Record<string, string[]> = {
+ // Entity mention index: pass, aliases, referrer query and coverage on Postgres.
+ "src/core/mentions/**": ["test/e2e/mentions-parity.test.ts"],
+ "src/core/ops/backlinks-paged.ts": ["test/e2e/mentions-parity.test.ts"],
// #5984: the env-gated wire-level SQL trace for the managed-sync catch-up bench.
"src/core/sql-trace.ts": ["test/e2e/sql-trace-postgres.test.ts"],
// Fix wave 8, Lane G: reindex auto-concurrency sizing (#5181).
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index c8d143f471..ec3131c79f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,12 +3,12 @@
# Raising a ceiling is a conscious, reviewer-visible act. Lower ceilings in
# the same commit as any peel (the guard fails on >50 lines of stale slack).
# Columns: path max_lines policy note
-src/cli.ts 3199 ratchet +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured)
+src/cli.ts 3201 ratchet +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage
src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)
src/commands/doctor.ts 667 ratchet +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 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 2541 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/)
src/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)
@@ -36,7 +36,7 @@ src/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0
src/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 refresh
src/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 read
src/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 1840 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); +2 entity mention index: mentions.auto_link, mentions.entity_types, mentions.ignore key rows (resolver in core/mentions/policy.ts)
src/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 env
src/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 option
src/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/skills/migrations/v0.61.1.0.md b/skills/migrations/v0.61.1.0.md
new file mode 100644
index 0000000000..683f9d7930
--- /dev/null
+++ b/skills/migrations/v0.61.1.0.md
@@ -0,0 +1,49 @@
+# Upgrade to v0.61.1.0: the brain links every page that names an entity
+
+`gbrain extract --stale` now links every page that names a person, company or
+account (by title, record-title subject, frontmatter alias or a declared code
+such as `Account code: ACMX`) to that page. The `entity` card lists those pages
+by type (`referenced_by`) with a `coverage` state, and `get_backlinks` pages
+through them (`group: "page"`). `gbrain-base-v2` gains an `account` page type
+(alias `crm`). Linking is free: no model calls.
+
+1. **Finish the upgrade.** `gbrain upgrade` runs it. To be sure, on the brain
+ host:
+ ```bash
+ gbrain apply-migrations --yes --no-autopilot-install
+ ```
+ Migration v201 adds columns to `page_aliases` and three small tables; no
+ existing row is rewritten. Restart every `gbrain serve`, autopilot and
+ worker.
+
+2. **Run the first mention pass.** `gbrain post-upgrade` prints an `[AGENT]`
+ line with the page count and an estimate while pages are due. Run it now
+ (free, resumable):
+ ```bash
+ gbrain extract --stale --catch-up
+ ```
+ Without it, autopilot cycles do the same work over several runs, and entity
+ cards report `coverage.state: "pending"` until then.
+
+3. **Verify.**
+ ```bash
+ gbrain extract --stale --dry-run --json # mention_due_pages: 0
+ gbrain entity "<an account or person name>"
+ ```
+
+4. **Tell the user about the off switch only if they ask, or if a name links
+ wrongly.** `gbrain extract mentions --explain <name> --page <slug>` says why
+ a name links or not. A wrong link is fixed by `mentions.ignore` (a name) or
+ frontmatter `mention_ignore` (one page); `gbrain config set
+ mentions.auto_link false` turns linking off and removes mention links on the
+ next sweep. These change the user's brain: ask before setting them.
+
+5. **Know the behavior changes.**
+ - `extract --stale` JSON adds `mention_*` fields; `stale_remaining` counts
+ link-stale pages plus mention-due pages.
+ - A derived alias (record-title subject or declared code) never answers for
+ another page's exact title, so `entity("Acme Example")` stays the company
+ page beside a `CRM record: Acme Example` page.
+ - Search's alias hop also resolves declared codes.
+
+Guide: `docs/guides/entity-recall.md`.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index ea8761ea35..34edd5f86b 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -165,6 +165,7 @@
"migrations/v0.60.47.0.md": "91a6015e3b85c6f2c8048680ee5873895ae2b1948bad8ba6cebce679c3ec7085",
"migrations/v0.60.5.0.md": "0d3ee19359a2740de08ac9ec388ddc15e7c72d663afe33832e1e54170528acab",
"migrations/v0.60.6.0.md": "1cbfca2c899e1348acbd61f0baa4c8e723b5283ff868c710c74e116c0cb6726e",
+ "migrations/v0.61.1.0.md": "e38f36739d1a704bb15cb2bcabfda420248d98dd78be42ad9f9102003554ffa7",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
"migrations/v0.8.0.md": "1919ff8b8f3680612ff888e7cfcc0d86ece5d5304ae19af4497bdf40b050561a",
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
diff --git a/src/cli.ts b/src/cli.ts
index ad39bb129f..387b10d3eb 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1757,7 +1757,7 @@ export function formatResult(
if (process.argv.includes('--json')) break;
const r = result as any;
if (!r.found) {
- const lines = [`No entity found. (${r.latency_ms}ms)`];
+ const lines = [`No entity found. (${r.latency_ms}ms)${r.coverage && r.coverage.state !== 'complete' ? ` Mention coverage: ${r.coverage.state}, ${r.coverage.pending_pages} page(s) pending.` : ''}`];
if (Array.isArray(r.suggestions) && r.suggestions.length) {
lines.push('Did you mean:');
for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title} [${s.create_safety}]`);
@@ -1780,6 +1780,8 @@ export function formatResult(
for (const e of c.edges) lines.push(` ${e.direction === 'out' ? '→' : '←'} ${e.type} ${e.slug}`);
}
lines.push(` backlinks: ${c.backlink_count} | active facts: ${c.active_fact_count}`);
+ if (c.referenced_by_count) lines.push(` referenced by ${c.referenced_by_count} page(s):`, ...c.referenced_by.map((g: any) => ` ${g.canonical_type} (${g.total}): ${g.rows.map((x: any) => x.slug).join(', ')}${g.next ? ', ...' : ''}`));
+ if (c.coverage && c.coverage.state !== 'complete') lines.push(` mention coverage: ${c.coverage.state}, ${c.coverage.pending_pages} page(s) pending`);
if (Array.isArray(r.suggestions) && r.suggestions.length) {
lines.push(' other matches:');
for (const s of r.suggestions) lines.push(` ${s.slug} — ${s.title}`);
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index bca0ce33bb..1d935ee1c2 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -14,6 +14,7 @@ import { lagFromContentMs, loadSyncFreshnessSources, resolveStalenessCeilingSeco
import { resolveEnvNumber, resolveHoursEnv, warnOnceForEnv } from '../../../core/env-number.ts';
import { CHUNKER_VERSION } from '../../../core/chunkers/code.ts';
import { LINK_EXTRACTOR_VERSION_TS } from '../../../core/link-extraction.ts';
+import { previewMentionPass } from '../../../core/mentions/stale.ts';
import { isUndefinedColumnError } from '../../../core/utils.ts';
import {
loadStorageConfig,
@@ -159,14 +160,18 @@ export async function checkLinksExtractionLag(
}
}
- const details = { total, stale, attendance_blocked: attendanceBlocked, pct: Number(pctStr), warn_pct: warnPct, fail_pct: failPct ?? null, source_id: sourceId ?? null };
+ // Entity mention index: pages the mention pass has not scanned at their current content.
+ const mention = await previewMentionPass(engine, sourceId).catch(() => null);
+ const mentionNote = mention?.due ? `; ${mention.due} page(s) await the mention pass (last pass: ${mention.last_pass_at ?? 'never'})` : '';
+ const details = { total, stale, attendance_blocked: attendanceBlocked, pct: Number(pctStr), warn_pct: warnPct, fail_pct: failPct ?? null, source_id: sourceId ?? null,
+ mention_due: mention?.due ?? null, mention_last_pass_at: mention?.last_pass_at ?? null };
if (failPct !== undefined && pct > failPct) {
- return { name, status: 'fail', message: `${stale}/${total} pages (${pctStr}%)${scope} need link/timeline extraction (> ${failPct}% fail threshold). ${fix}${blockedNote}`, details };
+ return { name, status: 'fail', message: `${stale}/${total} pages (${pctStr}%)${scope} need link/timeline extraction (> ${failPct}% fail threshold)${mentionNote}. ${fix}${blockedNote}`, details };
}
if (pct > warnPct) {
- return { name, status: 'warn', message: `${stale}/${total} pages (${pctStr}%)${scope} have un-extracted edges. ${fix}${blockedNote}`, details };
+ return { name, status: 'warn', message: `${stale}/${total} pages (${pctStr}%)${scope} have un-extracted edges${mentionNote}. ${fix}${blockedNote}`, details };
}
- return { name, status: 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}${blockedNote}`, details };
+ return { name, status: 'ok', message: `Extraction current: ${stale}/${total} pages (${pctStr}%) stale${scope}${mentionNote}${blockedNote}`, details };
} catch (e) {
// Pre-v112 brain: links_extracted_at column doesn't exist yet. Graceful OK
// (migration/bootstrap adds it; nothing to assess until then).
diff --git a/src/commands/doctor/checks/managed-guard.ts b/src/commands/doctor/checks/managed-guard.ts
index 31be987236..a5d9950d8d 100644
--- a/src/commands/doctor/checks/managed-guard.ts
+++ b/src/commands/doctor/checks/managed-guard.ts
@@ -19,7 +19,7 @@ export const GUARDED_TABLE_COLUMNS: Readonly<Record<string, readonly string[]>>
'title', 'type', 'updated_at'],
tags: ['id', 'page_id', 'tag', 'tag_source'],
slug_aliases: ['alias_slug', 'canonical_slug', 'created_at', 'id', 'notes', 'source_id'],
- page_aliases: ['alias_norm', 'created_at', 'id', 'slug', 'source_id'],
+ page_aliases: ['alias_norm', 'alias_text', 'case_sensitive', 'created_at', 'id', 'origin', 'slug', 'source_id'],
facts: ['claim_metric', 'claim_period', 'claim_unit', 'claim_value', 'confidence', 'consolidated_at', 'consolidated_into', 'context', 'created_at',
'dim_status', 'dimension', 'embedded_at', 'embedded_text_hash', 'embedding', 'embedding_model', 'entity_slug', 'event_type', 'expired_at', 'fact',
'id', 'kind', 'last_write_principal_id', 'last_write_principal_kind', 'last_write_request_id', 'last_written_at', 'notability', 'row_num', 'source',
diff --git a/src/commands/extract-explain.ts b/src/commands/extract-explain.ts
index 4c1d845594..3d46f091ff 100644
--- a/src/commands/extract-explain.ts
+++ b/src/commands/extract-explain.ts
@@ -26,6 +26,8 @@ export async function runExtractExplain(
engine: BrainEngine,
args: string[],
): Promise<void> {
+ // `gbrain extract mentions --explain <name|slug>` explains a mention, not an extractable kind.
+ if (args[0] === 'mentions') return (await import('./extract-mentions-explain.ts')).runExtractMentionsExplain(engine, args);
const json = args.includes('--json');
// --explain consumes the NEXT positional arg as the kind.
const explainIdx = args.indexOf('--explain');
diff --git a/src/commands/extract-mentions-explain.ts b/src/commands/extract-mentions-explain.ts
new file mode 100644
index 0000000000..cfa6b77126
--- /dev/null
+++ b/src/commands/extract-mentions-explain.ts
@@ -0,0 +1,146 @@
+/**
+ * `gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]`
+ *
+ * Says why a name does or does not link: the gazetteer entry it matches (with
+ * its origin: title, frontmatter, declared, subject) or the guard that dropped
+ * it, and, with `--page`, whether that page links to it now. Reason codes:
+ * `ambiguous_first_word`, `below_min_length`, `generic_token`,
+ * `alias_collision`, `case_mismatch`, `type_not_linkable`,
+ * `linking_disabled`, `pending`, `ignored_by_page`, `ignored_by_config`,
+ * `not_a_known_name`. Only `pending` suggests a sweep; a policy rejection
+ * names the setting or the page text that would change it.
+ */
+
+import type { BrainEngine } from '../core/engine.ts';
+import { buildGazetteer, findMentionedEntities, tokenizeTitle, type DroppedName, type GazetteerEntry } from '../core/by-mention.ts';
+import { isCrossSourceLinksEnabled } from '../core/link-extraction.ts';
+import { linkableTypesFor, loadSourcePack, parseNameList, readMentionPolicy } from '../core/mentions/policy.ts';
+import { deriveEntityAliases } from '../core/mentions/aliases.ts';
+import { MENTION_EXTRACTOR_VERSION } from '../core/mentions/pass.ts';
+
+export type ExplainReason = 'ambiguous_first_word' | 'below_min_length' | 'generic_token' | 'alias_collision' | 'case_mismatch'
+ | 'type_not_linkable' | 'linking_disabled' | 'pending' | 'ignored_by_page' | 'ignored_by_config' | 'not_a_known_name';
+
+export interface MentionExplanation {
+ query: string;
+ source_id: string;
+ /** Gazetteer entries the name (or slug) resolves to. */
+ entries: Array<{ name: string; slug: string; origin: string; case_sensitive: boolean }>;
+ /** Null when the name links (and, with --page, the page links to it). */
+ reason: ExplainReason | null;
+ message: string;
+ page?: { slug: string; linked: boolean };
+ next?: string;
+}
+
+const DROP_REASON: Record<DroppedName['reason'], ExplainReason> = {
+ below_min_length: 'below_min_length', generic_token: 'generic_token', alias_collision: 'alias_collision',
+ ambiguous_first_word: 'ambiguous_first_word', ignored: 'ignored_by_config', title_wins: 'alias_collision',
+};
+
+const MESSAGES: Record<ExplainReason, string> = {
+ ambiguous_first_word: 'This single word is the first word of a longer entity name in this source, so it never links alone; write the full name.',
+ below_min_length: 'Names shorter than 4 characters never link (too many false matches); write the full name or declare a longer alias.',
+ generic_token: 'This is a generic word (role, document or placeholder), so it never links as a single-word name.',
+ alias_collision: 'Another page in this source claims the same name (or it is another page\'s exact title), so the alias is dropped as ambiguous.',
+ case_mismatch: 'This alias is case-sensitive (a single-word declared code) and the text uses a different case.',
+ type_not_linkable: 'This page type is not a linkable entity type; add it with `gbrain config set mentions.entity_types +<type>`.',
+ linking_disabled: 'Mention linking is off (auto_link or mentions.auto_link is false).',
+ pending: 'The page changed or was never scanned since the last mention pass.',
+ ignored_by_page: 'The page lists this name in its frontmatter `mention_ignore`.',
+ ignored_by_config: 'The name is on an ignore list (`mentions.ignore` or the built-in ambiguous-brand list).',
+ not_a_known_name: 'No linkable entity page has this title, title subject or alias in this source.',
+};
+
+function done(base: Omit<MentionExplanation, 'reason' | 'message'>, reason: ExplainReason | null, message?: string): MentionExplanation {
+ return { ...base, reason, message: message ?? (reason ? MESSAGES[reason] : 'This name links.') };
+}
+
+export async function explainMention(engine: BrainEngine, query: string, opts: { sourceId?: string; page?: string } = {}): Promise<MentionExplanation> {
+ const sourceId = opts.sourceId ?? 'default';
+ const base: Omit<MentionExplanation, 'reason' | 'message'> = { query, source_id: sourceId, entries: [] };
+ const policy = await readMentionPolicy(engine);
+ if (!policy.enabled) return done(base, 'linking_disabled');
+ const dropped: DroppedName[] = [];
+ const gazetteer = await buildGazetteer(engine, { policy, dropped });
+ const all = [...gazetteer.values()].flat().filter(e => e.source_id === sourceId);
+ const view = (e: GazetteerEntry) => ({ name: e.caseTokens ? e.caseTokens.join(' ') : e.tokens.join(' '), slug: e.slug, origin: e.origin ?? 'title', case_sensitive: !!e.caseTokens });
+ const [asPage] = await engine.executeRaw<{ slug: string; type: string | null; title: string | null }>(
+ 'SELECT slug, type, title FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, query]);
+ const key = tokenizeTitle(query).join(' ');
+ const entries = asPage ? all.filter(e => e.slug === asPage.slug) : all.filter(e => e.tokens.join(' ') === key);
+ if (asPage && !entries.length) {
+ const types = linkableTypesFor(await loadSourcePack(engine, sourceId), policy);
+ if (!types.includes(asPage.type ?? '')) return done(base, 'type_not_linkable');
+ }
+ base.entries = entries.map(view);
+ if (!entries.length) {
+ const drop = dropped.find(d => d.source_id === sourceId && (asPage ? d.slug === asPage.slug : tokenizeTitle(d.name).join(' ') === key));
+ if (drop) return done(base, DROP_REASON[drop.reason]);
+ if (tokenizeTitle(query).length === 1 && all.some(e => e.tokens.length > 1 && e.tokens[0] === key)) return done(base, 'ambiguous_first_word');
+ const rejected = await rejectedDeclaration(engine, sourceId, query, policy);
+ return done(base, rejected ?? 'not_a_known_name');
+ }
+ if (!opts.page) {
+ const cased = entries.filter(e => e.caseTokens);
+ if (cased.length === entries.length && !cased.some(e => e.caseTokens!.join(' ') === query.normalize('NFC'))) return done(base, 'case_mismatch');
+ return done(base, null);
+ }
+ const [page] = await engine.executeRaw<{ id: number; slug: string; title: string | null; compiled_truth: string; timeline: string; mention_ignore: unknown; due: boolean }>(
+ `SELECT p.id, p.slug, p.title, p.compiled_truth, p.timeline, p.frontmatter->'mention_ignore' AS mention_ignore,
+ (s.page_id IS NULL OR s.mention_revision IS DISTINCT FROM p.knowledge_revision OR s.mention_version IS DISTINCT FROM $3) AS due
+ FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
+ WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [sourceId, opts.page, MENTION_EXTRACTOR_VERSION]);
+ if (!page) return done(base, 'not_a_known_name', `No live page ${opts.page} in source ${sourceId}.`);
+ const targets = new Set(entries.map(e => e.slug));
+ const ignore = parseNameList(page.mention_ignore);
+ if (ignore.some(n => tokenizeTitle(n).join(' ') === entries[0]!.tokens.join(' '))) return { ...done(base, 'ignored_by_page'), page: { slug: page.slug, linked: false } };
+ const text = `${page.title ?? ''}\n\n${page.compiled_truth}\n\n${page.timeline}`;
+ // Scan with this name's entries only (a slug query: every name of the page), so a link made through another name is not credited to this one.
+ const own: typeof gazetteer = new Map();
+ for (const e of entries) own.set(e.tokens[0]!, [...(own.get(e.tokens[0]!) ?? []), e]);
+ const found = findMentionedEntities(text, own, { fromSlug: page.slug, fromSourceId: sourceId,
+ allowCrossSource: await isCrossSourceLinksEnabled(engine), ignoreNames: ignore }).some(m => targets.has(m.slug));
+ const [link] = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM links l JOIN pages t ON t.id = l.to_page_id
+ WHERE l.from_page_id = $1 AND l.link_source = 'mentions' AND t.source_id = $2 AND t.slug = ANY($3::text[])`, [page.id, sourceId, [...targets]]);
+ const linked = Number(link?.n ?? 0) > 0;
+ const withPage = (r: ExplainReason | null, message?: string) => ({ ...done(base, r, message), page: { slug: page.slug, linked } });
+ if (found && !linked) return { ...withPage('pending'), next: 'gbrain extract --stale' };
+ if (found) return withPage(null, 'The page names this entity with this name and links to it.');
+ const cased = entries.find(e => e.caseTokens);
+ if (cased && text.toLowerCase().includes(cased.caseTokens!.join(' ').toLowerCase())) return withPage('case_mismatch');
+ if (page.due && linked) return { ...withPage('pending'), next: 'gbrain extract --stale' };
+ return withPage('not_a_known_name', linked ? 'The page links to this entity through another of its names, not this one.'
+ : 'The page text does not contain this name.');
+}
+
+/** A declaration the alias derivation rejected (e.g. a 3-character code), found on a linkable entity page. */
+async function rejectedDeclaration(engine: BrainEngine, sourceId: string, name: string, policy: Awaited<ReturnType<typeof readMentionPolicy>>): Promise<ExplainReason | null> {
+ const types = linkableTypesFor(await loadSourcePack(engine, sourceId), policy);
+ const pages = await engine.executeRaw<{ title: string | null; compiled_truth: string | null; timeline: string | null }>(
+ `SELECT title, compiled_truth, timeline FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND type = ANY($2::text[])
+ AND (compiled_truth ILIKE $3 OR title ILIKE $3) LIMIT 50`, [sourceId, types, `%${name.replace(/[\\%_]/g, m => `\\${m}`)}%`]);
+ for (const p of pages) {
+ const hit = deriveEntityAliases(p).rejected.find(r => r.alias.toLowerCase() === name.toLowerCase());
+ if (hit) return hit.reason;
+ }
+ return null;
+}
+
+export async function runExtractMentionsExplain(engine: BrainEngine, args: string[]): Promise<void> {
+ const value = (flag: string) => { const i = args.indexOf(flag); return i >= 0 && i + 1 < args.length ? args[i + 1] : undefined; };
+ const explainAt = args.indexOf('--explain');
+ const query = explainAt >= 0 ? args[explainAt + 1] : undefined;
+ if (!query || query.startsWith('--')) {
+ console.error('Usage: gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]');
+ process.exit(2);
+ }
+ const r = await explainMention(engine, query, { sourceId: value('--source-id'), page: value('--page') });
+ if (args.includes('--json')) { console.log(JSON.stringify(r, null, 2)); return; }
+ console.log(`${r.query} (source ${r.source_id}): ${r.reason ?? 'links'}`);
+ for (const e of r.entries) console.log(` entry: "${e.name}" → ${e.slug} (${e.origin}${e.case_sensitive ? ', case-sensitive' : ''})`);
+ if (r.page) console.log(` page ${r.page.slug}: ${r.page.linked ? 'linked' : 'not linked'}`);
+ console.log(` ${r.message}`);
+ if (r.next) console.log(` next: ${r.next}`);
+}
diff --git a/src/commands/extract.ts b/src/commands/extract.ts
index d5c1a55cb5..0bb3f58892 100644
--- a/src/commands/extract.ts
+++ b/src/commands/extract.ts
@@ -79,6 +79,8 @@ import { withRetry, isRetryableConnError } from '../core/retry.ts';
export { withRetry };
export type { WithRetryOpts } from '../core/retry.ts';
import { buildGazetteer, findMentionedEntities, hashGazetteer } from '../core/by-mention.ts';
+import { runMentionPass, type MentionPassResult } from '../core/mentions/pass.ts';
+import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMentionPass } from '../core/mentions/stale.ts';
// #4611: the cross-source link fallback follows the configured
// `sources.default` (validated shape) instead of the literal 'default'.
import {
@@ -849,10 +851,16 @@ Incremental sweep:
${ATTENDANCE_REPAIR_HELP}
gbrain extract --stale [--source-id <id>] [--include-frontmatter]
[--catch-up] [--dry-run] [--json]
- Re-extract links + timeline only for stale pages. DB-source; safe to
- cron. --catch-up loops past the 30-minute budget until none remain.
+ Re-extract links + timeline only for stale pages, then run the mention
+ pass: refresh entity pages' declared aliases and title subjects and link
+ every page that names an entity (link_source='mentions'). DB-source;
+ safe to cron. --catch-up loops past the 30-minute budget until none
+ remain. Off: gbrain config set mentions.auto_link false.
Inspection:
+ gbrain extract mentions --explain <name|slug> [--page <slug>] [--source-id <id>] [--json]
+ Why a name does or does not link (matched entry and origin, or the
+ guard that dropped it); with --page, whether that page links to it.
gbrain extract --explain <kind> [--json]
gbrain extract benchmark --pack <name> --kind <type> [--json]
@@ -2023,7 +2031,7 @@ export async function extractStaleFromDB(
*/
timeBudgetMs?: number;
},
-): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number }> {
+): Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; mentions?: MentionPassResult }> {
const { dryRun, jsonMode, sourceIdFilter, catchUp } = opts;
const includeFrontmatter = opts.includeFrontmatter ?? await resolveIncludeFrontmatter(engine);
const log = opts.quiet ? (..._args: unknown[]) => {} : console.log;
@@ -2033,25 +2041,24 @@ export async function extractStaleFromDB(
// Pre-flight count — cheap indexed COUNT. dry-run reports and returns.
const totalStale = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs });
if (dryRun) {
+ const m = await previewMentionPass(engine, sourceIdFilter);
if (jsonMode && !opts.quiet) {
- process.stdout.write(JSON.stringify({ action: 'extract_stale_dry_run', stale_pages: totalStale }) + '\n');
+ process.stdout.write(JSON.stringify({ action: 'extract_stale_dry_run', stale_pages: totalStale, mention_due_pages: m.due, mention_last_pass_at: m.last_pass_at }) + '\n');
} else {
- log(`(dry run) ${totalStale} page(s) need link/timeline extraction. Run without --dry-run to extract.`);
+ log(`(dry run) ${totalStale} page(s) need link/timeline extraction; ${m.due} page(s) need a mention pass (last pass: ${m.last_pass_at ?? 'never'}). Run without --dry-run to extract.`);
}
- return { linksCreated: 0, timelineCreated: 0, pagesProcessed: 0, staleRemaining: totalStale };
- }
- if (totalStale === 0) {
- if (!jsonMode) log('No stale pages — extraction is up to date.');
- return { linksCreated: 0, timelineCreated: 0, pagesProcessed: 0, staleRemaining: 0 };
+ return { linksCreated: 0, timelineCreated: 0, pagesProcessed: 0, staleRemaining: totalStale + m.due };
}
// Managed brains: the writer guard owns canonical rows, so links, missing
- // canonical timeline rows and the watermark publish on the one managed path.
+ // canonical timeline rows and the watermark publish on the one managed path
+ // (the mention pass runs inside it).
if (await managedPersistenceEnabled(engine)) {
const { extractManagedStaleLinks, formatManagedStaleExtraction } = await import('../core/persistence/links-maintenance.ts');
const r = await extractManagedStaleLinks(engine, { sourceId: sourceIdFilter, ...(catchUp ? {} : { timeBudgetMs }) });
if (!jsonMode) log(formatManagedStaleExtraction(r, false, false));
else if (!opts.quiet) process.stdout.write(formatManagedStaleExtraction(r, false, true) + '\n');
- return { linksCreated: r.created, timelineCreated: r.timeline, pagesProcessed: r.pages, staleRemaining: r.remaining, ...(r.skipped ? { skippedChanged: r.skipped } : {}) };
+ return { linksCreated: r.created, timelineCreated: r.timeline, pagesProcessed: r.pages, staleRemaining: r.remaining + (r.mentions?.remaining ?? 0),
+ ...(r.skipped ? { skippedChanged: r.skipped } : {}), ...(r.mentions ? { mentions: r.mentions } : {}) };
}
// Resolver + cross-source resolution map built ONCE before the loop (the
@@ -2075,7 +2082,8 @@ export async function extractStaleFromDB(
const crossSource = await isCrossSourceLinksEnabled(engine);
// #4611: mirrors extractLinksFromDB — configured default, resolved once.
const linkDefaultSourceId = await resolveLinkFallbackDefault(engine);
- const allRefs = await engine.listAllPageRefs();
+ // Nothing link-stale: skip the whole-brain resolver reads; the mention pass still runs.
+ const allRefs = totalStale ? await engine.listAllPageRefs() : [];
const allSlugs = new Set<string>();
const slugToSources = new Map<string, string[]>();
for (const ref of allRefs) {
@@ -2089,12 +2097,13 @@ export async function extractStaleFromDB(
const federatedSourceIds = new Set(
(await loadAllSources(engine, { federatedOnly: true })).map(source => source.id),
);
- const targetMetadata = new Map((await loadLinkPageMetadata(engine)).map(p => [`${p.source_id}\0${p.slug}`, p]));
+ const targetMetadata = new Map((totalStale ? await loadLinkPageMetadata(engine) : []).map(p => [`${p.source_id}\0${p.slug}`, p]));
const progress = createProgress(cliOptsToProgressOptions(getCliOptions()));
progress.start('extract.stale', totalStale);
const startMs = Date.now();
+ const linkDeadline = await linkPhaseDeadline(engine, sourceIdFilter, startMs, catchUp ? undefined : timeBudgetMs);
let afterPageId = 0;
let linksCreated = 0, timelineCreated = 0, pagesProcessed = 0;
let skippedAttendanceIncomplete = 0;
@@ -2206,15 +2215,19 @@ export async function extractStaleFromDB(
progress.tick(processedRefs.length);
afterPageId = rows[rows.length - 1]!.id;
- if (!catchUp && Date.now() - startMs > timeBudgetMs) { budgetHit = true; break; }
+ if (Date.now() > linkDeadline) { budgetHit = true; break; }
}
progress.finish();
if (packUnavailable) throw new Error('Cannot extract links: active schema pack is unavailable.');
- const staleRemaining = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs });
+ const mentions = await runMentionPass(engine, { sourceId: sourceIdFilter, ...(catchUp ? {} : { deadline: startMs + timeBudgetMs }) });
+ const staleRemaining = await engine.countStalePagesForExtraction({ sourceId: sourceIdFilter, versionTs }) + mentions.remaining;
if (!jsonMode) {
- log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
+ const mentionLine = formatMentionSummary(mentions);
+ if (totalStale === 0 && !mentionLine) log('No stale pages — extraction is up to date.');
+ else log(`Extract --stale: ${linksCreated} link(s) + ${timelineCreated} timeline entr(ies) from ${pagesProcessed} page(s).`);
+ if (mentionLine) log(mentionLine);
if (skippedAttendanceIncomplete) log(`Skipped ${skippedAttendanceIncomplete} page(s) with unresolved attendance; prior links and extraction watermarks were preserved.`);
if (skippedMissingTarget > 0) {
log(`Skipped ${skippedMissingTarget} candidate(s) whose target page doesn't exist (references to non-pages are never persisted).`);
@@ -2230,11 +2243,11 @@ export async function extractStaleFromDB(
action: 'extract_stale_done', links_created: linksCreated, timeline_created: timelineCreated,
pages_processed: pagesProcessed, stale_remaining: staleRemaining, budget_hit: budgetHit,
skipped_missing_target: skippedMissingTarget, skipped_cross_source: skippedCrossSource,
- ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}),
+ ...(skippedAttendanceIncomplete ? { skipped_attendance_incomplete: skippedAttendanceIncomplete } : {}), ...mentionJsonFields(mentions),
}) + '\n');
}
return { linksCreated, timelineCreated, pagesProcessed, staleRemaining, skippedMissingTarget, skippedCrossSource,
- ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}) };
+ ...(skippedAttendanceIncomplete ? { skippedAttendanceIncomplete } : {}), mentions };
}
/**
@@ -2398,7 +2411,7 @@ async function extractMentionsFromDb(
// D3: scan both columns joined with a paragraph separator so an
// end-of-compiled token doesn't accidentally merge with a
// start-of-timeline token into a false phrase match.
- const body = page.compiled_truth + '\n\n' + (page.timeline ?? '');
+ const body = (page.title ?? '') + '\n\n' + page.compiled_truth + '\n\n' + (page.timeline ?? '');
const mentions = body.trim()
? findMentionedEntities(body, gazetteer, {
fromSlug: slug,
diff --git a/src/commands/reindex-aliases.ts b/src/commands/reindex-aliases.ts
index 226a544269..90737e942d 100644
--- a/src/commands/reindex-aliases.ts
+++ b/src/commands/reindex-aliases.ts
@@ -3,18 +3,25 @@
* (T8 — backfill the free-text alias layer).
*
* Import-time projection (T3) covers NEW + changed pages; this backfills the
- * EXISTING pages whose frontmatter `aliases:` predate v110 (or predate the
- * projection landing). Reads each page's frontmatter `aliases:` and writes
- * page_aliases via engine.setPageAliases.
+ * EXISTING pages: each page's frontmatter `aliases:` (origin frontmatter)
+ * and, for linkable entity pages, its title subject and declared aliases
+ * (origin subject / declared, the same rows import and the mention pass
+ * write), including pages that have no frontmatter aliases.
*
- * Idempotent: setPageAliases replaces a page's alias set, so re-running is
- * safe and convergent — no op-checkpoint needed (the op is fast, no embedding).
+ * Idempotent: each origin's rows are replaced, so re-running is safe and
+ * convergent — no op-checkpoint needed (the op is fast, no embedding).
* Walks listAllPageRefs (cheap (source_id, slug) enumeration) so it's
- * cross-source by default; --source narrows it.
+ * cross-source by default; --source narrows it. On a managed brain the
+ * derived rows are written through the coordinated writer.
*/
import type { BrainEngine } from '../core/engine.ts';
import { normalizeAliasList } from '../core/search/alias-normalize.ts';
+import { writeDerivedAliases } from '../core/mentions/pass.ts';
+import { readMentionPolicy } from '../core/mentions/policy.ts';
+import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
+import { maintenanceAttribution } from '../core/persistence/attribution.ts';
+import { withCoordinatedWrite } from '../core/persistence/context.ts';
import { createProgress } from '../core/progress.ts';
import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';
@@ -43,7 +50,12 @@ export async function runReindexAliases(engine: BrainEngine, args: string[]): Pr
let scanned = 0;
let pagesWithAliases = 0;
let aliasesWritten = 0;
+ const managed = await managedPersistenceEnabled(engine);
+ const attribution = managed ? await maintenanceAttribution(engine) : null;
+ const derivedWrite = (sourceId: string, fn: (tx: BrainEngine) => Promise<number>) => engine.transaction(tx =>
+ attribution ? withCoordinatedWrite(tx, [sourceId], () => fn(tx), attribution) : fn(tx));
+ const mentionPolicy = dryRun ? null : await readMentionPolicy(engine);
for (const ref of refs) {
scanned++;
reporter.tick();
@@ -55,16 +67,19 @@ export async function runReindexAliases(engine: BrainEngine, args: string[]): Pr
}
if (!page) continue;
const aliasNorms = normalizeAliasList((page.frontmatter as Record<string, unknown> | undefined)?.aliases);
- if (aliasNorms.length === 0) continue;
- pagesWithAliases++;
- aliasesWritten += aliasNorms.length;
- if (!dryRun) {
- try {
- await engine.setPageAliases(ref.slug, ref.source_id, aliasNorms);
- } catch (e) {
- reporter.finish();
- throw e; // pre-v110 (no table) or a real write error — surface it.
- }
+ if (dryRun) {
+ if (aliasNorms.length) { pagesWithAliases++; aliasesWritten += aliasNorms.length; }
+ continue;
+ }
+ try {
+ if (aliasNorms.length) await engine.setPageAliases(ref.slug, ref.source_id, aliasNorms);
+ const derived = await derivedWrite(ref.source_id, tx => writeDerivedAliases(tx, ref.source_id,
+ { slug: ref.slug, title: page.title, type: page.type, compiled_truth: page.compiled_truth, timeline: page.timeline }, { policy: mentionPolicy }));
+ if (aliasNorms.length || derived) pagesWithAliases++;
+ aliasesWritten += aliasNorms.length + derived;
+ } catch (e) {
+ reporter.finish();
+ throw e; // pre-v110 (no table) or a real write error — surface it.
}
}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 225fa5026b..b8e20120f4 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -699,6 +699,8 @@ export async function runPostUpgrade(args: string[] = []): Promise<void> {
// #5876: auto_chronicle now defaults on; one-shot [AGENT] cost + opt-out notice, best-effort.
await (await import('../core/chronicle/upgrade-notice.ts')).printAutoChronicleUpgradeNotice(engine);
+ // Entity mention index: [AGENT] catch-up line while pages are due (best-effort).
+ await (await import('../core/mentions/upgrade-notice.ts')).printMentionIndexUpgradeNotice(engine);
// Ambient-writeback consent ask (WP8): one-shot for EXISTING installs
// upgrading into the feature. Personal brains only; double-gated on
diff --git a/src/core/by-mention.ts b/src/core/by-mention.ts
index 3bb91b543a..51042dbd49 100644
--- a/src/core/by-mention.ts
+++ b/src/core/by-mention.ts
@@ -1,29 +1,32 @@
/**
- * v0.42.0.0 Part B — Auto-link entity mentions to known entity pages.
- * Migration #1 of the consolidated #1409 design doc (orphan reduction).
+ * Auto-link entity mentions to known entity pages (orphan reduction, #1409;
+ * entity recall, src/core/mentions/).
*
- * `buildGazetteer` queries the brain for entity-typed pages and produces a
- * token-Map lookup structure suitable for fast body-text scanning.
+ * `buildGazetteer` reads the brain's linkable entity pages (the pack-aware
+ * per-source type set from `mentions/policy.ts`) and their names (titles plus
+ * `page_aliases` rows: frontmatter aliases, declared aliases and title
+ * subjects) into a token-Map lookup structure for body-text scanning.
*
* `findMentionedEntities` is a pure function that scans body text against
* the gazetteer, applies the maximal-munch matcher (longest gazetteer
- * entry wins at each offset), self-link guard, cross-source guard, and
- * per-page first-mention-only cap (1 link per (source_slug, target_slug)).
+ * entry wins at each offset), case-sensitive entries, per-page ignore names,
+ * the self-link guard, the cross-source guard, and the per-page
+ * first-mention-only cap (1 link per (source_slug, target_slug)).
*
- * Design decisions locked in /plan-eng-review for v0.42.0.0:
- * - D2/D10 Hardcoded entity-type filter (not pack-aware) — pack v2
- * extension filed as TODO-1.
- * - D6 Token-Map + multi-word phrase pass (no new deps, no regex
- * alternation, no Aho-Corasick).
- * - D7 DB-source only — caller restricts page WALK to DB iteration.
- * - D12 `link_source='mentions'` writes filtered out of backlink-count
- * for search ranking (see postgres-engine.ts/pglite-engine.ts).
- * - D13 Self-link guard.
- * - CK12 Ignore-list applied at gazetteer-build time, NOT match time.
- * Built-in ambiguous tokens (Apple, Amazon, Square, Stripe, Box)
- * are dropped from the gazetteer ONLY when no corresponding
- * entity page exists. If a page DOES exist, the user explicitly
- * created it and we trust the gazetteer presence.
+ * Design decisions:
+ * - Linkable types come from the source's schema pack (primitive: entity
+ * types and their type aliases, product excluded) unioned with person,
+ * company, organization and entity.
+ * - Token-Map + multi-word phrase pass (no new deps, no regex alternation,
+ * no Aho-Corasick).
+ * - DB-source only — callers walk pages from the database.
+ * - `link_source='mentions'` writes are filtered out of backlink-count for
+ * search ranking (see postgres-engine.ts/pglite-engine.ts).
+ * - Self-link guard.
+ * - Ignore-list applied at gazetteer-build time, not match time. Built-in
+ * ambiguous tokens (Apple, Amazon, Square, Stripe, Box) are dropped from
+ * the gazetteer only when no corresponding entity page exists: a page the
+ * user created is trusted. `mentions.ignore` names are dropped always.
*/
import { createHash } from 'crypto';
@@ -34,19 +37,20 @@ import { stripCodeBlocks, isCrossSourceLinksEnabled } from './link-extraction.ts
// #4222: shared generic-token reject list — same list gates enrichEntity
// minting and drives the junk_entity_hubs doctor check.
import { isGenericEntityToken } from './entity-name-quality.ts';
-
-/** D2: hardcoded entity types for v1. Pack-aware extension is TODO-1. */
-export const LINKABLE_ENTITY_TYPES = ['person', 'company', 'organization', 'entity'] as const;
+import { ALWAYS_LINKABLE_TYPES, linkableTypesFor, loadSourcePack, readMentionPolicy, type MentionPolicy } from './mentions/policy.ts';
/**
- * Minimum title length for gazetteer inclusion. Filters out 2-3 char names
- * (AI, YC, X, IBM) that produce dense false-positive auto-links in body text.
- * Codex CK13 noted v1 will under-deliver on 3-char real entities; the
- * pack-aware follow-up (TODO-1) can let users opt specific 3-char entity
- * types in.
+ * The four types that are always linkable, whatever the schema pack says. The
+ * full per-source set is `linkableTypesFor` (mentions/policy.ts).
*/
+export const LINKABLE_ENTITY_TYPES = ALWAYS_LINKABLE_TYPES;
+
let aliasGazetteerWarned = false;
+/**
+ * Minimum name length for gazetteer inclusion. Filters out 2-3 char names
+ * (AI, YC, X, IBM) that produce dense false-positive auto-links in body text.
+ */
const MIN_NAME_LENGTH = 4;
const MIN_CJK_NAME_LENGTH = 2;
@@ -62,6 +66,9 @@ const MIN_CJK_NAME_LENGTH = 2;
*/
const DEFAULT_IGNORE_LIST = ['Apple', 'Amazon', 'Square', 'Stripe', 'Box', 'Meta', 'Target', 'Oracle'];
+/** Where a gazetteer name came from: the page title or a `page_aliases` row's origin. */
+export type GazetteerOrigin = 'title' | 'frontmatter' | 'declared' | 'subject';
+
export interface GazetteerEntry {
/** Canonical page slug (e.g. `companies/acme-corp`). */
slug: string;
@@ -71,6 +78,13 @@ export interface GazetteerEntry {
title: string;
/** Lowercase title tokens in order. Length 1 = single-word entity. */
tokens: string[];
+ /** Absent on hand-built entries: a title. */
+ origin?: GazetteerOrigin;
+ /**
+ * Set on case-sensitive entries (single-token declared aliases): the tokens
+ * as written, NFC. A body token matches only when its original text equals.
+ */
+ caseTokens?: string[];
}
/**
@@ -91,11 +105,33 @@ export type Gazetteer = Map<string, GazetteerEntry[]>;
export function hashGazetteer(gazetteer: Gazetteer): string {
const entries: string[] = [];
for (const bucket of gazetteer.values()) {
- for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}`);
+ for (const e of bucket) entries.push(`${e.source_id}\0${e.slug}\0${e.title}\0${e.tokens.join(' ')}${e.caseTokens ? `\0${e.caseTokens.join(' ')}` : ''}`);
}
return createHash('sha256').update(entries.sort().join('\n')).digest('hex').slice(0, 8);
}
+/** One row of the saved entry set the mention pass diffs (mention_gazetteer_entries). */
+export interface GazetteerEntryKey {
+ source_id: string;
+ name_norm: string;
+ target_slug: string;
+ case_sensitive: boolean;
+}
+
+/** The gazetteer's entries as (source, normalized name, target, case flag), deduped and sorted. */
+export function gazetteerEntryKeys(gazetteer: Gazetteer): GazetteerEntryKey[] {
+ const out = new Map<string, GazetteerEntryKey>();
+ for (const bucket of gazetteer.values()) {
+ for (const e of bucket) {
+ const name_norm = (e.caseTokens ?? e.tokens).join(' ');
+ const key: GazetteerEntryKey = { source_id: e.source_id, name_norm, target_slug: e.slug, case_sensitive: !!e.caseTokens };
+ out.set(`${key.source_id}\0${key.name_norm}\0${key.target_slug}\0${key.case_sensitive}`, key);
+ }
+ }
+ return [...out.values()].sort((x, y) => x.source_id.localeCompare(y.source_id) || x.name_norm.localeCompare(y.name_norm)
+ || x.target_slug.localeCompare(y.target_slug) || Number(x.case_sensitive) - Number(y.case_sensitive));
+}
+
export interface Mention {
/** Target page slug (the entity being mentioned). */
slug: string;
@@ -107,12 +143,30 @@ export interface Mention {
offset: number;
}
+/** A name the gazetteer dropped, with the reason (read by `extract mentions --explain`). */
+export interface DroppedName {
+ source_id: string;
+ slug: string;
+ name: string;
+ origin: GazetteerOrigin;
+ reason: 'below_min_length' | 'generic_token' | 'alias_collision' | 'ambiguous_first_word' | 'ignored' | 'title_wins';
+}
+
export interface BuildGazetteerOpts {
/**
* Optional user-supplied additional ignore-list entries (case-sensitive
* raw title match). Merged with DEFAULT_IGNORE_LIST.
*/
extraIgnore?: string[];
+ /** Mention policy (types, `mentions.ignore`); read from config when absent. */
+ policy?: MentionPolicy;
+ /**
+ * Authoritative build for the mention pass: a pack that fails to resolve or
+ * an alias read that fails throws instead of degrading to a smaller set.
+ */
+ strict?: boolean;
+ /** Collects every dropped name with its reason. */
+ dropped?: DroppedName[];
}
export interface FindMentionsOpts {
@@ -129,6 +183,11 @@ export interface FindMentionsOpts {
* same-source-only posture.
*/
allowCrossSource?: boolean;
+ /**
+ * Names the scanning page opts out of (its frontmatter `mention_ignore`),
+ * compared on normalized tokens.
+ */
+ ignoreNames?: readonly string[];
}
// ============================================================
@@ -304,7 +363,7 @@ export function tokenizeForScan(text: string): ScannedToken[] {
return out;
}
-function hasCJK(s: string): boolean {
+export function hasCJK(s: string): boolean {
for (const ch of s) {
if (isCJKChar(ch)) return true;
}
@@ -384,12 +443,22 @@ export function tokenizeTitle(title: string): string[] {
}
/**
- * Build a token-Map gazetteer from all entity-typed pages in the brain.
+ * Build a token-Map gazetteer from every linkable entity page in the brain.
*
- * Hardcoded type filter per D2 (pack-awareness is TODO-1). Soft-deleted
- * pages excluded. Pages with too-short titles excluded (MIN_NAME_LENGTH).
+ * Linkable types are resolved per source (`linkableTypesFor`: the four
+ * always-linkable types plus the source pack's entity types and their type
+ * aliases). Soft-deleted pages excluded. Each entity page contributes its
+ * title and its `page_aliases` rows (frontmatter aliases, declared aliases,
+ * title subjects; one row per alias with precedence frontmatter > declared >
+ * subject). Guards on every name: the 4-character minimum, the generic-token
+ * reject list for single-token person titles and every single-token alias,
+ * the ignore lists. Guards on aliases only: an alias claimed by two pages of one source is dropped, an alias equal
+ * to an existing title in the same source yields to the title, and a
+ * single-token alias equal to the first word of another entity's multi-word
+ * name in the source is dropped (an ambiguous first word never links alone).
* Ignore-list applied per CK12: built-in ambiguous tokens dropped unless
- * the user has explicitly created the corresponding page.
+ * the user has explicitly created the corresponding page; `mentions.ignore`
+ * names always drop.
*
* Returned gazetteer is keyed by lowercase first token; entries with the
* same first token co-exist in the same bucket (e.g. "Acme" + "Acme Corp").
@@ -398,132 +467,179 @@ export async function buildGazetteer(
engine: BrainEngine,
opts: BuildGazetteerOpts = {},
): Promise<Gazetteer> {
- const typeList = LINKABLE_ENTITY_TYPES.map(t => `'${t}'`).join(', ');
- const rows = await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null; type: string | null }>(
+ const policy = opts.policy ?? await readMentionPolicy(engine);
+ const dropped = opts.dropped;
+ const drop = (d: DroppedName) => { dropped?.push(d); };
+ const sources = await engine.executeRaw<{ id: string }>('SELECT DISTINCT source_id AS id FROM pages WHERE deleted_at IS NULL', []);
+ const typesBySource = new Map<string, Set<string>>();
+ for (const { id } of sources) {
+ const pack = await loadSourcePack(engine, id, { strict: opts.strict });
+ typesBySource.set(id, new Set(linkableTypesFor(pack, policy)));
+ }
+ const allTypes = [...new Set([...typesBySource.values()].flatMap(set => [...set]))];
+ const linkable = (sourceId: string | null, type: string | null) => !!type && (typesBySource.get(sourceId ?? 'default')?.has(type) ?? false);
+ const rows = (await engine.executeRaw<{ slug: string; source_id: string | null; title: string | null; type: string | null }>(
`SELECT slug, source_id, title, type
FROM pages
- WHERE type IN (${typeList})
+ WHERE type = ANY($1::text[])
AND deleted_at IS NULL`,
- [],
- );
+ [allTypes],
+ )).filter(r => linkable(r.source_id, r.type));
- // Pre-build the existing-slug Set so the ignore-list rule can check
+ // Pre-build the existing-title Set so the ignore-list rule can check
// "does this name already correspond to a real page?" in O(1).
const existingTitles = new Set<string>();
for (const r of rows) {
if (r.title) existingTitles.add(r.title);
}
const ignoreSet = new Set<string>([...DEFAULT_IGNORE_LIST, ...(opts.extraIgnore ?? [])]);
+ const userIgnore = new Set(policy.ignore.map(n => tokenizeTitle(n).join(' ')).filter(Boolean));
const gazetteer: Gazetteer = new Map();
+ const add = (entry: GazetteerEntry) => {
+ const key = entry.tokens[0]!;
+ const bucket = gazetteer.get(key);
+ if (bucket) bucket.push(entry);
+ else gazetteer.set(key, [entry]);
+ };
+ // Per source: the first token of every multi-word entity name (titles here,
+ // aliases below), for the ambiguous-first-word guard on single-token aliases.
+ const firstWords = new Map<string, Set<string>>();
+ const noteFirstWord = (src: string, tokens: string[]) => {
+ if (tokens.length < 2) return;
+ const set = firstWords.get(src) ?? new Set<string>();
+ set.add(tokens[0]!);
+ firstWords.set(src, set);
+ };
for (const row of rows) {
if (!row.title) continue;
- if (!hasCJK(row.title) && row.title.length < MIN_NAME_LENGTH) continue;
- if (hasCJK(row.title) && cjkCharCount(row.title) < MIN_CJK_NAME_LENGTH) continue;
+ const src = row.source_id ?? 'default';
+ const base = { source_id: src, slug: row.slug, name: row.title, origin: 'title' as const };
+ if (!hasCJK(row.title) && row.title.length < MIN_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ if (hasCJK(row.title) && cjkCharCount(row.title) < MIN_CJK_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }
// NOTE (v0.46.15, deliberately preserved): for TITLES this condition is
// intentionally vacuous — every row here IS a real page, so an
// ignore-listed name the user explicitly created a page for is always
// allowed (documented CK12 policy). The ignore list bites only via
// opts.extraIgnore names that have no page, and — with real teeth — on
// the ALIAS entries below, which are not user-created pages.
- if (ignoreSet.has(row.title) && !existingTitles.has(row.title)) continue;
+ if (ignoreSet.has(row.title) && !existingTitles.has(row.title)) { drop({ ...base, reason: 'ignored' }); continue; }
const tokens = tokenizeTitle(row.title);
if (tokens.length === 0) continue;
- if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) continue;
+ if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ if (userIgnore.has(tokens.join(' '))) { drop({ ...base, reason: 'ignored' }); continue; }
// #4222: a single-generic-token PERSON title ("Will", "Chief") is a
// junk-hub magnet — every prose occurrence of the word would accrete
- // another mention edge onto a near-empty page. Dropped from the
- // gazetteer even though the page exists (unlike the CK12 ignore-list
- // rule above, which trusts user-created pages: these titles are
- // overwhelmingly extractor-minted, and the page itself stays intact —
- // only the auto-link accretion stops). Multi-token titles ("Will
- // Smith") and non-person types are unaffected.
- if (tokens.length === 1 && row.type === 'person' && isGenericEntityToken(tokens[0]!)) continue;
-
- const entry: GazetteerEntry = {
- slug: row.slug,
- source_id: row.source_id ?? 'default',
- title: row.title,
- tokens,
- };
- const key = tokens[0]!;
- const bucket = gazetteer.get(key);
- if (bucket) bucket.push(entry);
- else gazetteer.set(key, [entry]);
+ // another mention edge onto a near-empty page. Dropped from the gazetteer
+ // even though the page exists (unlike the CK12 ignore-list rule above,
+ // which trusts user-created pages: these titles are overwhelmingly
+ // extractor-minted, and the page itself stays intact — only the
+ // auto-link accretion stops). Multi-token titles ("Will Smith") and
+ // non-person titles are unaffected; aliases of every type are checked
+ // below.
+ if (tokens.length === 1 && row.type === 'person' && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
+ noteFirstWord(src, tokens);
+ add({ slug: row.slug, source_id: src, title: row.title, tokens, origin: 'title' });
}
- // ── Alias entries (v0.46.15 identity wave, #3801) ────────────────────────
- // page_aliases rows joined to LIVE entity-typed pages become additional
+ // ── Alias entries ────────────────────────────────────────────────────────
+ // page_aliases rows joined to LIVE linkable entity pages become additional
// gazetteer entries, so a body mention of "saoirse" links to
- // people/saoirse-x. Guards (stricter than titles — aliases are not
- // user-created pages):
+ // people/saoirse-x and "QUCO" links to the account that declares it.
+ // Guards (stricter than titles — aliases are not user-created pages):
+ // - one row per (source, alias, page) with origin precedence
+ // frontmatter > declared > subject
// - ignore-list applies CASE-INSENSITIVELY with NO existing-page escape
// (aliases store normalized lowercase; DEFAULT_IGNORE_LIST is cased)
- // - aliases mapping to >1 slug within a source are skipped (ambiguous)
+ // - an alias claimed by >1 page at its best origin within a source is
+ // dropped (ambiguous); a lower-precedence claim yields
// - aliases colliding with any existing page TITLE in the SAME source
// are skipped (the title entry wins; per-source scoping per R2-9)
- // - MIN_NAME_LENGTH applies to the alias string
+ // - MIN_NAME_LENGTH and the generic-token list apply to the alias string
+ // - a single-token alias equal to the first word of a multi-word entity
+ // name in the same source is dropped
+ // - a case-sensitive row (a single-token declared alias) matches only
+ // the original-case text
+ let aliasRows: Array<{ alias_norm: string; slug: string; source_id: string | null; title: string | null; type: string | null;
+ origin: string | null; case_sensitive: boolean | null; alias_text: string | null }> = [];
try {
- const aliasRows = await engine.executeRaw<{
- alias_norm: string;
- slug: string;
- source_id: string | null;
- title: string | null;
- }>(
- `SELECT pa.alias_norm, pa.slug, pa.source_id, p.title
+ aliasRows = (await engine.executeRaw<typeof aliasRows[number]>(
+ `SELECT pa.alias_norm, pa.slug, pa.source_id, p.title, p.type, pa.origin, pa.case_sensitive, pa.alias_text
FROM page_aliases pa
JOIN pages p ON p.slug = pa.slug AND p.source_id = pa.source_id
- WHERE p.type IN (${typeList})
+ WHERE p.type = ANY($1::text[])
AND p.deleted_at IS NULL`,
- [],
- );
- const ignoreLc = new Set(Array.from(ignoreSet, (s) => s.toLowerCase()));
- // Per-source title index for alias-vs-title collision checks.
- const titleBySource = new Set<string>();
- for (const r of rows) {
- if (r.title) titleBySource.add(`${r.source_id ?? 'default'}${r.title.toLowerCase()}`);
- }
- // Ambiguity: same (source, alias) → multiple slugs.
- const bySourceAlias = new Map<string, Set<string>>();
- for (const a of aliasRows) {
- const k = `${a.source_id ?? 'default'}${a.alias_norm}`;
- const set = bySourceAlias.get(k) ?? new Set<string>();
- set.add(a.slug);
- bySourceAlias.set(k, set);
- }
- const seenAliasEntry = new Set<string>();
- for (const a of aliasRows) {
- const alias = a.alias_norm?.trim();
- if (!alias || !a.title) continue;
- const src = a.source_id ?? 'default';
- if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) continue;
- if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) continue;
- if (ignoreLc.has(alias.toLowerCase())) continue;
- if ((bySourceAlias.get(`${src}${alias}`)?.size ?? 0) > 1) continue;
- if (titleBySource.has(`${src}${alias.toLowerCase()}`)) continue;
- const dedupeKey = `${src}${alias}${a.slug}`;
- if (seenAliasEntry.has(dedupeKey)) continue;
- seenAliasEntry.add(dedupeKey);
- const tokens = tokenizeTitle(alias);
- if (tokens.length === 0) continue;
- if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) continue;
- const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens };
- const key = tokens[0]!;
- const bucket = gazetteer.get(key);
- if (bucket) bucket.push(entry);
- else gazetteer.set(key, [entry]);
- }
+ [allTypes],
+ )).filter(r => linkable(r.source_id, r.type));
} catch (err) {
// pre-v110 brains: no page_aliases table — titles-only gazetteer.
// Any OTHER failure (connection blip, permission) warns once per process
// (adversarial F12): a silently titles-only gazetteer under-links every
- // page processed until restart, and nobody would know why.
+ // page processed until restart, and nobody would know why. A strict
+ // (mention-pass) build throws instead, so nothing is reconciled against
+ // a partial gazetteer.
+ if (opts.strict) throw err;
if (!isUndefinedTableError(err) && !aliasGazetteerWarned) {
aliasGazetteerWarned = true;
console.error(`[gbrain] gazetteer alias load degraded (titles-only): ${err instanceof Error ? err.message : String(err)}`);
}
}
+ const ignoreLc = new Set(Array.from(ignoreSet, (n) => n.toLowerCase()));
+ // Per-source title index for alias-vs-title collision checks.
+ const titleBySource = new Set<string>();
+ for (const r of rows) {
+ if (r.title) titleBySource.add(`${r.source_id ?? 'default'} ${r.title.toLowerCase()}`);
+ }
+ const rank = (origin: string | null) => origin === 'subject' ? 2 : origin === 'declared' ? 1 : 0;
+ // Best (lowest) origin rank per (source, alias, slug), then per (source, alias).
+ const bestPerPage = new Map<string, typeof aliasRows[number]>();
+ for (const a of aliasRows) {
+ const k = `${a.source_id ?? 'default'} ${a.alias_norm} ${a.slug}`;
+ const prev = bestPerPage.get(k);
+ if (!prev || rank(a.origin) < rank(prev.origin)) bestPerPage.set(k, a);
+ }
+ const claims = new Map<string, { rank: number; slugs: Set<string> }>();
+ for (const a of bestPerPage.values()) {
+ const k = `${a.source_id ?? 'default'} ${a.alias_norm}`;
+ const r = rank(a.origin);
+ const c = claims.get(k);
+ if (!c || r < c.rank) claims.set(k, { rank: r, slugs: new Set([a.slug]) });
+ else if (r === c.rank) c.slugs.add(a.slug);
+ }
+ const aliasEntries: Array<{ entry: GazetteerEntry; base: Omit<DroppedName, 'reason'> }> = [];
+ for (const a of bestPerPage.values()) {
+ const alias = a.alias_norm?.trim();
+ if (!alias || !a.title) continue;
+ const src = a.source_id ?? 'default';
+ const origin = (a.origin ?? 'frontmatter') as GazetteerOrigin;
+ const written = a.case_sensitive && a.alias_text ? a.alias_text : alias;
+ const base = { source_id: src, slug: a.slug, name: written, origin };
+ const claim = claims.get(`${src} ${alias}`)!;
+ if (rank(a.origin) > claim.rank) continue;
+ if (claim.slugs.size > 1) { drop({ ...base, reason: 'alias_collision' }); continue; }
+ if (alias.length < MIN_NAME_LENGTH && !hasCJK(alias)) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ if (hasCJK(alias) && cjkCharCount(alias) < MIN_CJK_NAME_LENGTH) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ if (ignoreLc.has(alias.toLowerCase())) { drop({ ...base, reason: 'ignored' }); continue; }
+ if (titleBySource.has(`${src} ${alias.toLowerCase()}`)) { drop({ ...base, reason: 'title_wins' }); continue; }
+ const tokens = tokenizeTitle(alias);
+ if (tokens.length === 0) continue;
+ if (tokens[0]!.length < MIN_NAME_LENGTH && tokens.length === 1) { drop({ ...base, reason: 'below_min_length' }); continue; }
+ if (userIgnore.has(tokens.join(' '))) { drop({ ...base, reason: 'ignored' }); continue; }
+ if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) { drop({ ...base, reason: 'generic_token' }); continue; }
+ const caseTokens = a.case_sensitive && a.alias_text ? caseTokensOf(a.alias_text) : undefined;
+ const entry: GazetteerEntry = { slug: a.slug, source_id: src, title: a.title, tokens, origin,
+ ...(caseTokens && caseTokens.length === tokens.length ? { caseTokens } : {}) };
+ noteFirstWord(src, tokens);
+ aliasEntries.push({ entry, base });
+ }
+ for (const { entry, base } of aliasEntries) {
+ if (entry.tokens.length === 1 && firstWords.get(entry.source_id)?.has(entry.tokens[0]!)) {
+ drop({ ...base, reason: 'ambiguous_first_word' });
+ continue;
+ }
+ add(entry);
+ }
// Sort each bucket by token-count DESC so maximal-munch walks longest-first;
// ties break on (source_id, slug) so the pick among same-name entries is
@@ -537,6 +653,11 @@ export async function buildGazetteer(
return gazetteer;
}
+/** Original-case tokens of a name (NFC, not lowercased), aligned with tokenizeTitle. */
+function caseTokensOf(name: string): string[] {
+ return tokenizeForScan(name).map(t => name.slice(t.offset, t.offset + t.length).normalize('NFC'));
+}
+
// ============================================================
// Body-text scanner (pure)
// ============================================================
@@ -577,6 +698,12 @@ export function findMentionedEntities(
const stripped = stripCodeBlocks(text);
const tokens = tokenizeForScan(stripped);
if (tokens.length === 0) return [];
+ const ignored = new Set((opts.ignoreNames ?? []).map(n => tokenizeTitle(n).join(' ')).filter(Boolean));
+ // A case-sensitive entry matches only the original-case body text.
+ const caseMatches = (entry: GazetteerEntry, at: number) => !entry.caseTokens || entry.caseTokens.every((t, k) => {
+ const tok = tokens[at + k]!;
+ return stripped.slice(tok.offset, tok.offset + tok.length).normalize('NFC') === t;
+ });
const out: Mention[] = [];
const seenTargets = new Set<string>();
@@ -595,6 +722,7 @@ export function findMentionedEntities(
let matched: GazetteerEntry | null = null;
let matchedTokens = 0;
for (const entry of bucket) {
+ if (!caseMatches(entry, i)) continue;
if (entry.tokens.length === 1) {
matched = entry;
matchedTokens = 1;
@@ -629,10 +757,15 @@ export function findMentionedEntities(
const own = bucket.find(
e => e.source_id === opts.fromSourceId
&& e.tokens.length === want.length
- && e.tokens.every((t, k) => t === want[k]),
+ && e.tokens.every((t, k) => t === want[k])
+ && caseMatches(e, i),
);
if (own) matched = own;
}
+ if (ignored.size > 0 && ignored.has(matched.tokens.join(' '))) {
+ i += matchedTokens;
+ continue;
+ }
// Guards.
if (matched.source_id === opts.fromSourceId && matched.slug === opts.fromSlug) {
@@ -768,7 +901,7 @@ export async function scanStaleMentions(
}>(
`${scannedCte}
SELECT p.id, p.slug, p.source_id,
- COALESCE(p.compiled_truth, '') || E'\n\n' || COALESCE(p.timeline, '') AS body
+ COALESCE(p.title, '') || E'\n\n' || COALESCE(p.compiled_truth, '') || E'\n\n' || COALESCE(p.timeline, '') AS body
FROM pages p
JOIN scanned s ON s.id = p.id
ORDER BY p.slug`,
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 742267af39..99c784c586 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -56,10 +56,10 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'errors': ['--brain', '--changed', '--help', '--json', '--source'],
'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--wait', '--with-code-intel', '--yes'],
'export': ['--accept-pending', '--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type', '--wait'],
- 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
+ 'extract': ['--accept-pending', '--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--http', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--no-accept-pending', '--pack', '--page', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--wait', '--workers', '--yes'],
'extract-conversation-facts': ['--accept-pending', '--admin-intent', '--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--help', '--input', '--json', '--limit', '--manifest', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-accept-pending', '--no-embedding', '--output', '--override-disabled', '--path', '--progress-interval', '--progress-json', '--quiet', '--rate', '--segment-limit', '--self-transfer', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--wait', '--workers', '--yes'],
'facts': ['--admin-intent', '--after-id', '--brain', '--dry-run', '--entity', '--examples', '--expected-state', '--help', '--include-private', '--json', '--limit', '--max-cost-usd', '--max-usd', '--no-conflict-queue', '--no-llm', '--path', '--retry-model', '--since', '--source'],
- 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--expect', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
+ 'features': ['--all', '--apply', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--expect', '--explain', '--facts', '--from-meetings', '--help', '--images', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--max-cost', '--max-usd', '--ner', '--non-interactive', '--only', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--path', '--priority', '--probe', '--prune-orphans', '--rebuild', '--refresh', '--repo', '--save', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--trust', '--type', '--verbose', '--workers', '--yes'],
'files': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--wait', '--yes'],
'forget': ['--brain', '--help', '--json', '--reason', '--request-id', '--source'],
'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],
@@ -76,7 +76,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'lint': ['--abbrev-ref', '--abort', '--accept-pending', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-accept-pending', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all', '--wait'],
'loops': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--adopt-columns', '--adopt-permissions', '--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--id', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-legacy', '--migrate-only', '--multimodal', '--ner', '--no-autopilot-install', '--no-embed', '--no-pull', '--older-than', '--only', '--operations', '--pack', '--page', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supabase', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--sources', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--accept-pending', '--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--wait', '--yes'],
'models': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status', '--to'],
@@ -87,7 +87,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'orphans': ['--accept-pending', '--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--path', '--probe', '--source', '--vectors', '--yes'],
- 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],
'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
'protocol': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--url', '--yes'],
@@ -96,7 +96,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],
'recall': ['--accept-pending', '--access', '--add', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--supersessions', '--surface', '--timeout', '--to', '--today', '--url', '--wait', '--watch', '--yes'],
'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'reindex': ['--accept-pending', '--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
+ 'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--manifest', '--markdown', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--self-transfer', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],
'reindex-code': ['--accept-pending', '--apply', '--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--trust', '--wait', '--workers', '--yes'],
'reindex-frontmatter': ['--apply', '--brain', '--concurrency', '--dry-run', '--expect', '--force', '--help', '--json', '--max-cost', '--max-usd', '--non-interactive', '--slug-prefix', '--source', '--trust', '--workers', '--yes'],
'reindex-search-vector': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--resume', '--source', '--timeout', '--wait', '--yes'],
@@ -122,11 +122,11 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--retry-held', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--accept-pending', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],
- 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--accept-pending', '--account', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--only', '--operations', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--accept-pending', '--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],
- 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
+ 'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--add', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--url', '--yes'],
diff --git a/src/core/config.ts b/src/core/config.ts
index 60c1fb60d9..285cef03a7 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1565,6 +1565,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// reconcile-links, and sweep. The documented off-switch is `gbrain config
// set auto_link false` — same unregistered-key class as auto_chronicle.
'auto_link',
+ // Entity mention index (core/mentions/policy.ts): off switch, +type/-type linkable types, names never linked.
+ 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore',
// #4987: the write-path timeline extractor's off switch (read by
// isAutoTimelineEnabled); registered so `gbrain config set auto_timeline off`
// works without --force, as the compiled-truth guide documents.
diff --git a/src/core/cycle.ts b/src/core/cycle.ts
index 4ae8dad37a..de91dc5935 100644
--- a/src/core/cycle.ts
+++ b/src/core/cycle.ts
@@ -1389,7 +1389,7 @@ async function runPhaseExtract(
stale_pages_drained: drained.pagesProcessed,
stale_links_created: drained.linksCreated,
stale_timeline_created: drained.timelineCreated,
- staleRemaining: drained.staleRemaining,
+ staleRemaining: drained.staleRemaining, ...(drained.mentions ? { mention_pages: drained.mentions.pages, mention_links_created: drained.mentions.created, mention_due: drained.mentions.remaining, mention_state: drained.mentions.state } : {}),
};
} catch (e) {
staleDetails = { stale_drain_error: e instanceof Error ? e.message : String(e) };
diff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.ts
index c68767a24f..6f4a71b874 100644
--- a/src/core/engine-sql/pages.ts
+++ b/src/core/engine-sql/pages.ts
@@ -859,7 +859,11 @@ export async function updateSlug(exec: SqlExecutor, tx: BrainEngine, oldSlug: st
return moved.length;
}
-/** Replace a page's alias set under its page-key lock, inside the engine's transaction. */
+/**
+ * Replace a page's frontmatter alias set under its page-key lock, inside the
+ * engine's transaction. Derived rows (`origin` declared/subject, written by
+ * the mention pass) are left alone.
+ */
export async function setPageAliases(
exec: SqlExecutor,
tx: Pick<BrainEngine, 'lockPageKeys'>,
@@ -869,7 +873,7 @@ export async function setPageAliases(
): Promise<void> {
const uniq = Array.from(new Set(aliasNorms.filter(a => a.length > 0)));
await tx.lockPageKeys([{ sourceId, slug }]);
- await exec.executeRaw('DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ await exec.executeRaw("DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 AND origin='frontmatter'", [sourceId, slug]);
if (!uniq.length) return;
await exec.executeRaw(`INSERT INTO page_aliases (source_id,alias_norm,slug)
SELECT $1,a,$2 FROM unnest($3::text[]) AS a ON CONFLICT DO NOTHING`, [sourceId, slug, uniq]);
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 2a789918c2..9d6ab34884 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -319,6 +319,7 @@ export const NOTICE_CODES = {
no_worker: { kind: 'degraded', summary: 'A job was queued but no worker is running to execute it; it waits until a worker runs.' },
unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },
listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },
+ mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },
degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence.' },
source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },
degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },
diff --git a/src/core/import-file.ts b/src/core/import-file.ts
index b15c1ac1be..f8f4da9824 100644
--- a/src/core/import-file.ts
+++ b/src/core/import-file.ts
@@ -50,7 +50,8 @@ import {
modeRequiresWrapper,
wrapChunkForEmbedding,
} from './embedding-context.ts';
-import { normalizeAliasList } from './search/alias-normalize.ts';
+import { writePageAliases } from './mentions/pass.ts';
+import { readMentionPolicy } from './mentions/policy.ts';
import { warnOncePerProcess, validateSlug, contentHash, contentHashLegacy, ATOMS_SCAN_HASH_KEY } from './utils.ts';
import { decorateEmbeddingDimError } from './embedding-dim-check.ts';
import { resolveImportContextualMode } from './import-contextual-mode.ts';
@@ -821,7 +822,7 @@ export async function importFromContent(
// for single-source callers.
const txOpts = { sourceId: sourceId ?? 'default' };
let persistedProjection: ProjectionSnapshot | null = null;
- const timeZone = await loadBrainTimeZone(engine);
+ const [timeZone, mentionPolicy] = await Promise.all([loadBrainTimeZone(engine), readMentionPolicy(engine).catch(() => null)]);
const applyPrepared = async (tx: BrainEngine) => {
await assertImportBase(tx, slug, txOpts.sourceId, existing);
await assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug);
@@ -965,7 +966,7 @@ export async function importFromContent(
}
// Alias projection and readback share the page commit. A later writer can
// no longer turn a successful import into a postcommit verification error.
- await tx.setPageAliases(slug, sourceId ?? 'default', normalizeAliasList(parsed.frontmatter.aliases));
+ await writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy);
await verifyPageReadable(tx, slug, hash, sourceId, 'importFromContent');
await opts.beforeCommit?.(tx, slug);
if (opts.onPostCommitEmbedding && !opts.noEmbed && chunks.length > 0) {
diff --git a/src/core/mentions/aliases.ts b/src/core/mentions/aliases.ts
new file mode 100644
index 0000000000..7691070417
--- /dev/null
+++ b/src/core/mentions/aliases.ts
@@ -0,0 +1,111 @@
+/**
+ * Derived names of an entity page: its title subject and the aliases its body
+ * declares. Search's declared-name fan-out (`aliasDeclarations`, ops/search.ts)
+ * and the mention pass's alias refresh share `declaredNames`, so both read the
+ * same declarations with the same post-filters.
+ *
+ * - Title subject: for a title with a prefix ending in `: ` ("CRM record:
+ * Acme Example"), the text after the last `: `. Stored with
+ * `origin='subject'`; an exact page title in the same source outranks it.
+ * - Declarations: `account code`, `also known as`, `a.k.a.`, `aka`, `short
+ * name`, `ticker`, `code name`, read from the body with private takes and
+ * facts fences stripped, so a private code never becomes a public name.
+ * Stored with `origin='declared'`. A single-token declaration matches only
+ * as written (`case_sensitive`), so "aka Mark" never links lowercase "mark".
+ */
+
+import { normalizeAlias } from '../search/alias-normalize.ts';
+import { stripTakesFence } from '../takes-fence.ts';
+import { stripFactsFence } from '../facts-fence.ts';
+import { isGenericEntityToken } from '../entity-name-quality.ts';
+import { hasCJK, tokenizeTitle } from '../by-mention.ts';
+
+export const ALIAS_DECLARATION = /\b(?:account code|also known as|a\.k\.a\.|aka|short name|ticker|code name)\b\s*[:(]?\s*["\u201c']?([A-Z0-9][A-Za-z0-9&.-]{1,24})/gi;
+/** Every ALIAS_DECLARATION keyword, lowercased: a text containing none of them cannot match the regex. */
+export const DECLARATION_KEYWORDS = ['account code', 'also known as', 'a.k.a', 'aka', 'short name', 'ticker', 'code name'];
+
+/** Below this many characters a (non-CJK) name is never linked or stored as a derived alias. */
+export const MIN_ALIAS_LENGTH = 4;
+
+/** The text after the last `: ` of a title, or the whole title when it has no such prefix. */
+export function titleName(title: string): string {
+ return (title ?? '').split(':').pop()!.trim();
+}
+
+/** The subject of a prefixed title ("CRM record: X" → "X"); null when the title has no `: ` prefix. */
+export function titleSubject(title: string | null | undefined): string | null {
+ const t = (title ?? '').trim();
+ const at = t.lastIndexOf(': ');
+ if (at < 0) return null;
+ const subject = t.slice(at + 2).trim();
+ return subject && subject !== t ? subject : null;
+}
+
+/** Names `text` declares for the entity called `name`, post-filtered (punctuation trimmed, an uppercase letter or digit, differs from the name). */
+export function declaredNames(text: string, name: string): string[] {
+ const lower = text.toLowerCase();
+ if (!DECLARATION_KEYWORDS.some(k => lower.includes(k))) return [];
+ const out: string[] = [];
+ for (const m of text.matchAll(ALIAS_DECLARATION)) {
+ const alias = m[1].replace(/[.,;]+$/, '');
+ if (!/[A-Z0-9]/.test(alias) || alias.toLowerCase() === name.toLowerCase()) continue;
+ if (!out.includes(alias)) out.push(alias);
+ }
+ return out;
+}
+
+export type AliasOrigin = 'frontmatter' | 'declared' | 'subject';
+export const ALIAS_ORIGIN_RANK: Record<AliasOrigin, number> = { frontmatter: 0, declared: 1, subject: 2 };
+
+export interface DerivedAlias {
+ alias_norm: string;
+ /** The alias as written. */
+ alias_text: string;
+ origin: 'declared' | 'subject';
+ case_sensitive: boolean;
+}
+
+export type AliasRejection = 'below_min_length' | 'generic_token' | 'ambiguous_first_word';
+
+/** Private takes and facts fences removed: the text a world reader may see. */
+export function publicBody(body: string): string {
+ return stripFactsFence(stripTakesFence(body ?? ''), { keepVisibility: ['world'] });
+}
+
+/** Why a derived name can never be linked or stored; null when it can. */
+export function aliasRejection(alias: string, ownName: string): AliasRejection | null {
+ const tokens = tokenizeTitle(alias);
+ if (!hasCJK(alias) && alias.length < MIN_ALIAS_LENGTH) return 'below_min_length';
+ if (tokens.length === 1 && isGenericEntityToken(tokens[0]!)) return 'generic_token';
+ const first = tokenizeTitle(ownName)[0];
+ if (tokens.length === 1 && first && tokens[0] === first && tokenizeTitle(ownName).length > 1) return 'ambiguous_first_word';
+ return null;
+}
+
+/**
+ * The derived alias rows of one entity page: its title subject and its body
+ * declarations, deduped by normalized form (subject first). Rejected names
+ * are returned beside the kept ones for `extract mentions --explain`.
+ */
+export function deriveEntityAliases(page: { title: string | null; compiled_truth: string | null; timeline?: string | null }): {
+ aliases: DerivedAlias[]; rejected: Array<{ alias: string; origin: 'declared' | 'subject'; reason: AliasRejection }>;
+} {
+ const title = page.title ?? '';
+ const name = titleName(title);
+ const aliases: DerivedAlias[] = [];
+ const rejected: Array<{ alias: string; origin: 'declared' | 'subject'; reason: AliasRejection }> = [];
+ const seen = new Set<string>([normalizeAlias(title)]);
+ const push = (alias: string, origin: 'declared' | 'subject', caseSensitive: boolean) => {
+ const norm = normalizeAlias(alias);
+ if (!norm || seen.has(norm)) return;
+ const reason = aliasRejection(alias, name);
+ if (reason) { rejected.push({ alias, origin, reason }); return; }
+ seen.add(norm);
+ aliases.push({ alias_norm: norm, alias_text: alias, origin, case_sensitive: caseSensitive });
+ };
+ const subject = titleSubject(title);
+ if (subject) push(subject, 'subject', false);
+ const text = publicBody(`${page.compiled_truth ?? ''}\n\n${page.timeline ?? ''}`);
+ for (const alias of declaredNames(text, name)) push(alias, 'declared', tokenizeTitle(alias).length === 1);
+ return { aliases, rejected };
+}
diff --git a/src/core/mentions/coverage.ts b/src/core/mentions/coverage.ts
new file mode 100644
index 0000000000..bef641ae04
--- /dev/null
+++ b/src/core/mentions/coverage.ts
@@ -0,0 +1,101 @@
+/**
+ * `coverage` on entity cards, entity misses and get_backlinks: whether every
+ * page in the caller's permitted sources has been scanned for recognized
+ * names. Read from the per-source status row the mention pass maintains plus
+ * the due pages written since its last count (an indexed read over recent
+ * pages per source), never a whole-brain scan, and never another source's
+ * state.
+ *
+ * States: `complete`; `pending` (pages written or invalidated since the last
+ * pass, or no pass yet); `disabled` (auto_link or mentions.auto_link is off);
+ * `type_not_linkable` (cards only: nothing links to this page type by
+ * mention); `failed` (the last pass could not build the index). Any state but
+ * `complete` carries `degraded: true` and a `[gbrain notice mention_index]`.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import type { Notice } from '../agent-output.ts';
+import { readMentionPolicy } from './policy.ts';
+import { MENTION_EXTRACTOR_VERSION } from './pass.ts';
+
+export type CoverageState = 'complete' | 'pending' | 'disabled' | 'type_not_linkable' | 'failed';
+
+export interface MentionCoverage {
+ state: CoverageState;
+ pending_pages: number;
+ last_pass_at: string | null;
+ degraded?: true;
+}
+
+const toIso = (v: unknown): string | null => {
+ if (v == null) return null;
+ const ms = v instanceof Date ? v.getTime() : Date.parse(String(v));
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
+};
+
+/** Coverage over `sourceIds` (the caller's permitted sources). */
+export async function readMentionCoverage(engine: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, sourceIds: string[]): Promise<MentionCoverage> {
+ const policy = await readMentionPolicy(engine);
+ const rows = await engine.executeRaw<{ source_id: string; state: string; pending: number; counted_at: unknown; last_pass_at: unknown }>(
+ `SELECT source_id, state, pending, counted_at, last_pass_at FROM mention_index_status WHERE source_id = ANY($1::text[])`, [sourceIds]);
+ const bySource = new Map(rows.map(r => [r.source_id, r]));
+ let pending = 0;
+ let failed = false;
+ let last: string | null = null;
+ for (const sourceId of sourceIds) {
+ const row = bySource.get(sourceId);
+ const lastPass = toIso(row?.last_pass_at);
+ if (lastPass && (!last || lastPass > last)) last = lastPass;
+ if (!policy.enabled) continue;
+ if (!row || row.state === 'disabled') {
+ const [n] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id = $1 AND deleted_at IS NULL', [sourceId]);
+ pending += Number(n?.n ?? 0);
+ continue;
+ }
+ if (row.state === 'failed') failed = true;
+ // Pages written at or after the last count that are not scanned at their current content (the index on updated_at keeps it small).
+ const [since] = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
+ WHERE p.source_id = $1 AND p.updated_at >= $2::timestamptz AND p.deleted_at IS NULL
+ AND (s.page_id IS NULL OR s.mention_revision IS DISTINCT FROM p.knowledge_revision OR s.mention_version IS DISTINCT FROM $3)`,
+ [sourceId, toIso(row.counted_at) ?? '-infinity', MENTION_EXTRACTOR_VERSION]);
+ pending += Number(row.pending ?? 0) + Number(since?.n ?? 0);
+ }
+ const state: CoverageState = !policy.enabled ? 'disabled' : failed ? 'failed' : pending > 0 ? 'pending' : 'complete';
+ return { state, pending_pages: policy.enabled ? pending : 0, last_pass_at: last, ...(state === 'complete' ? {} : { degraded: true as const }) };
+}
+
+const WHY: Record<Exclude<CoverageState, 'complete'>, (c: MentionCoverage) => string> = {
+ pending: c => `${c.pending_pages} page(s) have not been scanned for entity names yet, so references from them are missing; ` +
+ 'a short or empty list is not proof that nothing else mentions this entity.',
+ disabled: () => 'Mention linking is off (auto_link or mentions.auto_link is false), so only explicit links are listed, not pages that name this entity.',
+ type_not_linkable: () => 'This page type is not a linkable entity type, so pages that only name it are not listed; explicit links are. ' +
+ 'Add the type with `gbrain config set mentions.entity_types +<type>` to link it.',
+ failed: () => 'The last mention pass could not build the name index, so references may be missing or stale.',
+};
+
+/**
+ * The model-visible notice for a degraded coverage; null when complete.
+ * Pending and failed indexes name the free catch-up sweep; a policy state
+ * (disabled, type not linkable) names the setting the user controls.
+ */
+export function mentionCoverageNotice(coverage: MentionCoverage, entityType?: string | null): Notice | null {
+ if (coverage.state === 'complete') return null;
+ const why = WHY[coverage.state](coverage);
+ if (coverage.state === 'disabled') {
+ return { code: 'mention_index', kind: 'degraded', why, fix: { argv: ['gbrain', 'config', 'set', 'mentions.auto_link', 'true'], consent: [],
+ actor: 'user', requires_exclusive: false, why: 'Turns mention linking back on; the next `gbrain extract --stale` links every page.',
+ verify: { argv: ['gbrain', 'config', 'get', 'mentions.auto_link'] } } };
+ }
+ if (coverage.state === 'type_not_linkable') {
+ return { code: 'mention_index', kind: 'degraded', why, fix: { argv: ['gbrain', 'config', 'set', 'mentions.entity_types', `+${entityType ?? '<type>'}`],
+ consent: [], actor: 'user', requires_exclusive: false, why: 'Makes this page type linkable; the next `gbrain extract --stale` links pages that name it.',
+ verify: { argv: ['gbrain', 'config', 'get', 'mentions.entity_types'] } } };
+ }
+ return {
+ code: 'mention_index', kind: 'degraded', why,
+ fix: { argv: ['gbrain', 'extract', '--stale', '--catch-up'], consent: [], actor: 'agent', requires_exclusive: false,
+ verify: { argv: ['gbrain', 'doctor', '--only', 'links_extraction_lag', '--json'] },
+ why: 'Scans the pending pages for entity names and links them; free (no model calls). Then call entity again.' },
+ };
+}
diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.ts
new file mode 100644
index 0000000000..9776960f55
--- /dev/null
+++ b/src/core/mentions/pass.ts
@@ -0,0 +1,523 @@
+/**
+ * The mention pass: keeps entity pages' derived aliases and every page's
+ * `link_source='mentions'` links current, incrementally, from `gbrain extract
+ * --stale` and the managed stale path (sync's inline extraction stays
+ * link-only).
+ *
+ * One pass, per source in scope:
+ * 1. Policy. `auto_link=false` or `mentions.auto_link=false` removes plain
+ * mention links and derived alias rows once and records `disabled`;
+ * re-enabling makes every page due. A change of the linkable type set,
+ * cross-source policy or ignore list makes every page due once.
+ * 2. Alias refresh: linkable entity pages whose derived aliases were
+ * refreshed at another content revision (or alias version) get their
+ * `declared` and `subject` rows rewritten; pages that stopped being
+ * entities lose them. Frontmatter rows are never touched. Managed
+ * brains write through the coordinated writer (`page_aliases` is guarded).
+ * 3. Authoritative gazetteer: a pack or alias read that fails writes
+ * nothing and records `failed` with the error.
+ * 4. Entry diff: the gazetteer's (source, name, target, case) entries are
+ * compared with the saved set under an advisory lock; on change the set
+ * is saved, the source generation bumps, and only pages the change can
+ * affect are marked due (pages linking to a removed or retargeted
+ * target, plus pages whose text matches an added name through the real
+ * tokenizer, prefiltered by a substring superset).
+ * 5. Reconcile due pages (content revision, extractor version or an
+ * invalidation differs): per batch, publish only when the source
+ * generations and each page's content revision are unchanged since the
+ * scan read them (conditional publish), so an edit or a gazetteer change
+ * during the scan leaves the page due. Only plain mention rows are
+ * touched; `typed_ner` rows stay.
+ * 6. Status row: state, pending pages, last pass, generation. `coverage`
+ * on entity cards and get_backlinks reads it.
+ *
+ * MENTION_EXTRACTOR_VERSION is separate from LINK_EXTRACTOR_VERSION_TS, so a
+ * gazetteer change never reruns link or timeline extraction.
+ */
+
+import { createHash } from 'node:crypto';
+import type { BrainEngine, LinkBatchInput } from '../engine.ts';
+import { isCrossSourceLinksEnabled } from '../link-extraction.ts';
+import {
+ buildGazetteer, findMentionedEntities, gazetteerEntryKeys, tokenizeTitle,
+ type Gazetteer, type GazetteerEntry, type GazetteerEntryKey,
+} from '../by-mention.ts';
+import { linkableTypesFor, loadSourcePack, parseNameList, readMentionPolicy, type MentionPolicy, type PackTypes } from './policy.ts';
+import { deriveEntityAliases, type DerivedAlias } from './aliases.ts';
+import { normalizeAliasList } from '../search/alias-normalize.ts';
+import { withCoordinatedWrite } from '../persistence/context.ts';
+import { maintenanceAttribution } from '../persistence/attribution.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+
+/** Bump to rescan every page's mentions once (gazetteer or scanner behavior change). */
+export const MENTION_EXTRACTOR_VERSION = 1;
+/** Bump to re-derive every entity page's declared aliases and title subject once. */
+export const ALIAS_DERIVATION_VERSION = 1;
+
+const RECONCILE_BATCH = 200;
+const ALIAS_BATCH = 200;
+const PREFILTER_BATCH = 500;
+
+export type MentionState = 'complete' | 'pending' | 'disabled' | 'failed';
+
+export interface MentionPassResult {
+ /** Pages whose mention links were reconciled and published. */
+ pages: number;
+ created: number;
+ removed: number;
+ /** Pages left due because they (or the gazetteer) changed during the scan. */
+ skipped: number;
+ /** Entity pages whose derived alias rows changed. */
+ aliasPages: number;
+ /** Mention-due pages after the pass. */
+ remaining: number;
+ state: MentionState;
+ error?: string;
+}
+
+export interface MentionPassOpts {
+ sourceId?: string;
+ /** Epoch ms; the pass stops between batches after it. Absent = run to completion. */
+ deadline?: number;
+ signal?: AbortSignal;
+ /** Test seam: runs after a batch is scanned and before it is published. */
+ beforePublish?: (pageIds: number[]) => Promise<void>;
+}
+
+const DUE_PREDICATE = `(s.page_id IS NULL OR s.mention_revision IS DISTINCT FROM p.knowledge_revision OR s.mention_version IS DISTINCT FROM $2)`;
+
+/** Mention-due live pages, per source (or one source). */
+export async function countMentionDuePages(engine: Pick<BrainEngine, 'executeRaw'>, sourceId?: string): Promise<number> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
+ WHERE p.deleted_at IS NULL AND ($1::text IS NULL OR p.source_id = $1) AND ${DUE_PREDICATE}`,
+ [sourceId ?? null, MENTION_EXTRACTOR_VERSION]);
+ return Number(rows[0]?.n ?? 0);
+}
+
+async function sourcesInScope(engine: BrainEngine, sourceId?: string): Promise<string[]> {
+ if (sourceId) return [sourceId];
+ const rows = await engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id');
+ return rows.map(r => r.id);
+}
+
+function policyFingerprint(types: string[], crossSource: boolean, policy: MentionPolicy): string {
+ return createHash('sha256').update(JSON.stringify({
+ types, crossSource, ignore: [...policy.ignore].map(n => n.toLowerCase()).sort(),
+ })).digest('hex').slice(0, 16);
+}
+
+async function writeStatus(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, patch: {
+ state: MentionState; pending?: number; error?: string | null; lastPassAt?: string | null; bumpGeneration?: boolean; fingerprint?: string | null;
+}): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO mention_index_status (source_id, generation, state, pending, counted_at, last_pass_at, policy_fingerprint, error, updated_at)
+ VALUES ($1, CASE WHEN $6::boolean THEN 1 ELSE 0 END, $2, COALESCE($3::int, 0), now(), $4::timestamptz, $7, $5, now())
+ ON CONFLICT (source_id) DO UPDATE SET
+ state = EXCLUDED.state,
+ pending = COALESCE($3::int, mention_index_status.pending),
+ counted_at = CASE WHEN $3::int IS NULL THEN mention_index_status.counted_at ELSE now() END,
+ last_pass_at = COALESCE($4::timestamptz, mention_index_status.last_pass_at),
+ error = $5,
+ generation = mention_index_status.generation + CASE WHEN $6::boolean THEN 1 ELSE 0 END,
+ policy_fingerprint = CASE WHEN $8::boolean THEN $7 ELSE mention_index_status.policy_fingerprint END,
+ updated_at = now()`,
+ [sourceId, patch.state, patch.pending ?? null, patch.lastPassAt ?? null, patch.error ?? null, patch.bumpGeneration === true,
+ patch.fingerprint ?? null, patch.fingerprint !== undefined]);
+}
+
+/** Run `fn` in a transaction; on a managed brain, as a coordinated write for `sourceId` (page_aliases is guarded). */
+async function aliasWrite<T>(engine: BrainEngine, managed: boolean, sourceId: string, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ if (!managed) return engine.transaction(fn);
+ const attribution = await maintenanceAttribution(engine);
+ return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], () => fn(tx), attribution));
+}
+
+/**
+ * Replace one page's derived alias rows (declared, subject) with what its
+ * current title and body yield, inside the caller's transaction (import and
+ * `reindex --aliases`; on a managed brain the caller holds the coordinated
+ * write). A page that is not a linkable entity, or linking that is off,
+ * leaves no derived rows. Frontmatter rows are untouched.
+ */
+export async function writeDerivedAliases(tx: Pick<BrainEngine, 'executeRaw' | 'getConfig'>, sourceId: string,
+ page: { slug: string; title: string | null; type: string | null; compiled_truth: string | null; timeline?: string | null },
+ opts: { pack?: PackTypes | null; policy?: MentionPolicy | null } = {}): Promise<number> {
+ // A config read that fails (null policy) leaves the rows for the next sweep rather than failing the caller's write.
+ const policy = opts.policy !== undefined ? opts.policy : await readMentionPolicy(tx).catch(() => null);
+ if (!policy) return 0;
+ const types = policy.enabled ? linkableTypesFor(opts.pack !== undefined ? opts.pack : await loadSourcePack(tx, sourceId), policy) : [];
+ const aliases = types.includes(page.type ?? '') ? deriveEntityAliases(page).aliases : [];
+ await tx.executeRaw(`DELETE FROM page_aliases WHERE source_id = $1 AND slug = $2 AND origin IN ('declared','subject')`, [sourceId, page.slug]);
+ if (aliases.length) {
+ await tx.executeRaw(
+ `INSERT INTO page_aliases (source_id, alias_norm, slug, origin, case_sensitive, alias_text)
+ SELECT $1, a, $2, o, c::boolean, t FROM unnest($3::text[], $4::text[], $5::text[], $6::text[]) AS x(a, o, c, t) ON CONFLICT DO NOTHING`,
+ [sourceId, page.slug, aliases.map(a => a.alias_norm), aliases.map(a => a.origin), aliases.map(a => String(a.case_sensitive)), aliases.map(a => a.alias_text)]);
+ }
+ return aliases.length;
+}
+
+/**
+ * Import's alias projection: the page's frontmatter aliases and, for a
+ * linkable entity page, its derived aliases. Import never loads a schema
+ * pack itself: it uses the pack the caller already resolved (none: the four
+ * always-linkable types), and the next sweep refreshes with the source's pack.
+ * The caller reads the mention policy before its transaction opens.
+ */
+export async function writePageAliases(tx: BrainEngine, slug: string, sourceId: string,
+ page: { title: string; type: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown> }, pack: unknown,
+ policy: MentionPolicy | null): Promise<void> {
+ await tx.setPageAliases(slug, sourceId, normalizeAliasList(page.frontmatter.aliases));
+ await writeDerivedAliases(tx, sourceId, { slug, ...page }, { pack: (pack as PackTypes | undefined) ?? null, policy });
+}
+
+/** Turn the index off for one source: plain mention links, derived aliases, entries and page state go; typed_ner rows stay. */
+async function disableSource(engine: BrainEngine, managed: boolean, sourceId: string): Promise<number> {
+ let removed = 0;
+ await aliasWrite(engine, managed, sourceId, async tx => {
+ const rows = await tx.executeRaw<{ id: number }>(
+ `DELETE FROM links l USING pages f
+ WHERE f.id = l.from_page_id AND f.source_id = $1 AND l.link_source = 'mentions'
+ AND (l.link_kind IS NULL OR l.link_kind = 'plain') RETURNING l.id`, [sourceId]);
+ removed = rows.length;
+ await tx.executeRaw(`DELETE FROM page_aliases WHERE source_id = $1 AND origin IN ('declared','subject')`, [sourceId]);
+ await tx.executeRaw('DELETE FROM mention_gazetteer_entries WHERE source_id = $1', [sourceId]);
+ await tx.executeRaw('DELETE FROM page_mention_state WHERE source_id = $1', [sourceId]);
+ await writeStatus(tx, sourceId, { state: 'disabled', pending: 0, error: null, bumpGeneration: true, fingerprint: null });
+ });
+ return removed;
+}
+
+interface DuePage { id: number; slug: string; source_id: string; revision: string; title: string | null; type: string | null;
+ compiled_truth: string | null; timeline: string | null; mention_ignore: unknown }
+
+/** Refresh derived alias rows of due entity pages in one source; returns pages whose rows changed. */
+async function refreshAliases(engine: BrainEngine, managed: boolean, sourceId: string, types: string[], deadline: number): Promise<number> {
+ let changed = 0;
+ // Pages that stopped being linkable entities (retype, pack change, deletion) lose their derived rows.
+ const stale = await engine.executeRaw<{ slug: string }>(
+ `SELECT DISTINCT pa.slug FROM page_aliases pa
+ LEFT JOIN pages p ON p.slug = pa.slug AND p.source_id = pa.source_id
+ WHERE pa.source_id = $1 AND pa.origin IN ('declared','subject')
+ AND (p.id IS NULL OR p.deleted_at IS NOT NULL OR NOT (p.type = ANY($2::text[])))`, [sourceId, types]);
+ if (stale.length) {
+ await aliasWrite(engine, managed, sourceId, tx => tx.executeRaw(
+ `DELETE FROM page_aliases WHERE source_id = $1 AND slug = ANY($2::text[]) AND origin IN ('declared','subject')`,
+ [sourceId, stale.map(r => r.slug)]));
+ changed += stale.length;
+ }
+ let after = 0;
+ for (;;) {
+ if (Date.now() > deadline) break;
+ const pages = await engine.executeRaw<DuePage>(
+ `SELECT p.id, p.slug, p.source_id, p.knowledge_revision::text AS revision, p.title, p.type, p.compiled_truth, p.timeline, NULL AS mention_ignore
+ FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.type = ANY($2::text[]) AND p.id > $3
+ AND (s.page_id IS NULL OR s.alias_revision IS DISTINCT FROM p.knowledge_revision OR s.alias_version IS DISTINCT FROM $4)
+ ORDER BY p.id LIMIT $5`, [sourceId, types, after, ALIAS_DERIVATION_VERSION, ALIAS_BATCH]);
+ if (!pages.length) break;
+ after = pages[pages.length - 1]!.id;
+ const desired = new Map(pages.map(p => [p.slug, deriveEntityAliases(p).aliases]));
+ const existing = await engine.executeRaw<{ slug: string; alias_norm: string; origin: string; case_sensitive: boolean; alias_text: string | null }>(
+ `SELECT slug, alias_norm, origin, case_sensitive, alias_text FROM page_aliases
+ WHERE source_id = $1 AND slug = ANY($2::text[]) AND origin IN ('declared','subject')`, [sourceId, pages.map(p => p.slug)]);
+ const key = (a: { alias_norm: string; origin: string; case_sensitive: boolean; alias_text: string | null }) =>
+ `${a.alias_norm}\0${a.origin}\0${a.case_sensitive}\0${a.case_sensitive ? a.alias_text : ''}`;
+ const have = new Map<string, Set<string>>();
+ for (const row of existing) {
+ const set = have.get(row.slug) ?? new Set<string>();
+ set.add(key(row));
+ have.set(row.slug, set);
+ }
+ const rewrite = pages.filter(p => {
+ const want = new Set((desired.get(p.slug) ?? []).map(a => key({ ...a, alias_text: a.alias_text })));
+ const got = have.get(p.slug) ?? new Set<string>();
+ return want.size !== got.size || [...want].some(k => !got.has(k));
+ });
+ await aliasWrite(engine, managed, sourceId, async tx => {
+ const current = new Map((await tx.executeRaw<{ id: number; revision: string }>(
+ `SELECT id, knowledge_revision::text AS revision FROM pages WHERE id = ANY($1::int[]) AND deleted_at IS NULL`,
+ [pages.map(p => p.id)])).map(r => [Number(r.id), r.revision]));
+ const fresh = pages.filter(p => current.get(Number(p.id)) === p.revision);
+ const freshRewrite = rewrite.filter(p => current.get(Number(p.id)) === p.revision);
+ if (freshRewrite.length) {
+ await tx.executeRaw(`DELETE FROM page_aliases WHERE source_id = $1 AND slug = ANY($2::text[]) AND origin IN ('declared','subject')`,
+ [sourceId, freshRewrite.map(p => p.slug)]);
+ const rows = freshRewrite.flatMap(p => (desired.get(p.slug) ?? []).map((a: DerivedAlias) => ({ slug: p.slug, ...a })));
+ if (rows.length) {
+ await tx.executeRaw(
+ `INSERT INTO page_aliases (source_id, alias_norm, slug, origin, case_sensitive, alias_text)
+ SELECT $1, a, s, o, c::boolean, t FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[]) AS x(a, s, o, c, t)
+ ON CONFLICT DO NOTHING`,
+ [sourceId, rows.map(r => r.alias_norm), rows.map(r => r.slug), rows.map(r => r.origin), rows.map(r => String(r.case_sensitive)), rows.map(r => r.alias_text)]);
+ }
+ }
+ if (fresh.length) {
+ await tx.executeRaw(
+ `INSERT INTO page_mention_state (page_id, source_id, alias_revision, alias_version, aliases_refreshed_at)
+ SELECT id, $1, rev::uuid, $4, now() FROM unnest($2::int[], $3::text[]) AS x(id, rev)
+ ON CONFLICT (page_id) DO UPDATE SET alias_revision = EXCLUDED.alias_revision, alias_version = EXCLUDED.alias_version,
+ aliases_refreshed_at = EXCLUDED.aliases_refreshed_at`,
+ [sourceId, fresh.map(p => p.id), fresh.map(p => p.revision), ALIAS_DERIVATION_VERSION]);
+ }
+ changed += freshRewrite.length;
+ });
+ }
+ return changed;
+}
+
+/** Live pages in `sourceIds` whose text the mini-gazetteer of `added` matches (real tokenizer, substring-superset prefilter). */
+async function pagesMatchingNames(engine: BrainEngine, sourceIds: string[], added: Gazetteer, allowCrossSource: boolean): Promise<number[]> {
+ const longest = [...added.values()].flat().map(e => [...e.tokens].sort((a, b) => b.length - a.length)[0]!);
+ // ASCII tokens: lower() in SQL agrees with the scanner's NFC+toLowerCase, so LIKE is a superset.
+ // Otherwise every page in scope is scanned in JS.
+ const ascii = longest.every(t => /^[\x20-\x7e]+$/.test(t));
+ const patterns = [...new Set(longest)].map(t => `%${t.replace(/[\\%_]/g, m => `\\${m}`)}%`);
+ const out: number[] = [];
+ let after = 0;
+ for (;;) {
+ const rows = await engine.executeRaw<{ id: number; slug: string; source_id: string; body: string; mention_ignore: unknown }>(
+ `SELECT id, slug, source_id, COALESCE(title, '') || E'\\n\\n' || COALESCE(compiled_truth, '') || E'\\n\\n' || COALESCE(timeline, '') AS body,
+ frontmatter->'mention_ignore' AS mention_ignore
+ FROM pages WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND id > $2
+ ${ascii ? `AND lower(COALESCE(title, '') || ' ' || COALESCE(compiled_truth, '') || ' ' || COALESCE(timeline, '')) LIKE ANY($4::text[])` : ''}
+ ORDER BY id LIMIT $3`,
+ ascii ? [sourceIds, after, PREFILTER_BATCH, patterns] : [sourceIds, after, PREFILTER_BATCH]);
+ if (!rows.length) break;
+ after = rows[rows.length - 1]!.id;
+ for (const r of rows) {
+ const hits = findMentionedEntities(r.body, added, { fromSlug: r.slug, fromSourceId: r.source_id, allowCrossSource });
+ if (hits.length) out.push(Number(r.id));
+ }
+ }
+ return out;
+}
+
+function miniGazetteer(gazetteer: Gazetteer, keys: Set<string>): Gazetteer {
+ const out: Gazetteer = new Map();
+ for (const [first, bucket] of gazetteer) {
+ const kept = bucket.filter(e => keys.has(entryKey(e)));
+ if (kept.length) out.set(first, kept);
+ }
+ return out;
+}
+
+function entryKey(e: GazetteerEntry | GazetteerEntryKey): string {
+ if ('target_slug' in e) return `${e.source_id}\0${e.name_norm}\0${e.target_slug}\0${e.case_sensitive}`;
+ return `${e.source_id}\0${(e.caseTokens ?? e.tokens).join(' ')}\0${e.slug}\0${!!e.caseTokens}`;
+}
+
+/**
+ * Diff the saved entry set of one source against `gazetteer`; on change, save
+ * it, bump the generation and mark affected pages due, in one transaction under
+ * the source's advisory lock. Returns whether the set changed.
+ */
+async function saveEntries(engine: BrainEngine, sourceId: string, gazetteer: Gazetteer, scopeSources: string[], allowCrossSource: boolean): Promise<boolean> {
+ const current = gazetteerEntryKeys(gazetteer).filter(k => k.source_id === sourceId);
+ const read = async (db: Pick<BrainEngine, 'executeRaw'>) => (await db.executeRaw<GazetteerEntryKey>(
+ 'SELECT source_id, name_norm, target_slug, case_sensitive FROM mention_gazetteer_entries WHERE source_id = $1', [sourceId]));
+ const before = await read(engine);
+ const beforeKeys = new Set(before.map(entryKey));
+ const currentKeys = new Set(current.map(entryKey));
+ const added = current.filter(k => !beforeKeys.has(entryKey(k)));
+ const removed = before.filter(k => !currentKeys.has(entryKey(k)));
+ if (!added.length && !removed.length) return false;
+ // The first save for a source marks the whole candidate scope due (cheap); later saves only affected pages.
+ const firstSave = before.length === 0;
+ let candidates: number[] = [];
+ if (!firstSave) {
+ const linked = removed.length ? await engine.executeRaw<{ id: number }>(
+ `SELECT DISTINCT l.from_page_id AS id FROM links l JOIN pages t ON t.id = l.to_page_id
+ WHERE t.source_id = $1 AND t.slug = ANY($2::text[]) AND l.link_source = 'mentions'`,
+ [sourceId, [...new Set(removed.map(k => k.target_slug))]]) : [];
+ const matched = added.length ? await pagesMatchingNames(engine, scopeSources,
+ miniGazetteer(gazetteer, new Set(added.map(entryKey))), allowCrossSource) : [];
+ candidates = [...new Set([...linked.map(r => Number(r.id)), ...matched])];
+ }
+ return engine.transaction(async tx => {
+ await tx.executeRaw('SELECT pg_advisory_xact_lock(hashtext($1)::bigint)', [`gbrain:mention-entries:${sourceId}`]);
+ const locked = await read(tx);
+ // Another sweep saved first: its pages and generation are authoritative; this pass's scan fails its conditional publish.
+ if (locked.length !== before.length || locked.some(k => !beforeKeys.has(entryKey(k)))) return true;
+ if (removed.length) {
+ await tx.executeRaw(
+ `DELETE FROM mention_gazetteer_entries e USING unnest($2::text[], $3::text[], $4::text[]) AS x(n, t, c)
+ WHERE e.source_id = $1 AND e.name_norm = x.n AND e.target_slug = x.t AND e.case_sensitive = x.c::boolean`,
+ [sourceId, removed.map(k => k.name_norm), removed.map(k => k.target_slug), removed.map(k => String(k.case_sensitive))]);
+ }
+ if (added.length) {
+ await tx.executeRaw(
+ `INSERT INTO mention_gazetteer_entries (source_id, name_norm, target_slug, case_sensitive)
+ SELECT $1, n, t, c::boolean FROM unnest($2::text[], $3::text[], $4::text[]) AS x(n, t, c) ON CONFLICT DO NOTHING`,
+ [sourceId, added.map(k => k.name_norm), added.map(k => k.target_slug), added.map(k => String(k.case_sensitive))]);
+ }
+ if (firstSave) {
+ await tx.executeRaw('UPDATE page_mention_state SET mention_revision = NULL WHERE source_id = ANY($1::text[])', [scopeSources]);
+ } else if (candidates.length) {
+ await tx.executeRaw('UPDATE page_mention_state SET mention_revision = NULL WHERE page_id = ANY($1::int[])', [candidates]);
+ }
+ await writeStatus(tx, sourceId, { state: 'pending', bumpGeneration: true });
+ return true;
+ });
+}
+
+async function readGenerations(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds: string[], lock: boolean): Promise<Map<string, string>> {
+ const rows = await engine.executeRaw<{ source_id: string; generation: string }>(
+ `SELECT source_id, generation::text AS generation FROM mention_index_status WHERE source_id = ANY($1::text[])${lock ? ' FOR SHARE' : ''}`,
+ [sourceIds]);
+ return new Map(rows.map(r => [r.source_id, r.generation]));
+}
+
+function sameGenerations(a: Map<string, string>, b: Map<string, string>): boolean {
+ if (a.size !== b.size) return false;
+ for (const [k, v] of a) if (b.get(k) !== v) return false;
+ return true;
+}
+
+/** Reconcile due pages of one source; returns counts and whether a gazetteer change stopped it. */
+async function reconcileSource(engine: BrainEngine, sourceId: string, gazetteer: Gazetteer, genSources: string[], allowCrossSource: boolean,
+ opts: MentionPassOpts, deadline: number, result: MentionPassResult): Promise<void> {
+ const generations = await readGenerations(engine, genSources, false);
+ let after = 0;
+ for (;;) {
+ opts.signal?.throwIfAborted();
+ if (Date.now() > deadline) return;
+ const pages = await engine.executeRaw<DuePage>(
+ `SELECT p.id, p.slug, p.source_id, p.knowledge_revision::text AS revision, p.title, p.type, p.compiled_truth, p.timeline,
+ p.frontmatter->'mention_ignore' AS mention_ignore
+ FROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id
+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.id > $3 AND ${DUE_PREDICATE}
+ ORDER BY p.id LIMIT $4`, [sourceId, MENTION_EXTRACTOR_VERSION, after, RECONCILE_BATCH]);
+ if (!pages.length) return;
+ after = pages[pages.length - 1]!.id;
+ const found = new Map(pages.map(p => [Number(p.id), (p.title || p.compiled_truth || p.timeline)
+ ? findMentionedEntities(`${p.title ?? ''}\n\n${p.compiled_truth ?? ''}\n\n${p.timeline ?? ''}`, gazetteer, {
+ fromSlug: p.slug, fromSourceId: p.source_id, allowCrossSource, ignoreNames: parseNameList(p.mention_ignore),
+ })
+ : []]));
+ await opts.beforePublish?.(pages.map(p => Number(p.id)));
+ const outcome = await engine.transaction(async tx => {
+ if (!sameGenerations(generations, await readGenerations(tx, genSources, true))) return null;
+ const current = new Map((await tx.executeRaw<{ id: number; revision: string }>(
+ `SELECT id, knowledge_revision::text AS revision FROM pages WHERE id = ANY($1::int[]) AND deleted_at IS NULL FOR SHARE`,
+ [pages.map(p => p.id)])).map(r => [Number(r.id), r.revision]));
+ const fresh = pages.filter(p => current.get(Number(p.id)) === p.revision);
+ if (!fresh.length) return { fresh: 0, created: 0, removed: 0 };
+ const rows = await tx.executeRaw<{ id: number; from_page_id: number; to_slug: string; to_source_id: string; plain: boolean }>(
+ `SELECT l.id, l.from_page_id, t.slug AS to_slug, t.source_id AS to_source_id,
+ (l.link_source = 'mentions' AND (l.link_kind IS NULL OR l.link_kind = 'plain')) AS plain
+ FROM links l JOIN pages t ON t.id = l.to_page_id WHERE l.from_page_id = ANY($1::int[])`,
+ [fresh.map(p => p.id)]);
+ const existing = rows.filter(r => r.plain);
+ // One link per page pair: a pair another producer already links (markdown, frontmatter, typed_ner, manual) gets no plain mention.
+ // A cross-source mention is also covered by an explicit link to the same slug in any source (the resolver may pick another twin).
+ const covered = new Set(rows.filter(r => !r.plain).flatMap(r => [`${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`, `${r.from_page_id}\0*\0${r.to_slug}`]));
+ const pageSource = new Map(fresh.map(p => [Number(p.id), p.source_id]));
+ const want = new Set(fresh.flatMap(p => (found.get(Number(p.id)) ?? [])
+ .filter(m => !covered.has(`${p.id}\0${m.source_id}\0${m.slug}`) && !(m.source_id !== pageSource.get(Number(p.id)) && covered.has(`${p.id}\0*\0${m.slug}`)))
+ .map(m => `${p.id}\0${m.source_id}\0${m.slug}`)));
+ const have = new Set(existing.map(r => `${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`));
+ const drop = existing.filter(r => !want.has(`${r.from_page_id}\0${r.to_source_id}\0${r.to_slug}`)).map(r => Number(r.id));
+ if (drop.length) await tx.executeRaw('DELETE FROM links WHERE id = ANY($1::int[])', [drop]);
+ const add: LinkBatchInput[] = fresh.flatMap(p => (found.get(Number(p.id)) ?? [])
+ .filter(m => want.has(`${p.id}\0${m.source_id}\0${m.slug}`) && !have.has(`${p.id}\0${m.source_id}\0${m.slug}`))
+ .map(m => ({ from_slug: p.slug, to_slug: m.slug, link_type: 'mentions', link_source: 'mentions', context: m.name,
+ from_source_id: p.source_id, to_source_id: m.source_id })));
+ const created = add.length ? await tx.addLinksBatch(add, { auditSite: 'extract.mentions' }) : 0; // gbrain-allow-direct-insert: mention pass — reconciling write of the scan's own plain mention rows
+ await tx.executeRaw(
+ `INSERT INTO page_mention_state (page_id, source_id, mention_revision, mention_version, mention_generation, mentions_scanned_at)
+ SELECT id, $1, rev::uuid, $4, $5::bigint, now() FROM unnest($2::int[], $3::text[]) AS x(id, rev)
+ ON CONFLICT (page_id) DO UPDATE SET mention_revision = EXCLUDED.mention_revision, mention_version = EXCLUDED.mention_version,
+ mention_generation = EXCLUDED.mention_generation, mentions_scanned_at = EXCLUDED.mentions_scanned_at`,
+ [sourceId, fresh.map(p => p.id), fresh.map(p => p.revision), MENTION_EXTRACTOR_VERSION, generations.get(sourceId) ?? '0']);
+ return { fresh: fresh.length, created, removed: drop.length };
+ });
+ if (!outcome) { result.skipped += pages.length; return; }
+ result.pages += outcome.fresh;
+ result.skipped += pages.length - outcome.fresh;
+ result.created += outcome.created;
+ result.removed += outcome.removed;
+ }
+}
+
+/**
+ * Run the mention pass for one source or every source. Never throws for a
+ * pack, alias or entry-table failure: it writes nothing and returns
+ * `state: 'failed'` with the error (recorded on the status rows).
+ */
+export async function runMentionPass(engine: BrainEngine, opts: MentionPassOpts = {}): Promise<MentionPassResult> {
+ const result: MentionPassResult = { pages: 0, created: 0, removed: 0, skipped: 0, aliasPages: 0, remaining: 0, state: 'complete' };
+ const deadline = opts.deadline ?? Infinity;
+ const passStart = new Date().toISOString();
+ const policy = await readMentionPolicy(engine);
+ const sources = await sourcesInScope(engine, opts.sourceId);
+ const managed = await managedPersistenceEnabled(engine).catch(() => false);
+ if (!policy.enabled) {
+ const status = new Map((await engine.executeRaw<{ source_id: string; state: string }>(
+ 'SELECT source_id, state FROM mention_index_status WHERE source_id = ANY($1::text[])', [sources])).map(r => [r.source_id, r.state]));
+ for (const sourceId of sources) {
+ if (status.get(sourceId) === 'disabled') continue;
+ result.removed += await disableSource(engine, managed, sourceId);
+ }
+ result.state = 'disabled';
+ return result;
+ }
+ const allowCrossSource = await isCrossSourceLinksEnabled(engine);
+ const types = new Map<string, string[]>();
+ let gazetteer: Gazetteer;
+ try {
+ for (const sourceId of sources) types.set(sourceId, linkableTypesFor(await loadSourcePack(engine, sourceId, { strict: true }), policy));
+ gazetteer = await buildGazetteer(engine, { policy, strict: true });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ for (const sourceId of sources) await writeStatus(engine, sourceId, { state: 'failed', error: message });
+ return { ...result, state: 'failed', error: message, remaining: await countMentionDuePages(engine, opts.sourceId) };
+ }
+ const allSources = allowCrossSource ? (await sourcesInScope(engine)) : [];
+ const fingerprints = new Map<string, string>(sources.map(s => [s, policyFingerprint(types.get(s)!, allowCrossSource, policy)]));
+ const stored = new Map((await engine.executeRaw<{ source_id: string; policy_fingerprint: string | null }>(
+ 'SELECT source_id, policy_fingerprint FROM mention_index_status WHERE source_id = ANY($1::text[])', [sources]))
+ .map(r => [r.source_id, r.policy_fingerprint]));
+ for (const sourceId of sources) {
+ if (stored.get(sourceId) === fingerprints.get(sourceId)) continue;
+ await engine.transaction(async tx => {
+ await tx.executeRaw('UPDATE page_mention_state SET mention_revision = NULL, alias_revision = NULL WHERE source_id = $1', [sourceId]);
+ await writeStatus(tx, sourceId, { state: 'pending', bumpGeneration: true, fingerprint: fingerprints.get(sourceId)! });
+ });
+ }
+ for (const sourceId of sources) {
+ if (Date.now() > deadline) break;
+ result.aliasPages += await refreshAliases(engine, managed, sourceId, types.get(sourceId)!, deadline);
+ }
+ // Aliases may have changed: the gazetteer the reconcile uses is built after the refresh.
+ if (result.aliasPages > 0) {
+ try { gazetteer = await buildGazetteer(engine, { policy, strict: true }); }
+ catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ for (const sourceId of sources) await writeStatus(engine, sourceId, { state: 'failed', error: message });
+ return { ...result, state: 'failed', error: message, remaining: await countMentionDuePages(engine, opts.sourceId) };
+ }
+ }
+ for (const sourceId of sources) {
+ await saveEntries(engine, sourceId, gazetteer, allowCrossSource ? allSources : [sourceId], allowCrossSource);
+ }
+ for (const sourceId of sources) {
+ await reconcileSource(engine, sourceId, gazetteer, allowCrossSource ? allSources : [sourceId], allowCrossSource, opts, deadline, result);
+ const pending = await countMentionDuePages(engine, sourceId);
+ result.remaining += pending;
+ await writeStatus(engine, sourceId, { state: pending > 0 ? 'pending' : 'complete', pending, error: null, lastPassAt: passStart });
+ }
+ result.state = result.remaining > 0 ? 'pending' : 'complete';
+ return result;
+}
+
+/** The gazetteer's entries targeting one page, with their origins (for explain). */
+export function entriesFor(gazetteer: Gazetteer, sourceId: string, slug: string): GazetteerEntry[] {
+ return [...gazetteer.values()].flat().filter(e => e.source_id === sourceId && e.slug === slug);
+}
+
+/** Normalized token key of a name, as the scanner compares it. */
+export function nameKey(name: string): string {
+ return tokenizeTitle(name).join(' ');
+}
diff --git a/src/core/mentions/policy.ts b/src/core/mentions/policy.ts
new file mode 100644
index 0000000000..28934ef28d
--- /dev/null
+++ b/src/core/mentions/policy.ts
@@ -0,0 +1,120 @@
+/**
+ * Mention-linking policy: which page types are linkable entities, which names
+ * are ignored, and whether the mention pass runs at all.
+ *
+ * Linkable types per source are the union of the four always-linkable types
+ * (person, company, organization, entity), every type the source's schema pack
+ * marks `primitive: entity`, and those types' declared type aliases (`product`
+ * excluded: a product page is not a name agents brief on), adjusted by
+ * `mentions.entity_types` (`+type` or `type` adds, `-type` removes; the four
+ * always-linkable types cannot be removed). The gazetteer, the entity card's
+ * entity preference and the mention pass's alias refresh all read this one
+ * resolver. Type lists reach SQL bound as `text[]`, never interpolated.
+ *
+ * Off switches: `auto_link=false` (global) or `mentions.auto_link=false`.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
+
+export const ALWAYS_LINKABLE_TYPES = ['person', 'company', 'organization', 'entity'] as const;
+const EXCLUDED_LINKABLE_ALIASES: ReadonlySet<string> = new Set(['product']);
+
+export interface PackTypes {
+ page_types: ReadonlyArray<{ name: string; primitive?: string; aliases?: ReadonlyArray<string> }>;
+}
+
+export interface MentionPolicy {
+ enabled: boolean;
+ /** The key that turned the pass off, when it is off. */
+ disabledBy: 'auto_link' | 'mentions.auto_link' | null;
+ typeAdds: string[];
+ typeRemoves: string[];
+ /** Names never linked (`mentions.ignore`), matched case-insensitively. */
+ ignore: string[];
+}
+
+const FALSE_VALUES = new Set(['false', '0', 'no', 'off']);
+
+function isOff(value: string | null): boolean {
+ return value != null && FALSE_VALUES.has(value.trim().toLowerCase());
+}
+
+/** A JSON array or a comma/newline-separated list of strings. */
+export function parseNameList(value: unknown): string[] {
+ if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string').map(v => v.trim()).filter(Boolean);
+ if (typeof value !== 'string' || !value.trim()) return [];
+ const text = value.trim();
+ if (text.startsWith('[')) {
+ try { return parseNameList(JSON.parse(text)); } catch { /* fall through to the plain list */ }
+ }
+ return text.split(/[,\n]/).map(v => v.trim()).filter(Boolean);
+}
+
+export async function readMentionPolicy(engine: Pick<BrainEngine, 'getConfig'>): Promise<MentionPolicy> {
+ const [global, own, types, ignore] = await Promise.all([
+ engine.getConfig('auto_link'), engine.getConfig('mentions.auto_link'),
+ engine.getConfig('mentions.entity_types'), engine.getConfig('mentions.ignore'),
+ ]);
+ const typeAdds: string[] = [];
+ const typeRemoves: string[] = [];
+ for (const entry of parseNameList(types)) {
+ if (entry.startsWith('-')) typeRemoves.push(entry.slice(1).trim());
+ else typeAdds.push(entry.replace(/^\+/, '').trim());
+ }
+ const disabledBy = isOff(global) ? 'auto_link' : isOff(own) ? 'mentions.auto_link' : null;
+ return { enabled: disabledBy === null, disabledBy, typeAdds: typeAdds.filter(Boolean), typeRemoves: typeRemoves.filter(Boolean), ignore: parseNameList(ignore) };
+}
+
+/** Linkable entity types for one pack (null = no pack resolved), sorted. */
+export function linkableTypesFor(pack: PackTypes | null, policy: Pick<MentionPolicy, 'typeAdds' | 'typeRemoves'>): string[] {
+ const types = new Set<string>(ALWAYS_LINKABLE_TYPES);
+ for (const pt of pack?.page_types ?? []) {
+ if (pt.primitive !== 'entity') continue;
+ types.add(pt.name);
+ for (const alias of pt.aliases ?? []) if (!EXCLUDED_LINKABLE_ALIASES.has(alias)) types.add(alias);
+ }
+ for (const t of policy.typeAdds) types.add(t);
+ for (const t of policy.typeRemoves) if (!(ALWAYS_LINKABLE_TYPES as readonly string[]).includes(t)) types.delete(t);
+ return [...types].sort();
+}
+
+/** Stored type → the pack's canonical type (type aliases mapped); untyped pages group as `untyped`. */
+export function canonicalTypeOf(stored: string | null | undefined, pack: PackTypes | null): string {
+ if (!stored) return 'untyped';
+ for (const pt of pack?.page_types ?? []) if (pt.name === stored) return stored;
+ for (const pt of pack?.page_types ?? []) if (pt.aliases?.includes(stored)) return pt.name;
+ return stored;
+}
+
+/** `[stored, canonical]` pairs for every alias the pack declares, for SQL grouping (bound as two text[]). */
+export function typeAliasPairs(pack: PackTypes | null): { stored: string[]; canonical: string[] } {
+ const stored: string[] = [];
+ const canonical: string[] = [];
+ const declared = new Set((pack?.page_types ?? []).map(pt => pt.name));
+ for (const pt of pack?.page_types ?? []) {
+ for (const alias of pt.aliases ?? []) {
+ if (declared.has(alias) || stored.includes(alias)) continue;
+ stored.push(alias);
+ canonical.push(pt.name);
+ }
+ }
+ return { stored, canonical };
+}
+
+/** The active pack for a source; null when none resolves. `strict` rethrows a resolution failure instead. */
+export async function loadSourcePack(engine: Pick<BrainEngine, 'getConfig'>, sourceId: string, opts: { strict?: boolean } = {}): Promise<PackTypes | null> {
+ try {
+ return (await loadActivePackForEngine(engine, { remote: false, sourceId })).manifest;
+ } catch (error) {
+ if (opts.strict) throw error;
+ return null;
+ }
+}
+
+export async function loadLinkableTypes(engine: Pick<BrainEngine, 'getConfig'>, sourceId: string,
+ opts: { strict?: boolean; policy?: MentionPolicy } = {}): Promise<{ types: string[]; pack: PackTypes | null }> {
+ const policy = opts.policy ?? await readMentionPolicy(engine);
+ const pack = await loadSourcePack(engine, sourceId, opts);
+ return { types: linkableTypesFor(pack, policy), pack };
+}
diff --git a/src/core/mentions/referrers.ts b/src/core/mentions/referrers.ts
new file mode 100644
index 0000000000..f9791eb6e4
--- /dev/null
+++ b/src/core/mentions/referrers.ts
@@ -0,0 +1,224 @@
+/**
+ * Pages that link to an entity, one row per referring page: the entity card's
+ * `referenced_by` groups and `get_backlinks {group: "page"}` both read this
+ * one helper, so a card group and its continuation agree on membership,
+ * order, privacy and identity union.
+ *
+ * - Every link source counts (mentions included), unlike `backlink_count`.
+ * - Rows are ordered by `(date DESC, source_id, slug)` where date is
+ * `COALESCE(effective_date, updated_at)`; paging is a keyset cursor.
+ * - Grouping is by the referring page's pack-canonical type (stored type
+ * mapped through the pack's type aliases; untyped pages are `untyped`).
+ * A `type` filter accepts a canonical type or a stored type.
+ * - Untrusted callers never see a private or derived-private referrer, nor a
+ * link whose origin page is private, in rows or counts.
+ * - With `entity_identity.union` on, links to the page's identity co-members
+ * count as links to the page.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { privateLinkOriginFilterFragment, privatePagesFilterFragment, privatePagesFilterFragmentFast } from '../search/private-visibility.ts';
+import { isIdentityUnionEnabled, listEntityIdentities } from '../entity-identity.ts';
+import { stripTakesFence } from '../takes-fence.ts';
+import { stripFactsFence } from '../facts-fence.ts';
+import { redactFindings } from '../secret-scan.ts';
+import { typeAliasPairs, type PackTypes } from './policy.ts';
+
+export const PREVIEW_CHARS = 160;
+export const GROUP_ROW_CAP = 10;
+export const CARD_ROW_CAP = 50;
+export const PAGE_DEFAULT_LIMIT = 50;
+export const PAGE_MAX_LIMIT = 500;
+
+export interface ReferenceRow {
+ slug: string;
+ source_id: string;
+ title: string;
+ type: string | null;
+ canonical_type: string;
+ date: string | null;
+ /** `effective_date` provenance (event_date, date, published, filename, fallback) or `updated_at`. */
+ date_source: string;
+ /** First 160 characters of body text, private fences stripped and secrets redacted. Not evidence: fetch the page. */
+ preview: string;
+}
+
+export interface ReferrerScope {
+ /** The entity page. */
+ slug: string;
+ sourceId: string;
+ /** Sources a referring page may live in (the caller's read scope). */
+ referrerSources: string[];
+ excludePrivate: boolean;
+ pack: PackTypes | null;
+ /** Visibility kept in previews (world only for untrusted callers). */
+ keepVisibility: ('private' | 'world')[];
+}
+
+interface RawRow { id: number; slug: string; source_id: string; type: string | null; canonical_type: string;
+ d: string | null; gtotal?: number }
+
+/** The entity page plus, under `entity_identity.union`, its identity co-members. */
+async function targetPages(engine: BrainEngine, scope: ReferrerScope): Promise<{ sources: string[]; slugs: string[] }> {
+ const targets = [{ slug: scope.slug, source_id: scope.sourceId }];
+ if (await isIdentityUnionEnabled(engine)) {
+ try {
+ const members = await listEntityIdentities(engine, { slug: scope.slug, slugSourceId: scope.sourceId, sourceId: scope.sourceId,
+ allowedSources: scope.referrerSources, excludePrivate: scope.excludePrivate });
+ for (const m of members) if (!targets.some(t => t.slug === m.slug && t.source_id === m.source_id)) targets.push({ slug: m.slug, source_id: m.source_id });
+ } catch { /* the union never breaks the base read */ }
+ }
+ return { sources: targets.map(t => t.source_id), slugs: targets.map(t => t.slug) };
+}
+
+/**
+ * The shared CTE `typed`: one row per referring page with its canonical type
+ * and date. Params $1..$5 are fixed (target sources, target slugs, referrer
+ * sources, stored type aliases, their canonical types; all bound as text[]).
+ * The target's own privacy is checked once in `tgt`, and the referring page
+ * ids are collected once in `refs`, so a hub with thousands of inbound links
+ * costs one hashed membership test per candidate page.
+ */
+function referrersCte(scope: ReferrerScope): string {
+ const targetPriv = scope.excludePrivate ? ` AND ${privatePagesFilterFragment('t')}` : '';
+ const linkPriv = scope.excludePrivate ? ` AND ${privateLinkOriginFilterFragment('l')}` : '';
+ const pagePriv = scope.excludePrivate ? ` AND ${privatePagesFilterFragmentFast('f')}` : '';
+ return `WITH tgt AS MATERIALIZED (
+ SELECT t.id FROM pages t JOIN unnest($1::text[], $2::text[]) AS k(s, g) ON t.source_id = k.s AND t.slug = k.g
+ WHERE t.deleted_at IS NULL${targetPriv}
+ ),
+ refs AS MATERIALIZED (
+ SELECT DISTINCT l.from_page_id AS id FROM links l WHERE l.to_page_id IN (SELECT id FROM tgt)${linkPriv}
+ ),
+ typed AS MATERIALIZED (
+ SELECT f.id, f.slug, f.source_id, f.type,
+ COALESCE(f.effective_date, f.updated_at) AS d,
+ COALESCE(($5::text[])[array_position($4::text[], f.type)], NULLIF(f.type, ''), 'untyped') AS canonical_type
+ FROM pages f
+ WHERE f.id IN (SELECT id FROM refs)
+ AND f.deleted_at IS NULL AND f.source_id = ANY($3::text[])
+ AND f.id NOT IN (SELECT id FROM tgt)${pagePriv}
+ )`;
+}
+
+/** A timestamp as UTC ISO text with microseconds (a cursor compares at full precision). */
+const dateText = (column: string) => `to_char(${column} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+
+function preview(body: string | null, keep: ('private' | 'world')[]): string {
+ if (!body) return '';
+ const clean = redactFindings(stripFactsFence(stripTakesFence(body), { keepVisibility: keep }), { highEntropy: true }).text
+ .replace(/^---[\s\S]*?---\s*/, '')
+ .replace(/^\s*#\s[^\n]*\n?/, '');
+ const text = clean.replace(/\s+/g, ' ').trim();
+ return text.length > PREVIEW_CHARS ? text.slice(0, PREVIEW_CHARS) : text;
+}
+
+async function hydrate(engine: BrainEngine, rows: RawRow[], keep: ('private' | 'world')[]): Promise<ReferenceRow[]> {
+ if (!rows.length) return [];
+ const pages = new Map((await engine.executeRaw<{ id: number; title: string | null; body: string | null; date_source: string }>(
+ `SELECT id, title, left(compiled_truth, 4000) AS body,
+ CASE WHEN effective_date IS NULL THEN 'updated_at' ELSE COALESCE(effective_date_source, 'effective_date') END AS date_source
+ FROM pages WHERE id = ANY($1::int[])`, [rows.map(r => r.id)])).map(r => [Number(r.id), r]));
+ return rows.map(r => {
+ const page = pages.get(Number(r.id));
+ return {
+ slug: r.slug, source_id: r.source_id, title: page?.title ?? r.slug, type: r.type || null, canonical_type: r.canonical_type,
+ date: r.d, date_source: page?.date_source ?? 'updated_at', preview: preview(page?.body ?? null, keep),
+ };
+ });
+}
+
+export function encodeCursor(row: Pick<ReferenceRow, 'date' | 'source_id' | 'slug'>): string {
+ return Buffer.from(JSON.stringify([row.date, row.source_id, row.slug])).toString('base64url');
+}
+
+export function decodeCursor(cursor: string): [string | null, string, string] | null {
+ try {
+ const v = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
+ if (Array.isArray(v) && v.length === 3 && (v[0] === null || typeof v[0] === 'string') && typeof v[1] === 'string' && typeof v[2] === 'string') {
+ return v as [string | null, string, string];
+ }
+ } catch { /* invalid */ }
+ return null;
+}
+
+/** Canonical and stored types observed among the entity's referrers (for the unknown-type error). */
+export async function referrerTypes(engine: BrainEngine, scope: ReferrerScope): Promise<string[]> {
+ const t = await targetPages(engine, scope);
+ const pairs = typeAliasPairs(scope.pack);
+ const rows = await engine.executeRaw<{ canonical_type: string; type: string | null }>(
+ `${referrersCte(scope)} SELECT DISTINCT canonical_type, type FROM typed`,
+ [t.sources, t.slugs, scope.referrerSources, pairs.stored, pairs.canonical]);
+ return [...new Set(rows.flatMap(r => [r.canonical_type, ...(r.type ? [r.type] : [])]))].sort();
+}
+
+/** One page of referring pages (newest first), optionally of one type. */
+export async function readReferrerPage(engine: BrainEngine, scope: ReferrerScope,
+ opts: { type?: string; limit: number; cursor?: [string | null, string, string] | null }): Promise<{ rows: ReferenceRow[]; total: number; truncated: boolean; cursor: string | null }> {
+ const t = await targetPages(engine, scope);
+ const pairs = typeAliasPairs(scope.pack);
+ const params: unknown[] = [t.sources, t.slugs, scope.referrerSources, pairs.stored, pairs.canonical, opts.type ?? null];
+ const typeFilter = `($6::text IS NULL OR canonical_type = $6 OR type = $6)`;
+ const [count] = await engine.executeRaw<{ n: number }>(`${referrersCte(scope)} SELECT count(*)::int AS n FROM typed WHERE ${typeFilter}`, params);
+ let after = '';
+ if (opts.cursor) {
+ params.push(opts.cursor[0], opts.cursor[1], opts.cursor[2]);
+ after = ` AND ((d IS NOT DISTINCT FROM $7::timestamptz AND (source_id, slug) > ($8::text, $9::text))
+ OR ($7::timestamptz IS NOT NULL AND (d < $7::timestamptz OR d IS NULL)))`;
+ }
+ params.push(opts.limit + 1);
+ const raw = await engine.executeRaw<RawRow>(
+ `${referrersCte(scope)}
+ SELECT id, slug, source_id, type, canonical_type, ${dateText('d')} AS d FROM typed
+ WHERE ${typeFilter}${after}
+ ORDER BY d DESC NULLS LAST, source_id, slug LIMIT $${params.length}`, params);
+ const truncated = raw.length > opts.limit;
+ const rows = await hydrate(engine, raw.slice(0, opts.limit), scope.keepVisibility);
+ return { rows, total: Number(count?.n ?? 0), truncated, cursor: truncated ? encodeCursor(rows[rows.length - 1]!) : null };
+}
+
+export interface ReferenceGroup {
+ canonical_type: string;
+ total: number;
+ rows: ReferenceRow[];
+}
+
+/**
+ * The card's groups: every canonical type with its total, newest rows first,
+ * at most GROUP_ROW_CAP per group and CARD_ROW_CAP across the card (spread so
+ * every group shows rows before any group shows more). Groups are ordered by
+ * their newest row.
+ */
+export async function readReferrerGroups(engine: BrainEngine, scope: ReferrerScope): Promise<{ total: number; groups: ReferenceGroup[] }> {
+ const t = await targetPages(engine, scope);
+ const pairs = typeAliasPairs(scope.pack);
+ // Per-type totals by hash aggregate, then a bounded top-N per type (no full sort of the referrers).
+ const raw = await engine.executeRaw<RawRow>(
+ `${referrersCte(scope)},
+ counts AS (SELECT canonical_type, count(*)::int AS n FROM typed GROUP BY canonical_type)
+ SELECT x.id, x.slug, x.source_id, x.type, c.canonical_type, ${dateText('x.d')} AS d, c.n AS gtotal
+ FROM counts c CROSS JOIN LATERAL (
+ SELECT * FROM typed t WHERE t.canonical_type = c.canonical_type ORDER BY t.d DESC NULLS LAST, t.source_id, t.slug LIMIT $6
+ ) x
+ ORDER BY c.canonical_type, x.d DESC NULLS LAST, x.source_id, x.slug`,
+ [t.sources, t.slugs, scope.referrerSources, pairs.stored, pairs.canonical, GROUP_ROW_CAP]);
+ const byType = new Map<string, RawRow[]>();
+ for (const r of raw) byType.set(r.canonical_type, [...(byType.get(r.canonical_type) ?? []), r]);
+ const order = [...byType.entries()].sort(([a, x], [b, y]) => (y[0]!.d ?? '').localeCompare(x[0]!.d ?? '') || a.localeCompare(b));
+ // Water-fill: raise a per-group quota until the card cap is reached.
+ const quota = new Map(order.map(([type]) => [type, 0]));
+ let used = 0;
+ for (let level = 1; level <= GROUP_ROW_CAP && used < CARD_ROW_CAP; level++) {
+ for (const [type, rows] of order) {
+ if (used >= CARD_ROW_CAP) break;
+ if (rows.length >= level) { quota.set(type, level); used++; }
+ }
+ }
+ const kept = order.flatMap(([type, rows]) => rows.slice(0, quota.get(type)));
+ const hydrated = await hydrate(engine, kept, scope.keepVisibility);
+ const groups: ReferenceGroup[] = order.map(([type, rows]) => ({
+ canonical_type: type, total: Number(rows[0]!.gtotal ?? rows.length), rows: hydrated.filter(r => r.canonical_type === type),
+ }));
+ return { total: groups.reduce((n, g) => n + g.total, 0), groups };
+}
+
diff --git a/src/core/mentions/stale.ts b/src/core/mentions/stale.ts
new file mode 100644
index 0000000000..268c1704f5
--- /dev/null
+++ b/src/core/mentions/stale.ts
@@ -0,0 +1,58 @@
+/**
+ * The mention pass as a phase of `gbrain extract --stale` and the managed
+ * stale path: preview counts for `--dry-run`, the cycle's budget split, and
+ * the report lines. The pass itself is `pass.ts`.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { countMentionDuePages, type MentionPassResult } from './pass.ts';
+import { readMentionPolicy } from './policy.ts';
+
+export interface MentionPreview {
+ due: number;
+ last_pass_at: string | null;
+ enabled: boolean;
+}
+
+/** Mention-due pages and the newest pass time, for `extract --stale --dry-run` and post-upgrade. */
+export async function previewMentionPass(engine: BrainEngine, sourceId?: string): Promise<MentionPreview> {
+ const policy = await readMentionPolicy(engine);
+ const [row] = await engine.executeRaw<{ last: string | null }>(
+ `SELECT to_char(max(last_pass_at) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS last FROM mention_index_status
+ WHERE ($1::text IS NULL OR source_id = $1)`, [sourceId ?? null]);
+ return { due: policy.enabled ? await countMentionDuePages(engine, sourceId) : 0, last_pass_at: row?.last ?? null, enabled: policy.enabled };
+}
+
+/**
+ * Deadline for the link phase of a budgeted sweep: half the budget while
+ * mention-due pages exist, so a link backlog cannot starve the mention pass
+ * across cycles. Unbudgeted (catch-up) sweeps get no deadline.
+ */
+export async function linkPhaseDeadline(engine: BrainEngine, sourceId: string | undefined, startMs: number, budgetMs: number | undefined): Promise<number> {
+ if (budgetMs === undefined) return Infinity;
+ const policy = await readMentionPolicy(engine);
+ const due = policy.enabled ? await countMentionDuePages(engine, sourceId) : 0;
+ return startMs + (due > 0 ? budgetMs / 2 : budgetMs);
+}
+
+/** One report line, or null when the pass did nothing worth reporting. */
+export function formatMentionSummary(r: MentionPassResult): string | null {
+ if (r.state === 'failed') {
+ return `Mentions: not indexed (${r.error ?? 'unknown error'}); nothing was changed. Fix the cause, then re-run 'gbrain extract --stale'.`;
+ }
+ if (r.state === 'disabled') {
+ return r.removed ? `Mentions: linking is off (auto_link or mentions.auto_link); removed ${r.removed} mention link(s).` : null;
+ }
+ if (!r.pages && !r.removed && !r.remaining && !r.aliasPages) return null;
+ return `Mentions: ${r.created} link(s) added, ${r.removed} removed from ${r.pages} page(s)` +
+ (r.aliasPages ? `; derived names refreshed on ${r.aliasPages} entity page(s)` : '') +
+ (r.remaining ? `; ${r.remaining} page(s) still due — re-run 'gbrain extract --stale' (or pass --catch-up) to continue.` : '.');
+}
+
+export function mentionJsonFields(r: MentionPassResult): Record<string, unknown> {
+ return {
+ mention_pages: r.pages, mention_links_created: r.created, mention_links_removed: r.removed,
+ mention_alias_pages: r.aliasPages, mention_due_remaining: r.remaining, mention_state: r.state,
+ ...(r.error ? { mention_error: r.error } : {}),
+ };
+}
diff --git a/src/core/mentions/upgrade-notice.ts b/src/core/mentions/upgrade-notice.ts
new file mode 100644
index 0000000000..7f81874242
--- /dev/null
+++ b/src/core/mentions/upgrade-notice.ts
@@ -0,0 +1,49 @@
+/**
+ * `gbrain post-upgrade`: while mention-due pages exist, an `[AGENT]` block
+ * names the catch-up sweep and how long it takes, so an upgraded brain gets
+ * its entity mention index without waiting for autopilot cycles.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { agentBlock } from '../agent-markers.ts';
+import { previewMentionPass } from './stale.ts';
+
+/**
+ * Planning rate for the catch-up estimate. The 52k-document world ran its
+ * full pass at 3,300-7,800 pages/s on PGLite with no embeddings; real pages
+ * are longer, so the estimate assumes 1,000 and rounds up to whole minutes.
+ */
+export const MENTION_PASS_PAGES_PER_SECOND = 1000;
+
+export const MENTION_CATCH_UP_ARGV = ['gbrain', 'extract', '--stale', '--catch-up'] as const;
+
+/** The notice lines, or null when nothing is due (or linking is off). */
+export async function mentionIndexUpgradeNotice(engine: BrainEngine): Promise<string[] | null> {
+ const preview = await previewMentionPass(engine);
+ if (!preview.enabled || preview.due === 0) return null;
+ const minutes = Math.max(1, Math.ceil(preview.due / MENTION_PASS_PAGES_PER_SECOND / 60));
+ return [
+ '',
+ agentBlock({
+ why: `${preview.due} page(s) have not been scanned for entity names. Until they are, entity cards list only explicit links ` +
+ '(coverage: pending) and documents that name an account, person or company by name or code are not linked to it.',
+ consent: 'none (free: no model calls, no egress)',
+ actor: 'agent',
+ next: `run: ${MENTION_CATCH_UP_ARGV.join(' ')} (about ${minutes} minute(s) for ${preview.due} page(s); resumable, and autopilot cycles continue it otherwise)`,
+ verify: 'gbrain extract --stale --dry-run --json (mention_due_pages: 0)',
+ }).trimEnd(),
+ '',
+ ];
+}
+
+/** Prints the notice when pages are due. Best-effort: never blocks the upgrade. */
+export async function printMentionIndexUpgradeNotice(engine: BrainEngine, log: (line: string) => void = console.log): Promise<boolean> {
+ try {
+ const lines = await mentionIndexUpgradeNotice(engine);
+ if (!lines) return false;
+ for (const line of lines) log(line);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/src/core/minions/handlers/extract.ts b/src/core/minions/handlers/extract.ts
index 310a0b4111..443c1830cf 100644
--- a/src/core/minions/handlers/extract.ts
+++ b/src/core/minions/handlers/extract.ts
@@ -27,7 +27,7 @@ export function makeExtractHandler(engine: BrainEngine): MinionHandler {
// continuation job so a very large deferred backlog converges without
// waiting for the next sync. Forward-progress guard (pagesProcessed >
// 0) prevents an infinite chain if the sweep can't advance.
- if (!job.data.dryRun && r.staleRemaining > 0 && r.pagesProcessed > 0) {
+ if (!job.data.dryRun && r.staleRemaining > 0 && (r.pagesProcessed > 0 || (r.mentions?.pages ?? 0) > 0)) {
try {
const queue = new MinionQueue(engine);
// NO maxWaiting: with an unscoped (NULL-sourceId) payload the
diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.ts
index 7bf7c5aacb..3e91c9ff43 100644
--- a/src/core/notice-ledger.ts
+++ b/src/core/notice-ledger.ts
@@ -21,7 +21,7 @@ const MAX_KEYS = 10_000;
const TTL_MS = 24 * 60 * 60 * 1000;
export const COACHING_BUDGET_PER_SESSION = 2;
/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */
-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed', 'local_transcripts', 'held_files']);
+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'mention_index']);
export interface NoticeAudience {
transport: Transport;
diff --git a/src/core/operations-descriptions.ts b/src/core/operations-descriptions.ts
index c40b16d668..5f246d9356 100644
--- a/src/core/operations-descriptions.ts
+++ b/src/core/operations-descriptions.ts
@@ -49,10 +49,10 @@ export const LIST_PAGES_DESCRIPTION =
"List pages with filters. For 'what's recent / what did I touch this week' use sort=updated_desc. Default 50 rows (remote max 100); a full page may be truncated: continue with updated_after + updated_after_slug from the last row.";
export const QUERY_DESCRIPTION =
- "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies; raw transcripts: `gbrain transcripts recent` on the brain host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key, else keyword-only; expansion needs a chat-model key. fields: \"full\" adds diagnostics.";
+ "Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.";
export const SEARCH_DESCRIPTION =
- "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal questions: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.";
+ "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.";
// ──────────────────────────────────────────────────────────────────────────────
// v0.32.6 — contradiction probe MCP surface (M3)
diff --git a/src/core/ops/backlinks-paged.ts b/src/core/ops/backlinks-paged.ts
new file mode 100644
index 0000000000..94b7b436fa
--- /dev/null
+++ b/src/core/ops/backlinks-paged.ts
@@ -0,0 +1,143 @@
+/**
+ * get_backlinks' entity-recall parameters (`type`, `group`, `limit`,
+ * `cursor`). With none of them the op is today's bare `Link[]` read
+ * (ops/links.ts readLinkEdges). `type` filters by the referring page's type
+ * in both modes (a pack-canonical type, or any stored type observed on a
+ * referrer; `untyped` for untyped pages). `group: "page"` returns
+ * `{rows, total, truncated, cursor, coverage}`: one row per referring page,
+ * newest first by `(date DESC, source_id, slug)`, read through the same
+ * helper as the entity card's `referenced_by`, so a card group's `next` call
+ * continues it exactly.
+ */
+
+import { opError, type OperationContext } from './contract.ts';
+import type { Link, PageReadPolicy } from '../types.ts';
+import type { Notice } from '../agent-output.ts';
+import { canonicalTypeOf, loadSourcePack } from '../mentions/policy.ts';
+import {
+ decodeCursor, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,
+} from '../mentions/referrers.ts';
+import { mentionCoverageNotice, readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';
+
+export interface BacklinkPage {
+ rows: ReferenceRow[];
+ total: number;
+ truncated: boolean;
+ cursor: string | null;
+ coverage: MentionCoverage;
+}
+
+/** True when the call uses any entity-recall parameter. */
+export function wantsPagedBacklinks(p: Record<string, unknown>): boolean {
+ return p.type !== undefined || p.group !== undefined || p.limit !== undefined || p.cursor !== undefined;
+}
+
+function parseLimit(p: Record<string, unknown>, fallback: number | undefined): number | undefined {
+ if (p.limit === undefined) return fallback;
+ const n = typeof p.limit === 'string' ? Number(p.limit) : p.limit;
+ if (typeof n !== 'number' || !Number.isInteger(n) || n < 1 || n > PAGE_MAX_LIMIT) {
+ throw opError('invalid_params', `get_backlinks: limit must be an integer from 1 to ${PAGE_MAX_LIMIT}.`,
+ `Pass limit between 1 and ${PAGE_MAX_LIMIT}; page through the rest with group: "page" and the returned cursor.`);
+ }
+ return n;
+}
+
+async function scopeSources(ctx: OperationContext, policy: PageReadPolicy): Promise<string[]> {
+ if (policy.sourceIds?.length) return policy.sourceIds;
+ if (policy.sourceId) return [policy.sourceId];
+ return (await ctx.engine.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(r => r.id);
+}
+
+/** The entity page's source: the first source in scope holding a live page with this slug. */
+async function targetSource(ctx: OperationContext, slug: string, sources: string[]): Promise<string | null> {
+ const rows = await ctx.engine.executeRaw<{ source_id: string }>(
+ 'SELECT source_id FROM pages WHERE slug = $1 AND source_id = ANY($2::text[]) AND deleted_at IS NULL', [slug, sources]);
+ const found = new Set(rows.map(r => r.source_id));
+ return sources.find(s => found.has(s)) ?? null;
+}
+
+async function referrerScope(ctx: OperationContext, slug: string, policy: PageReadPolicy): Promise<{ scope: ReferrerScope; sources: string[] } | null> {
+ const sources = await scopeSources(ctx, policy);
+ const sourceId = await targetSource(ctx, slug, sources);
+ if (!sourceId) return null;
+ const pack = await loadSourcePack(ctx.engine, sourceId);
+ const excludePrivate = policy.excludePrivate === true;
+ return { sources, scope: { slug, sourceId, referrerSources: sources, excludePrivate, pack, keepVisibility: excludePrivate ? ['world'] : ['private', 'world'] } };
+}
+
+async function assertKnownType(ctx: OperationContext, scope: ReferrerScope, type: string): Promise<void> {
+ const declared = (scope.pack?.page_types ?? []).flatMap(pt => [pt.name, ...(pt.aliases ?? [])]);
+ if (declared.includes(type) || type === 'untyped') return;
+ const observed = await referrerTypes(ctx.engine, scope);
+ if (observed.includes(type)) return;
+ const canonical = (scope.pack?.page_types ?? []).map(pt => pt.name);
+ const valid = [...new Set([...observed, ...canonical, 'untyped'])].sort();
+ throw opError('invalid_params', `get_backlinks: unknown type "${type}".`,
+ `Use a type this page's referrers have (${observed.join(', ') || 'none yet'}), a schema-pack type or untyped; valid values: ${valid.join(', ')}.`,
+ { detail: JSON.stringify({ valid_types: valid, referrer_types: observed }) });
+}
+
+/**
+ * `group: "page"`: one page of referring pages. A slug with no live page in
+ * scope answers like an empty read (no rows, total 0).
+ */
+export async function readBacklinkPage(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<BacklinkPage> {
+ if (p.group !== 'page') {
+ throw opError('invalid_params', `get_backlinks: group must be "page".`, 'Pass group: "page" for one row per referring page, or omit group for link rows.');
+ }
+ const limit = parseLimit(p, PAGE_DEFAULT_LIMIT)!;
+ const cursor = p.cursor === undefined ? null : decodeCursor(String(p.cursor));
+ if (p.cursor !== undefined && !cursor) {
+ throw opError('invalid_params', 'get_backlinks: cursor is not one this tool returned.', 'Pass the cursor from the previous get_backlinks response unchanged, or omit it to start from the newest page.');
+ }
+ const resolved = await referrerScope(ctx, String(p.slug), policy);
+ const coverage = await readMentionCoverage(ctx.engine, resolved?.sources ?? await scopeSources(ctx, policy));
+ const notice = mentionCoverageNotice(coverage);
+ if (notice) ctx.emitNotice?.(notice);
+ if (!resolved) return { rows: [], total: 0, truncated: false, cursor: null, coverage };
+ const type = typeof p.type === 'string' && p.type ? p.type : undefined;
+ if (type) await assertKnownType(ctx, resolved.scope, type);
+ return { ...await readReferrerPage(ctx.engine, resolved.scope, { type, limit, cursor }), coverage };
+}
+
+/**
+ * Array mode with `type` and/or `limit`: today's link rows, filtered by the
+ * referring page's type and cut at `limit` (a cut is reported with a
+ * `listing_truncated` notice naming the paged call).
+ */
+export async function filterBacklinkRows(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy, links: Link[]): Promise<Link[]> {
+ if (p.cursor !== undefined) {
+ throw opError('invalid_params', 'get_backlinks: cursor needs group: "page".', 'Pass group: "page" with the cursor, or omit cursor.');
+ }
+ const limit = parseLimit(p, undefined);
+ let rows = links;
+ const type = typeof p.type === 'string' && p.type ? p.type : undefined;
+ if (type) {
+ const resolved = await referrerScope(ctx, String(p.slug), policy);
+ if (resolved) await assertKnownType(ctx, resolved.scope, type);
+ const keys = [...new Set(links.map(l => `${l.from_source_id}\0${l.from_slug}`))];
+ const types = new Map((await ctx.engine.executeRaw<{ source_id: string; slug: string; type: string | null }>(
+ `SELECT p.source_id, p.slug, p.type FROM pages p JOIN unnest($1::text[], $2::text[]) AS k(s, g) ON p.source_id = k.s AND p.slug = k.g`,
+ [keys.map(k => k.split('\0')[0]), keys.map(k => k.split('\0')[1])])).map(r => [`${r.source_id}\0${r.slug}`, r.type]));
+ const packs = new Map<string, Awaited<ReturnType<typeof loadSourcePack>>>();
+ const filtered: Link[] = [];
+ for (const l of links) {
+ if (!packs.has(l.from_source_id)) packs.set(l.from_source_id, await loadSourcePack(ctx.engine, l.from_source_id));
+ const stored = types.get(`${l.from_source_id}\0${l.from_slug}`) ?? null;
+ if (stored === type || canonicalTypeOf(stored, packs.get(l.from_source_id) ?? null) === type) filtered.push(l);
+ }
+ rows = filtered;
+ }
+ if (limit !== undefined && rows.length > limit) {
+ const notice: Notice = {
+ code: 'listing_truncated', kind: 'info',
+ why: `${rows.length} link rows match; ${limit} were returned. For one row per referring page with a cursor, use group: "page".`,
+ fix: { mcp: { tool: 'get_backlinks', arguments: { slug: p.slug, ...(p.source_id !== undefined ? { source_id: p.source_id } : {}),
+ ...(type ? { type } : {}), group: 'page', limit } }, consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Pages through every referring page, newest first, without dropping rows.' },
+ };
+ ctx.emitNotice?.(notice);
+ rows = rows.slice(0, limit);
+ }
+ return rows;
+}
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index 7643344824..52e7b3663c 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -1,4 +1,5 @@
import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';
+import { filterBacklinkRows, readBacklinkPage, wantsPagedBacklinks } from './backlinks-paged.ts';
/**
* Links + graph operation cluster — pure move from operations.ts (v0.46.x
* tranche 1). MANAGED_LINK_SOURCES stays exported (test suite + operations.ts
@@ -326,13 +327,22 @@ const get_backlinks: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'retrieval',
- description: 'List links pointing to a page. Use when finding what mentions an entity.',
+ description: 'Links to a page; group:"page" pages newest first with total and cursor.',
params: {
slug: { type: 'string', description: 'Page slug.', required: true },
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
+ type: { type: 'string', description: 'Referring page type.' },
+ group: { type: 'string', enum: ['page'], description: 'Row per referrer.' },
+ limit: { type: 'number', description: 'Max 500; default 50.' },
+ cursor: { type: 'string', description: 'From last page.' },
+ },
+ handler: async (ctx, p) => {
+ if (!wantsPagedBacklinks(p)) return readLinkEdges(ctx, p, 'get_backlinks', 'in');
+ if (p.group !== undefined) return readBacklinkPage(ctx, p, (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy);
+ const links = await readLinkEdges(ctx, p, 'get_backlinks', 'in');
+ return filterBacklinkRows(ctx, p, (await resolveLinkReadScope(ctx, p, 'get_backlinks')).policy, links);
},
- handler: async (ctx, p) => readLinkEdges(ctx, p, 'get_backlinks', 'in'),
scope: 'read',
cliHints: { name: 'backlinks', positional: ['slug'] },
};
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index ecd2fb6e31..99a112fdfa 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -35,6 +35,7 @@ import { probeProjectionReadiness } from '../search/projection-readiness.ts';
import { resolveBoostMap, resolveHardExcludes } from '../search/source-boost.ts';
import { pageReadFilter } from '../search/read-policy-sql.ts';
import { QUERY_DESCRIPTION, SEARCH_DESCRIPTION } from '../operations-descriptions.ts';
+import { declaredNames, titleName } from '../mentions/aliases.ts';
import { heldFilesNotice, stampHeldHits } from '../persistence/held-reads.ts';
import { opError } from './contract.ts';
import type { Operation, OperationContext } from './contract.ts';
@@ -106,7 +107,7 @@ const FIELDS_PARAM = {
const RETURN_UNIT_PARAM = {
type: 'string' as const,
enum: ['chunk', 'window', 'section', 'page', 'auto'],
- description: "chunk, window, section, page or auto (default; whole page for conversations).",
+ description: 'auto (default) returns whole conversations.',
};
const RETURN_WINDOW_PARAM = {
type: 'number' as const,
@@ -247,10 +248,6 @@ function indexOfName(text: string, word: string, wholeWord: boolean): number {
return -1;
}
-const ALIAS_DECLARATION = /\b(?:account code|also known as|a\.k\.a\.|aka|short name|ticker|code name)\b\s*[:(]?\s*["\u201c']?([A-Z0-9][A-Za-z0-9&.-]{1,24})/gi;
-/** Every ALIAS_DECLARATION keyword, lowercased: a row containing none of them cannot match the regex. */
-const DECLARATION_KEYWORDS = ['account code', 'also known as', 'a.k.a', 'aka', 'short name', 'ticker', 'code name'];
-
/**
* Pages often declare another name for their subject ("Account code: MULI",
* "also known as ..."), and documents elsewhere use only that name, so a
@@ -264,14 +261,9 @@ export function aliasDeclarations(rows: Array<{ slug: string; title?: string; ch
const q = queryText.toLowerCase();
const out = new Map<string, AliasDeclaration>();
for (const row of rows.slice(0, 10)) {
- const name = (row.title ?? '').split(':').pop()!.trim();
+ const name = titleName(row.title ?? '');
if (!name) continue;
- const text = row.chunk_text ?? '';
- const lower = text.toLowerCase();
- if (!DECLARATION_KEYWORDS.some(k => lower.includes(k))) continue;
- for (const m of text.matchAll(ALIAS_DECLARATION)) {
- const alias = m[1].replace(/[.,;]+$/, '');
- if (!/[A-Z0-9]/.test(alias) || alias.toLowerCase() === name.toLowerCase()) continue;
+ for (const alias of declaredNames(row.chunk_text ?? '', name)) {
const hasName = q.includes(name.toLowerCase());
const hasAlias = indexOfName(q, alias, true) >= 0;
if (hasName === hasAlias) continue;
@@ -668,7 +660,7 @@ const query: Operation = {
/** v0.27.1: image-similarity search. Path resolved on the CLI side
* before the op fires (the op receives raw bytes neither side; the
* CLI loads the file, base64-encodes, and passes through `image`). */
- image: { type: 'string', description: 'Base64 image for image search.' },
+ image: { type: 'string', description: 'Base64 image.' },
image_mime: { type: 'string', description: 'MIME type of image.' },
// #4356 — the text/hybrid path no longer hard-defaults this to 20; an
// omitted OR falsy (0) `limit` resolves from the active search mode's
@@ -694,9 +686,9 @@ const query: Operation = {
snippet_chars: { type: 'number', description: SNIPPET_CHARS_PARAM_DESCRIPTION },
return_unit: RETURN_UNIT_PARAM,
return_window: RETURN_WINDOW_PARAM,
- token_budget: { type: 'number', description: 'Token cap on the returned evidence.' },
+ token_budget: { type: 'number', description: 'Evidence token cap.' },
expand: { type: 'boolean', description: 'Default true; false skips the expansion LLM call.' },
- detail: { type: 'string', description: 'low (compiled truth only), medium (default) or high (all chunks).' },
+ detail: { type: 'string', description: 'low (compiled truth), medium (default) or high (all chunks).' },
fields: FIELDS_PARAM,
mode: { type: 'string', description: 'Local callers only.' },
// v0.20.0 Cathedral II Layer 10 C1/C2: language + symbol-kind filters.
@@ -713,8 +705,8 @@ const query: Operation = {
source_id: { type: 'string', description: SOURCE_ID_PARAM_DESCRIPTION },
cross_modal: { type: 'string', enum: ['text', 'image', 'both', 'auto'], description: 'Default auto.' },
embedding_column: { type: 'string', description: 'Registered embedding column.' },
- adaptive_return: { type: 'boolean', description: 'true when one specific answer is wanted (fewer rows; never returns empty); omit for breadth.' },
- autocut: { type: 'boolean', description: 'Default on (never returns empty); false gives full top-K for breadth. Cuts at the score cliff, unlike adaptive_return.' },
+ adaptive_return: { type: 'boolean', description: 'true when one answer is wanted (fewer rows; never returns empty); omit for breadth.' },
+ autocut: { type: 'boolean', description: 'Default on (never returns empty); false gives full top-K for breadth, unlike adaptive_return.' },
relational: { type: 'boolean', description: 'Relationship-graph arm (default on).' },
},
handler: async (ctx, p) => {
diff --git a/src/core/page-state/rename-alias.ts b/src/core/page-state/rename-alias.ts
index 826ad05f90..c7fa6f86be 100644
--- a/src/core/page-state/rename-alias.ts
+++ b/src/core/page-state/rename-alias.ts
@@ -56,7 +56,7 @@ export async function moveSlugBindings(
AND EXISTS (SELECT 1 FROM facts o WHERE o.source_id = $1 AND o.source_markdown_slug = $2 AND o.row_num = f.row_num)`,
`UPDATE facts SET source_markdown_slug = $3 WHERE source_id = $1 AND source_markdown_slug = $2`,
`DELETE FROM page_aliases a WHERE a.source_id = $1 AND a.slug = $3
- AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $1 AND o.slug = $2 AND o.alias_norm = a.alias_norm)`,
+ AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $1 AND o.slug = $2 AND o.alias_norm = a.alias_norm AND o.origin = a.origin)`,
`UPDATE page_aliases SET slug = $3 WHERE source_id = $1 AND slug = $2`,
];
for (const sql of statements) {
diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.ts
index 60c6e6fb78..bbd83b7d06 100644
--- a/src/core/persistence/links-maintenance.ts
+++ b/src/core/persistence/links-maintenance.ts
@@ -4,28 +4,39 @@ import { prepareAutomaticLinks } from './links-preparation.ts';
import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
import { unrecordedCanonicalTimeline } from './canonical-projections.ts';
+import { runMentionPass, type MentionPassResult } from '../mentions/pass.ts';
+import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMentionPass } from '../mentions/stale.ts';
-export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number; }
+export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number;
+ /** The mention pass (absent when the caller ran links only, as sync does). */
+ mentions?: MentionPassResult; mention_due?: number; mention_last_pass_at?: string | null; }
/** `gbrain extract --stale` on a managed brain, locally or inside the PGLite owner. */
export async function runManagedStaleExtraction(engine: BrainEngine, opts: { sourceId?: string; dryRun?: boolean }): Promise<ManagedLinkExtraction> {
if (!opts.dryRun) return extractManagedStaleLinks(engine, { sourceId: opts.sourceId });
const remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs: LINK_EXTRACTOR_VERSION_TS });
- return { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining };
+ const m = await previewMentionPass(engine, opts.sourceId);
+ return { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining, mention_due: m.due, mention_last_pass_at: m.last_pass_at };
}
/** The `extract --stale` report for a managed brain, in the same text and JSON shapes as the unmanaged sweep. */
export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryRun: boolean, json: boolean): string {
if (json) {
- return JSON.stringify(dryRun ? { action: 'extract_stale_dry_run', stale_pages: result.remaining } : {
+ return JSON.stringify(dryRun ? { action: 'extract_stale_dry_run', stale_pages: result.remaining, mention_due_pages: result.mention_due ?? 0,
+ mention_last_pass_at: result.mention_last_pass_at ?? null } : {
action: 'extract_stale_done', links_created: result.created, links_removed: result.removed, timeline_created: result.timeline,
- pages_processed: result.pages, stale_remaining: result.remaining, ...(result.skipped ? { skipped_changed: result.skipped } : {}),
+ pages_processed: result.pages, stale_remaining: result.remaining + (result.mentions?.remaining ?? 0),
+ ...(result.skipped ? { skipped_changed: result.skipped } : {}), ...(result.mentions ? mentionJsonFields(result.mentions) : {}),
});
}
- if (dryRun) return `(dry run) ${result.remaining} page(s) need link/timeline extraction. Run without --dry-run to extract.`;
+ if (dryRun) {
+ return `(dry run) ${result.remaining} page(s) need link/timeline extraction; ${result.mention_due ?? 0} page(s) need a mention pass ` +
+ `(last pass: ${result.mention_last_pass_at ?? 'never'}). Run without --dry-run to extract.`;
+ }
+ const mentionLine = result.mentions ? formatMentionSummary(result.mentions) : null;
return `Extract --stale: ${result.created} link(s) created, ${result.removed} removed, ${result.timeline} timeline entr(ies) from ${result.pages} page(s).` +
(result.skipped ? ` Skipped ${result.skipped} page(s) edited during extraction or with unresolved attendance; they stay stale.` : '') +
- (result.remaining ? ` ${result.remaining} page(s) remain stale.` : '');
+ (result.remaining ? ` ${result.remaining} page(s) remain stale.` : '') + (mentionLine ? `\n${mentionLine}` : '');
}
/**
@@ -36,6 +47,9 @@ export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryR
* their link targets existed; then pages whose watermark is stale follow. Each
* page's links and watermark commit together, bound to the revision that was
* read; a page edited meanwhile, or with unresolved attendance, stays stale.
+ * Then, unless `mentions: false` (sync's inline extraction), the mention pass
+ * runs (mentions/pass.ts); a budgeted run gives link work half the budget
+ * while mention-due pages exist.
* An unresolved-attendance page is marked attendance-blocked at the revision
* read (doctor reports it apart from lag) and is still reconsidered every run;
* publishing its links later clears the marker with the watermark.
@@ -46,9 +60,12 @@ export function formatManagedStaleExtraction(result: ManagedLinkExtraction, dryR
* PGLite owner delegation all run it, in the process that owns the brain.
*/
export async function extractManagedStaleLinks(engine: BrainEngine,
- opts: { sourceId?: string; slugs?: readonly string[]; maxPages?: number; timeBudgetMs?: number; signal?: AbortSignal } = {}): Promise<ManagedLinkExtraction> {
+ opts: { sourceId?: string; slugs?: readonly string[]; maxPages?: number; timeBudgetMs?: number; signal?: AbortSignal; mentions?: boolean } = {}): Promise<ManagedLinkExtraction> {
const result: ManagedLinkExtraction = { pages: 0, created: 0, removed: 0, timeline: 0, skipped: 0, remaining: 0 };
- const deadline = opts.timeBudgetMs === undefined ? Infinity : Date.now() + opts.timeBudgetMs;
+ const startMs = Date.now();
+ const withMentions = opts.mentions !== false;
+ const deadline = withMentions ? await linkPhaseDeadline(engine, opts.sourceId, startMs, opts.timeBudgetMs)
+ : opts.timeBudgetMs === undefined ? Infinity : startMs + opts.timeBudgetMs;
const versionTs = LINK_EXTRACTOR_VERSION_TS;
const maxPages = opts.maxPages ?? Infinity;
const done = new Set<string>();
@@ -98,5 +115,9 @@ export async function extractManagedStaleLinks(engine: BrainEngine,
}
}
result.remaining = await engine.countStalePagesForExtraction({ sourceId: opts.sourceId, versionTs });
+ if (withMentions) {
+ result.mentions = await runMentionPass(engine, { sourceId: opts.sourceId, signal: opts.signal,
+ ...(opts.timeBudgetMs === undefined ? {} : { deadline: startMs + opts.timeBudgetMs }) });
+ }
return result;
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index b27ca706ca..b3377fd800 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -553,7 +553,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
// the pages stale for `gbrain extract --stale` instead of failing the sync.
const withLinks = async (done: Cursor, synced: SyncResult): Promise<SyncResult> => {
if (company || (done.processingOptions ?? processingOptions).noExtract) return synced;
- try { return { ...synced, links: await extractManagedStaleLinks(engine, { sourceId: done.sourceId, maxPages: 1000, signal,
+ try { return { ...synced, links: await extractManagedStaleLinks(engine, { sourceId: done.sourceId, maxPages: 1000, signal, mentions: false,
slugs: done.entries.flatMap(entry => entry.action === 'import' && entry.slug ? [entry.slug] : []) }) }; }
catch { return synced; }
};
diff --git a/src/core/retry.ts b/src/core/retry.ts
index 53945db558..86c216635d 100644
--- a/src/core/retry.ts
+++ b/src/core/retry.ts
@@ -89,6 +89,8 @@ export const BATCH_AUDIT_SITES = [
'extract.by_mention',
// #3674: --rebuild reconciling delete-then-insert of the mention scan's rows.
'extract.by_mention.rebuild',
+ // Entity mention index: the stale sweep's reconciling mention pass.
+ 'extract.mentions',
// v0.42.7 (#1696): extract --stale incremental sweep.
'extract.stale',
// #3961: atom-provenance edges banked after the completion-receipt flip.
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 16ef4d9ecc..864ddb20fc 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-entity-mention-index.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-entity-mention-index.ts b/src/core/schema-migrations/v201-entity-mention-index.ts
new file mode 100644
index 0000000000..f4428b394d
--- /dev/null
+++ b/src/core/schema-migrations/v201-entity-mention-index.ts
@@ -0,0 +1,76 @@
+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.
+//
+// Entity mention index (src/core/mentions/). Additive only; no existing row
+// is rewritten:
+// - page_aliases gains `origin` (frontmatter | declared | subject; existing
+// rows read as frontmatter), `case_sensitive` and `alias_text` (the alias
+// as written, for case-sensitive matching). The unique key widens to
+// include origin, so a frontmatter alias and the same derived alias of one
+// page coexist and readers apply precedence frontmatter > declared > subject.
+// - page_mention_state: per page, the content revision, mention extractor
+// version and source generation its mention links were published at, and
+// the revision its derived aliases were refreshed at.
+// - mention_gazetteer_entries: the last saved gazetteer entry set per source,
+// diffed on the next pass to mark only affected pages due.
+// - mention_index_status: one row per source (generation, state, pending
+// count, last pass), read by entity cards and get_backlinks as `coverage`.
+// page_aliases carries the managed-writer guard; ALTER TABLE fires no row
+// trigger, so the column adds need no coordinated write.
+export const v201: Migration = {
+ version: 201,
+ name: 'entity_mention_index',
+ idempotent: true,
+ sql: `
+ ALTER TABLE page_aliases ADD COLUMN IF NOT EXISTS origin TEXT NOT NULL DEFAULT 'frontmatter'
+ CHECK (origin IN ('frontmatter','declared','subject'));
+ ALTER TABLE page_aliases ADD COLUMN IF NOT EXISTS case_sensitive BOOLEAN NOT NULL DEFAULT false;
+ ALTER TABLE page_aliases ADD COLUMN IF NOT EXISTS alias_text TEXT;
+ DO $alias_origin$
+ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'page_aliases_origin_uniq' AND conrelid = 'page_aliases'::regclass) THEN
+ ALTER TABLE page_aliases ADD CONSTRAINT page_aliases_origin_uniq UNIQUE (source_id, alias_norm, slug, origin);
+ END IF;
+ ALTER TABLE page_aliases DROP CONSTRAINT IF EXISTS page_aliases_uniq;
+ END $alias_origin$;
+ CREATE TABLE IF NOT EXISTS page_mention_state (
+ page_id INTEGER PRIMARY KEY REFERENCES pages(id) ON DELETE CASCADE,
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ mention_revision UUID,
+ mention_version INTEGER,
+ mention_generation BIGINT,
+ mentions_scanned_at TIMESTAMPTZ,
+ alias_revision UUID,
+ alias_version INTEGER,
+ aliases_refreshed_at TIMESTAMPTZ
+ );
+ CREATE INDEX IF NOT EXISTS page_mention_state_source_idx ON page_mention_state (source_id, mention_version);
+ CREATE TABLE IF NOT EXISTS mention_gazetteer_entries (
+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,
+ name_norm TEXT NOT NULL,
+ target_slug TEXT NOT NULL,
+ case_sensitive BOOLEAN NOT NULL DEFAULT false,
+ PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)
+ );
+ CREATE TABLE IF NOT EXISTS mention_index_status (
+ source_id TEXT PRIMARY KEY REFERENCES sources(id) ON DELETE CASCADE,
+ generation BIGINT NOT NULL DEFAULT 0,
+ state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('complete','pending','disabled','failed')),
+ pending INTEGER NOT NULL DEFAULT 0,
+ counted_at TIMESTAMPTZ,
+ last_pass_at TIMESTAMPTZ,
+ policy_fingerprint TEXT,
+ error TEXT,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+ );
+ DO $rls$ BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname=current_user AND rolbypassrls) THEN
+ ALTER TABLE page_mention_state ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE mention_gazetteer_entries ENABLE ROW LEVEL SECURITY;
+ ALTER TABLE mention_index_status ENABLE ROW LEVEL SECURITY;
+ END IF;
+ END $rls$;
+ `,
+};
diff --git a/src/core/schema-pack/base/gbrain-base-v2.yaml b/src/core/schema-pack/base/gbrain-base-v2.yaml
index 61dc50330c..4ad59ef86f 100644
--- a/src/core/schema-pack/base/gbrain-base-v2.yaml
+++ b/src/core/schema-pack/base/gbrain-base-v2.yaml
@@ -1,13 +1,16 @@
-# gbrain-base-v2 — 15-type DRY/MECE canonical taxonomy
+# gbrain-base-v2 — 16-type DRY/MECE canonical taxonomy
#
# v0.42 (T22) — the response to issue #1479. A production gbrain brain
# (186K pages) had accreted 94 distinct `pages.type` values in 9 clusters
-# of redundancy. This pack collapses them to 14 canonical types plus
-# `note` as the catch-all (15 total) using subtypes/aliases/mapping_rules.
+# of redundancy. This pack collapses them to 15 canonical types plus
+# `note` as the catch-all (16 total) using subtypes/aliases/mapping_rules.
+# v1.3.0 adds `account` (a customer or CRM record, alias `crm`): an entity
+# type, so documents that name an account link to it, kept out of expert
+# routing.
#
# STANDALONE pack (D11/F1): NO `extends:` field. Declaring inheritance
-# would compose gbrain-base's 24 types on top of the 15 declared here,
-# breaking the "14 canonical types" claim. Old types are reached via
+# would compose gbrain-base's 24 types on top of the 16 declared here,
+# breaking the "15 canonical types" claim. Old types are reached via
# the alias graph (query closure) plus the catch-all retype rule (data
# migration).
#
@@ -26,8 +29,8 @@
api_version: gbrain-schema-pack-v1
name: gbrain-base-v2
-version: 1.2.0
-description: 14-type DRY/MECE canonical taxonomy + `note` catch-all (15 total). Successor to gbrain-base. Issue #1479.
+version: 1.3.0
+description: 15-type DRY/MECE canonical taxonomy + `note` catch-all (16 total). Successor to gbrain-base. Issue #1479.
gbrain_min_version: 0.42.0
extends: null
borrow_from: []
@@ -91,6 +94,16 @@ page_types:
extractable: false
expert_routing: true
+ - name: account
+ primitive: entity
+ path_prefixes:
+ - accounts/
+ - crm/
+ aliases:
+ - crm
+ extractable: false
+ expert_routing: false
+
- name: media
primitive: media
path_prefixes:
diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.ts
index f581bf28cd..f8498839c4 100644
--- a/src/core/search/private-visibility.ts
+++ b/src/core/search/private-visibility.ts
@@ -48,6 +48,18 @@ export function privatePagesFilterFragment(pageAlias: string): string {
AND NOT ${declaredLineagePrivateSql(pageAlias)})`;
}
+/**
+ * `privatePagesFilterFragment` with a cheap first test: a page with no
+ * `visibility` or `derived_from` key whose type is not atom, concept or event
+ * is visible by every rule above, so only the remaining pages run the full
+ * check. For scans over thousands of candidate pages (an entity's referrers).
+ */
+export function privatePagesFilterFragmentFast(pageAlias: string): string {
+ return `((${pageAlias}.frontmatter->'visibility' IS NULL AND ${pageAlias}.frontmatter->'derived_from' IS NULL
+ AND ${pageAlias}.type NOT IN ('atom', 'concept', 'event'))
+ OR ${privatePagesFilterFragment(pageAlias)})`;
+}
+
/**
* Declared lineage: a page whose frontmatter `derived_from` names a page (one
* slug or a list, `.md` optional) that is explicitly `visibility: private` in
@@ -57,14 +69,14 @@ export function privatePagesFilterFragment(pageAlias: string): string {
* private input propagates; a missing input does not hide the page.
*/
function declaredLineagePrivateSql(p: string): string {
- return `(jsonb_typeof(${p}.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS (
+ return `(CASE WHEN jsonb_typeof(${p}.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS (
SELECT 1 FROM pages declared_origin
WHERE declared_origin.source_id = ${p}.source_id
AND declared_origin.frontmatter->>'visibility' = 'private'
AND declared_origin.slug IN (
SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text(
CASE WHEN jsonb_typeof(${p}.frontmatter->'derived_from') = 'array' THEN ${p}.frontmatter->'derived_from'
- ELSE jsonb_build_array(${p}.frontmatter->'derived_from') END) AS declared(slug))))`;
+ ELSE jsonb_build_array(${p}.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)`;
}
/**
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index 58d7dc58d7..7651944d68 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -184,16 +184,30 @@ export async function readAliases(query: ReadQuery, aliases: string[], scope?: P
// read filter out of that lookup): without planner statistics (PGLite has no
// autovacuum) the page_aliases -> sources foreign key otherwise makes the planner
// walk every readable page and probe aliases per page.
- const rows = await query<PageRef & { alias_norm: string }>(`
+ // Precedence: within a source, only the claims at the best origin answer
+ // (frontmatter > declared > subject), and a derived (declared or subject)
+ // alias never answers for a name that is another live page's exact title,
+ // so "Acme Example" stays the company page beside "CRM record: Acme Example".
+ const rows = await query<PageRef & { alias_norm: string; rank: number }>(`
WITH a AS MATERIALIZED (
- SELECT m.alias_norm, m.slug, m.source_id FROM page_aliases m
+ SELECT m.alias_norm, m.slug, m.source_id,
+ CASE m.origin WHEN 'subject' THEN 2 WHEN 'declared' THEN 1 ELSE 0 END AS rank
+ FROM page_aliases m
WHERE m.alias_norm = ANY($1::text[]) AND ${aliasScope}
)
- SELECT a.alias_norm, a.slug, a.source_id FROM a
+ SELECT a.alias_norm, a.slug, a.source_id, a.rank FROM a
CROSS JOIN LATERAL (SELECT * FROM pages WHERE source_id = a.source_id AND slug = a.slug OFFSET 0) p
WHERE ${filter}
- ORDER BY a.alias_norm, a.source_id, a.slug`, params);
+ AND (a.rank = 0 OR NOT EXISTS (SELECT 1 FROM pages t WHERE t.source_id = a.source_id AND t.deleted_at IS NULL
+ AND lower(t.title) = a.alias_norm AND t.slug <> a.slug))
+ ORDER BY a.alias_norm, a.source_id, a.rank, a.slug`, params);
+ const best = new Map<string, number>();
for (const row of rows) {
+ const k = `${row.alias_norm}\0${row.source_id}`;
+ best.set(k, Math.min(best.get(k) ?? Infinity, Number(row.rank)));
+ }
+ for (const row of rows) {
+ if (Number(row.rank) > best.get(`${row.alias_norm}\0${row.source_id}`)!) continue;
const refs = out.get(row.alias_norm) ?? [];
if (!refs.some(ref => ref.slug === row.slug && ref.source_id === row.source_id)) refs.push({ slug: row.slug, source_id: row.source_id });
out.set(row.alias_norm, refs);
diff --git a/src/core/snapshot-schema-inputs.ts b/src/core/snapshot-schema-inputs.ts
index ec4fc5d952..114ac40a61 100644
--- a/src/core/snapshot-schema-inputs.ts
+++ b/src/core/snapshot-schema-inputs.ts
@@ -44,6 +44,7 @@ export const SNAPSHOT_DYNAMIC_IMPORTS_NOT_HASHED: Readonly<Record<string, string
'persistence/memory-mutations.ts': 'verbs.ts request-time verb handlers',
'persistence/verb-errors.ts': 'verbs.ts request-time verb handlers',
'verbs/entity-card.ts': 'verbs.ts request-time verb handlers',
+ 'mentions/coverage.ts': 'verbs.ts request-time verb handlers (entity coverage notice)',
'think/index.ts': 'verbs.ts request-time verb handlers',
'embedding.ts': 'verbs.ts request-time verb handlers',
'model-pricing.ts': 'verbs.ts request-time verb handlers',
diff --git a/src/core/verbs.ts b/src/core/verbs.ts
index 1cd8c68b92..92d907cf04 100644
--- a/src/core/verbs.ts
+++ b/src/core/verbs.ts
@@ -168,7 +168,7 @@ const entity: Operation = {
mutating: false,
idempotent: true,
outputRedaction: 'retrieval',
- description: 'MEMORY VERB (v1): one known person/company/project card, zero LLM. A miss returns found:false with near matches and create_safety, so you do not duplicate a page. Facts: recall.',
+ description: 'MEMORY VERB (v1): person/company/account card, zero LLM. referenced_by: every page linking here, by type, newest first (backlink_count excludes mentions); a group\'s `next` pages the rest. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches and create_safety. Facts: recall.',
params: {
name: { type: 'string', required: true, description: 'Name, alias or slug (e.g. "Alice Example").' },
},
@@ -188,14 +188,21 @@ const entity: Operation = {
const t0 = Date.now();
const { buildEntityCard } = await import('./verbs/entity-card.ts');
const result = await buildEntityCard(ctx.engine, ctx.sourceId ?? 'default', name, {
- remote: ctx.remote !== false,
+ remote: ctx.remote !== false, includeReferences: true, surfaceCeiling: ctx.surfaceCeiling,
});
+ const coverage = result.card?.coverage ?? result.coverage;
+ if (coverage) {
+ const { mentionCoverageNotice } = await import('./mentions/coverage.ts');
+ const notice = mentionCoverageNotice(coverage, result.card?.entity.type);
+ if (notice) ctx.emitNotice?.(notice);
+ }
return {
protocol_version: MEMORY_VERBS_VERSION,
found: result.found,
latency_ms: Date.now() - t0,
...(result.card ? { card: result.card } : {}),
...(result.suggestions !== undefined ? { suggestions: result.suggestions } : {}),
+ ...(!result.card && result.coverage ? { coverage: result.coverage } : {}),
};
},
cliHints: { name: 'entity', positional: ['name'] },
@@ -400,6 +407,28 @@ const SYNTHESIS_STATUS_ENUM = [
'ok', 'empty_answer', 'not_json', 'output_truncated', 'no_llm', 'model_unusable', 'llm_error', 'extractive_fallback',
];
+/** `coverage` on entity cards and misses (mentions/coverage.ts). */
+const COVERAGE_SCHEMA = {
+ type: 'object',
+ required: ['state', 'pending_pages', 'last_pass_at'],
+ properties: {
+ state: { type: 'string', enum: ['complete', 'pending', 'disabled', 'type_not_linkable', 'failed'] },
+ pending_pages: { type: 'integer' },
+ last_pass_at: { type: ['string', 'null'] },
+ degraded: { type: 'boolean', const: true },
+ },
+} as const;
+
+/** One `referenced_by` row (mentions/referrers.ts). */
+const REFERENCE_ROW_SCHEMA = {
+ type: 'object',
+ required: ['slug', 'title', 'type', 'canonical_type', 'date', 'date_source', 'preview'],
+ properties: {
+ slug: { type: 'string' }, title: { type: 'string' }, type: { type: ['string', 'null'] }, canonical_type: { type: 'string' },
+ date: { type: ['string', 'null'] }, date_source: { type: 'string' }, preview: { type: 'string' },
+ },
+} as const;
+
const RECALL_BUDGET_ARM_SCHEMA = {
type: 'object',
required: ['candidates', 'kept', 'dropped', 'used'],
@@ -548,8 +577,27 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {
},
backlink_count: { type: 'integer' },
active_fact_count: { type: 'integer' },
+ // Entity recall — ADDITIVE OPTIONAL (frozen-v1 legal); the `entity`
+ // verb sets them, ambient callers (context_pack, delta) do not.
+ referenced_by_count: { type: 'integer' },
+ referenced_by: {
+ type: 'array',
+ items: {
+ type: 'object',
+ required: ['canonical_type', 'total', 'rows'],
+ properties: {
+ canonical_type: { type: 'string' },
+ total: { type: 'integer' },
+ rows: { type: 'array', items: REFERENCE_ROW_SCHEMA },
+ next: { type: 'object', required: ['tool', 'arguments'], properties: {
+ tool: { type: 'string', const: 'get_backlinks' }, arguments: { type: 'object' }, requires_surface: { type: 'string', enum: ['starter'] } } },
+ },
+ },
+ },
+ coverage: COVERAGE_SCHEMA,
},
},
+ coverage: COVERAGE_SCHEMA,
suggestions: {
type: 'array',
items: {
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index a37a9abdb3..2162fb2385 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -26,13 +26,15 @@ import { slugify } from '../entities/resolve.ts';
import { safeSynopsis } from '../context/retrieval-reflex.ts';
import { stampEvidence, markKeywordHits } from '../search/evidence.ts';
import type { SearchResult } from '../types.ts';
+import { loadLinkableTypes } from '../mentions/policy.ts';
+import { readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';
+import { encodeCursor, readReferrerGroups, PAGE_DEFAULT_LIMIT, type ReferenceRow } from '../mentions/referrers.ts';
const EDGE_CAP = 10;
const OPEN_THREADS_CAP = 3;
const OPEN_THREAD_TIMELINE_WINDOW_DAYS = 90;
const SUGGESTION_CAP = 3;
const FACT_FETCH_CAP = 100;
-const ENTITY_PAGE_TYPES = new Set(['person', 'company', 'organization', 'entity']);
export interface EntityCardEdge {
type: string;
@@ -75,6 +77,20 @@ export interface EntityCard {
backlink_count: number;
/** Exact active-fact count (indexed COUNT, not payload length); visibility-filtered for remote. */
active_fact_count: number;
+ /** Distinct pages with any inbound link (every link source, mentions included). `entity` verb only. */
+ referenced_by_count?: number;
+ /** Those pages grouped by pack-canonical type, newest first; capped per group and per card. `entity` verb only. */
+ referenced_by?: ReferenceGroupView[];
+ /** Whether every page in this source has been scanned for this entity's names. `entity` verb only. */
+ coverage?: MentionCoverage;
+}
+
+export interface ReferenceGroupView {
+ canonical_type: string;
+ total: number;
+ rows: Array<Omit<ReferenceRow, 'source_id'>>;
+ /** The call that returns the rest of a truncated group (`requires_surface` when this connection cannot call it). */
+ next?: { tool: 'get_backlinks'; arguments: Record<string, unknown>; requires_surface?: 'starter' };
}
export interface EntitySuggestion {
@@ -87,6 +103,19 @@ export interface EntityCardResult {
found: boolean;
card?: EntityCard;
suggestions?: EntitySuggestion[];
+ /** On a miss with `includeReferences`: the source's mention coverage (a miss may be a not-yet-indexed name). */
+ coverage?: MentionCoverage;
+}
+
+export interface EntityCardOpts {
+ remote: boolean;
+ /**
+ * Compute `referenced_by`, `referenced_by_count` and `coverage` (the `entity`
+ * verb). Ambient callers (context_pack, delta) leave it off.
+ */
+ includeReferences?: boolean;
+ /** The serving surface ceiling; on `verbs` a continuation names the starter surface. */
+ surfaceCeiling?: 'verbs' | 'starter' | 'full';
}
interface CardPageRow {
@@ -112,7 +141,7 @@ export async function buildEntityCard(
engine: BrainEngine,
sourceId: string,
name: string,
- opts: { remote: boolean },
+ opts: EntityCardOpts,
): Promise<EntityCardResult> {
const trimmed = (name ?? '').trim();
if (!trimmed) return { found: false, suggestions: [] };
@@ -195,20 +224,26 @@ export async function buildEntityCard(
// Rank candidates: arm rank asc. Inside the precision arm an explicit slug
// stays stronger than title inference; otherwise exact-title collisions
- // prefer an entity page over transcript/note containers. Recency remains
- // the final tie-break within the same match shape.
+ // prefer a linkable entity page (the source pack's entity types) over
+ // transcript/note containers. Recency remains the final tie-break within
+ // the same match shape.
+ const { types: linkable } = await loadLinkableTypes(engine, sourceId).catch(() => ({ types: [] as string[], pack: null }));
+ const entityTypes = new Set(linkable);
const candidates = [...rankBySlug.entries()]
.map(([s, rank]) => ({ slug: s, rank, row: rowBySlug.get(s) }))
.filter((c): c is { slug: string; rank: number; row: CardPageRow } => c.row !== undefined)
.sort((a, b) =>
a.rank - b.rank
|| (a.rank === ARM_EXACT
- ? exactMatchPreference(a.row, exactSlugs) - exactMatchPreference(b.row, exactSlugs)
+ ? exactMatchPreference(a.row, exactSlugs, entityTypes) - exactMatchPreference(b.row, exactSlugs, entityTypes)
: 0)
|| lastTouchedMs(b.row) - lastTouchedMs(a.row));
if (candidates.length === 0) {
- return { found: false, suggestions: await nearMissSuggestions(engine, sourceId, trimmed, excludePrivate) };
+ return {
+ found: false, suggestions: await nearMissSuggestions(engine, sourceId, trimmed, excludePrivate),
+ ...(opts.includeReferences ? { coverage: await readMentionCoverage(engine, [sourceId]).catch(() => undefined) } : {}),
+ };
}
const best = candidates[0];
@@ -220,6 +255,7 @@ export async function buildEntityCard(
}));
const card = await assembleCard(engine, sourceId, best.row, opts.remote, excludePrivate);
+ if (opts.includeReferences) Object.assign(card, await cardReferences(engine, sourceId, best.row, opts, excludePrivate, entityTypes));
return {
found: true,
card,
@@ -227,9 +263,37 @@ export async function buildEntityCard(
};
}
-function exactMatchPreference(row: CardPageRow, exactSlugs: string[]): number {
+function exactMatchPreference(row: CardPageRow, exactSlugs: string[], entityTypes: ReadonlySet<string>): number {
if (exactSlugs.includes(row.slug)) return 0;
- return ENTITY_PAGE_TYPES.has(row.type ?? '') ? 1 : 2;
+ return entityTypes.has(row.type ?? '') ? 1 : 2;
+}
+
+/**
+ * The `entity` verb's reference fields: every page linking here (mentions
+ * included), grouped by pack-canonical type with the continuation for a
+ * truncated group, and the source's mention coverage. Fail-soft: a failed
+ * read leaves the card without them rather than failing the lookup.
+ */
+async function cardReferences(engine: BrainEngine, sourceId: string, row: CardPageRow, opts: EntityCardOpts, excludePrivate: boolean,
+ entityTypes: ReadonlySet<string>): Promise<Pick<EntityCard, 'referenced_by_count' | 'referenced_by' | 'coverage'>> {
+ try {
+ const { pack } = await loadLinkableTypes(engine, sourceId);
+ const { total, groups } = await readReferrerGroups(engine, { slug: row.slug, sourceId, referrerSources: [sourceId], excludePrivate, pack,
+ keepVisibility: opts.remote ? ['world'] : ['private', 'world'] });
+ let coverage = await readMentionCoverage(engine, [sourceId]);
+ if (coverage.state !== 'disabled' && !entityTypes.has(row.type ?? '')) coverage = { ...coverage, state: 'type_not_linkable', degraded: true };
+ const referenced_by = groups.map((g): ReferenceGroupView => {
+ const rows = g.rows.map(({ source_id: _s, ...rest }) => rest);
+ if (g.rows.length >= g.total) return { canonical_type: g.canonical_type, total: g.total, rows };
+ const last = g.rows[g.rows.length - 1];
+ return { canonical_type: g.canonical_type, total: g.total, rows, next: { tool: 'get_backlinks', arguments: {
+ slug: row.slug, source_id: sourceId, type: g.canonical_type, group: 'page', limit: PAGE_DEFAULT_LIMIT,
+ ...(last ? { cursor: encodeCursor(last) } : {}) }, ...(opts.surfaceCeiling === 'verbs' ? { requires_surface: 'starter' as const } : {}) } };
+ });
+ return { referenced_by_count: total, referenced_by, coverage };
+ } catch {
+ return {};
+ }
}
async function assembleCard(
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 4321c345a8..68ab81bc09 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.60.48.0 -->
+<!-- gbrain-template-stamp: 0.61.1.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/core/retry.test.ts b/test/core/retry.test.ts
index 80e2e3245e..31385ad718 100644
--- a/test/core/retry.test.ts
+++ b/test/core/retry.test.ts
@@ -346,6 +346,8 @@ describe('BATCH_AUDIT_SITES typed enum + isBatchAuditSite guard (D10c codex)', (
'extract.by_mention',
// #3674: --rebuild reconciling delete-then-insert of the mention scan's rows.
'extract.by_mention.rebuild',
+ // Entity mention index: the stale sweep's reconciling mention pass.
+ 'extract.mentions',
'extract.stale',
// #3961: atom-provenance edges banked after the completion-receipt flip.
'cycle.extract_atoms.provenance',
diff --git a/test/e2e/mentions-parity.test.ts b/test/e2e/mentions-parity.test.ts
new file mode 100644
index 0000000000..3e33e57f7a
--- /dev/null
+++ b/test/e2e/mentions-parity.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Entity mention index: PGLite and Postgres parity.
+ *
+ * Protects: the v201 migration shape (origin-aware page_aliases, mention
+ * state, entry and status tables) and the pass, alias writes, entity card
+ * and get_backlinks paging producing the same rows on both engines. Bound
+ * `text[]` parameters, the JSONB-free status writes and the conditional
+ * publish's `FOR SHARE` reads run on real Postgres here, which PGLite cannot
+ * prove. Regression: an engine-specific SQL difference in the pass or the
+ * referrer query.
+ *
+ * Gated by DATABASE_URL (skips without it); the PGLite half always runs.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { setCliOptions } from '../../src/core/cli-options.ts';
+import { extractStaleFromDB } from '../../src/commands/extract.ts';
+import { buildEntityCard } from '../../src/core/verbs/entity-card.ts';
+import { readReferrerPage } from '../../src/core/mentions/referrers.ts';
+import { loadSourcePack } from '../../src/core/mentions/policy.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+const SKIP_PG = !hasDatabase();
+const describeBoth = SKIP_PG ? describe.skip : describe;
+
+async function seed(engine: BrainEngine): Promise<void> {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ const put = (slug: string, type: string, title: string, body: string) =>
+ engine.putPage(slug, { type: type as never, title, compiled_truth: body, timeline: '', frontmatter: {} }, { sourceId: 'default' });
+ await put('crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO\nOwner: Dana Example');
+ await put('crm/124', 'crm', 'CRM record: Quormiro Labs', 'Account code: QULA');
+ await put('people/dana', 'person', 'Dana Example', 'Account owner.');
+ for (let i = 0; i < 14; i++) await put(`tickets/t${String(i).padStart(2, '0')}`, 'ticket', `Ticket ${i}`, `Customer: QUCO\nStatus: ${i === 3 ? 'Open' : 'Closed'}`);
+ await put('meetings/m1', 'meeting', 'Meeting: QULA renewal prep', 'Quormiro asked about Dana Example.');
+ await put('notes/lower', 'note', 'Lowercase', 'quco is not a code here');
+ // Distinct referrer dates: both engines order the newest-first page identically,
+ // independent of how many writes share one clock tick.
+ await engine.executeRaw(
+ `UPDATE pages SET effective_date = TIMESTAMPTZ '2026-01-01T00:00:00Z' + (substring(slug from 10)::int * INTERVAL '1 day')
+ WHERE slug LIKE 'tickets/t%'`);
+}
+
+async function snapshot(engine: BrainEngine) {
+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });
+ const sweep = await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: true });
+ const links = await engine.executeRaw<{ f: string; t: string }>(
+ `SELECT f.slug AS f, t.slug AS t FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE l.link_source = 'mentions' ORDER BY 1, 2`);
+ const aliases = await engine.executeRaw<{ slug: string; alias_norm: string; origin: string; case_sensitive: boolean }>(
+ 'SELECT slug, alias_norm, origin, case_sensitive FROM page_aliases ORDER BY slug, origin, alias_norm');
+ const card = (await buildEntityCard(engine, 'default', 'QUCO', { remote: true, includeReferences: true })).card!;
+ const pack = await loadSourcePack(engine, 'default');
+ const scope = { slug: 'crm/123', sourceId: 'default', referrerSources: ['default'], excludePrivate: true, pack, keepVisibility: ['world' as const] };
+ const first = await readReferrerPage(engine as never, scope, { type: 'ticket', limit: 5 });
+ const columns = await engine.executeRaw<{ column_name: string }>(
+ `SELECT column_name FROM information_schema.columns WHERE table_name = 'page_aliases' ORDER BY column_name`);
+ return {
+ mentions: { state: sweep.mentions?.state, remaining: sweep.mentions?.remaining },
+ links: links.map(r => `${r.f}->${r.t}`),
+ aliases: aliases.map(r => `${r.slug}:${r.origin}:${r.alias_norm}:${r.case_sensitive}`),
+ card: { slug: card.entity.slug, count: card.referenced_by_count, groups: card.referenced_by!.map(g => `${g.canonical_type}:${g.total}:${g.rows.length}`),
+ coverage: card.coverage!.state },
+ page: { total: first.total, truncated: first.truncated, rows: first.rows.map(r => r.slug) },
+ columns: columns.map(r => r.column_name),
+ };
+}
+
+let pglite: PGLiteEngine;
+let pgliteSnap: Awaited<ReturnType<typeof snapshot>>;
+beforeAll(async () => {
+ pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ await seed(pglite);
+ pgliteSnap = await snapshot(pglite);
+}, 180_000);
+afterAll(async () => { await pglite.disconnect(); });
+
+describe('entity mention index (PGLite half)', () => {
+ test('the pass, aliases, card and paging produce the expected rows', () => {
+ expect(pgliteSnap.mentions).toEqual({ state: 'complete', remaining: 0 });
+ expect(pgliteSnap.links).toContain('meetings/m1->crm/124');
+ expect(pgliteSnap.links).not.toContain('notes/lower->crm/123');
+ expect(pgliteSnap.card).toEqual({ slug: 'crm/123', count: 14, groups: ['ticket:14:10'], coverage: 'complete' });
+ expect(pgliteSnap.page).toMatchObject({ total: 14, truncated: true });
+ expect(pgliteSnap.columns).toEqual(expect.arrayContaining(['origin', 'case_sensitive', 'alias_text']));
+ });
+});
+
+describeBoth('entity mention index (Postgres parity)', () => {
+ let pgSnap: Awaited<ReturnType<typeof snapshot>>;
+ beforeAll(async () => {
+ const pg = await setupDB();
+ // setupDB truncates page-keyed tables only; alias rows and mention state from earlier files would leak in.
+ for (const table of ['page_aliases', 'page_mention_state', 'mention_gazetteer_entries', 'mention_index_status']) await pg.executeRaw(`DELETE FROM ${table}`);
+ await seed(pg);
+ pgSnap = await snapshot(pg);
+ }, 180_000);
+ afterAll(async () => { await teardownDB(); });
+
+ test('Postgres produces the same links, alias rows, card and page as PGLite', () => {
+ expect(pgSnap).toEqual(pgliteSnap);
+ });
+});
diff --git a/test/entity-card-perf.slow.test.ts b/test/entity-card-perf.slow.test.ts
index 9966dc2b21..e567aa836f 100644
--- a/test/entity-card-perf.slow.test.ts
+++ b/test/entity-card-perf.slow.test.ts
@@ -35,6 +35,11 @@
* itself is already ratio-guarded above — an O(N) regression in the shared
* arms trips the card gate first.
*
+ * Entity recall: the `entity` verb's path (includeReferences: referenced_by
+ * groups + coverage) has its own p99 gate on the same corpus, with a hub
+ * page carrying 10,000 inbound mention links; the ambient gates below stay
+ * on the reference-free path.
+ *
* .slow.test.ts suffix keeps it out of the fast loop (`bun run test:slow`).
*/
@@ -72,6 +77,8 @@ const DELTA_CHANGED_FACTS = 100;
// is divided by a sub-ms getPage median. 100× stays far below the ≥200× O(N)
// regression signal.)
const RATIO_CEILING = 100;
+const HUB_SLUG = 'companies/hub-company';
+const HUB_LINKS = 10_000;
function percentile(sorted: number[], p: number): number {
const idx = Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1);
@@ -154,6 +161,22 @@ beforeAll(async () => {
'world', 'medium', NOW(), 'perf-seed', 1.0, NOW()
FROM generate_series(0, ${TARGET_ENTITIES - 1}) t, generate_series(1, 20) g`,
);
+ // Entity recall: a hub with 10,000 inbound mention links (the card's worst
+ // case for referenced_by), its referrers spread over five types, and a
+ // complete mention status row (the coverage read).
+ await engine.putPage(HUB_SLUG, { type: 'company', title: 'Hub Company', compiled_truth: '# Hub Company\n\nSynthetic hub.', frontmatter: {} }, { sourceId: 'default' });
+ await db.query(
+ `UPDATE pages SET type = (ARRAY['ticket','email','meeting','note','contract'])[(id % 5) + 1]
+ WHERE id IN (SELECT id FROM pages WHERE slug LIKE 'filler/%' ORDER BY id LIMIT ${HUB_LINKS})`,
+ );
+ await db.query(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, link_source)
+ SELECT f.id, h.id, 'mentions', 'mentions'
+ FROM (SELECT id FROM pages WHERE slug LIKE 'filler/%' ORDER BY id LIMIT ${HUB_LINKS}) f,
+ (SELECT id FROM pages WHERE slug = '${HUB_SLUG}') h
+ ON CONFLICT DO NOTHING`,
+ );
+ await db.query(`INSERT INTO mention_index_status (source_id, state, pending, counted_at, last_pass_at) VALUES ('default', 'complete', 0, now(), now())`);
await engine.executeRaw('ANALYZE pages, links, page_aliases, facts');
}, 300_000);
@@ -210,6 +233,33 @@ describe('entity card p99 latency gate', () => {
}, 300_000);
});
+describe('entity verb with referenced_by (entity recall)', () => {
+ it(`p99 < ${P99_BUDGET_MS}ms with referenced_by and coverage, including a ${HUB_LINKS}-link hub`, async () => {
+ const names: string[] = [];
+ for (let i = 0; i < TARGET_ENTITIES; i++) names.push(`Target Person ${i}`, `tp${i}`, 'Hub Company', `zzz-absent-${i}`);
+ const opts = { remote: true, includeReferences: true };
+ for (let i = 0; i < WARMUP; i++) await buildEntityCard(engine, 'default', names[i % names.length], opts);
+ const samples: number[] = [];
+ let hubCard: Awaited<ReturnType<typeof buildEntityCard>>['card'];
+ for (let i = 0; i < MEASURED; i++) {
+ const name = names[(i * 13) % names.length];
+ const t0 = performance.now();
+ const res = await buildEntityCard(engine, 'default', name, opts);
+ samples.push(performance.now() - t0);
+ if (name === 'Hub Company') hubCard = res.card;
+ }
+ samples.sort((a, b) => a - b);
+ const p50 = percentile(samples, 50);
+ const p99 = percentile(samples, 99);
+ // eslint-disable-next-line no-console
+ console.log(`[entity-recall-perf] hub=${HUB_LINKS} links entity+references p50=${p50.toFixed(2)}ms p99=${p99.toFixed(2)}ms | budget=${P99_BUDGET_MS}ms`);
+ // Real work: the hub card carries every referrer in its count and at most 50 rows.
+ expect(hubCard?.referenced_by_count).toBe(HUB_LINKS);
+ expect(hubCard!.referenced_by!.reduce((n, g) => n + g.rows.length, 0)).toBeLessThanOrEqual(50);
+ expect(p99).toBeLessThan(P99_BUDGET_MS);
+ }, 300_000);
+});
+
describe('context_pack p99 latency gate (v0.45.7 ambient recall)', () => {
it(`pack p99 < ${BOUNDARY_P99_BUDGET_MS}ms with ${PACK_DEFAULT_MAX_ENTITIES} standing entities on ${PAGES} pages`, async () => {
// 8 standing entities per call, rotated across the 50 targets and the
diff --git a/test/extract-stale.test.ts b/test/extract-stale.test.ts
index dc8facd0ab..a2f88100bf 100644
--- a/test/extract-stale.test.ts
+++ b/test/extract-stale.test.ts
@@ -432,13 +432,17 @@ describe('gbrain extract --stale', () => {
timeBudgetMs: 0,
});
expect(r.pagesProcessed).toBe(25);
- expect(r.staleRemaining).toBe(1);
+ // staleRemaining counts link-stale pages plus mention-due pages (the
+ // mention pass shares the exhausted budget, so all 26 are still due).
+ expect(r.mentions?.remaining).toBe(26);
+ expect(r.staleRemaining).toBe(1 + 26);
// Default budget (~30 min) finishes the remainder.
const r2 = await extractStaleFromDB(engine, {
dryRun: false, jsonMode: true, includeFrontmatter: false, catchUp: false,
});
expect(r2.pagesProcessed).toBe(1);
+ expect(r2.mentions?.remaining).toBe(0);
expect(r2.staleRemaining).toBe(0);
});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 99a6d7000e..eb668ecb20 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -99,6 +99,11 @@
"mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"mcp_spend_reservations.mcp_spend_reservations_pkey": "p PRIMARY KEY (reservation_id)",
"mcp_spend_reservations.mcp_spend_reservations_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'settled'::text, 'expired'::text])))",
+ "mention_gazetteer_entries.mention_gazetteer_entries_pkey": "p PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_gazetteer_entries.mention_gazetteer_entries_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_pkey": "p PRIMARY KEY (source_id)",
+ "mention_index_status.mention_index_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'disabled'::text, 'failed'::text])))",
"migration_impact_log.migration_impact_log_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"migration_impact_log.migration_impact_log_pkey": "p PRIMARY KEY (id)",
"minion_attachments.chk_attachment_size": "c CHECK ((size_bytes >= 0))",
@@ -147,11 +152,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
+ "page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
- "page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
+ "page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
"page_projection_jobs.page_projection_jobs_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",
"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
@@ -456,6 +465,12 @@
"mcp_spend_reservations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "mention_gazetteer_entries": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "mention_index_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"migration_impact_log": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -507,6 +522,9 @@
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_mention_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_projection_jobs": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -834,6 +852,8 @@
"mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",
"mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)",
"mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)",
+ "mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_index_status_pkey": "CREATE UNIQUE INDEX mention_index_status_pkey ON public.mention_index_status USING btree (source_id)",
"migration_impact_log_attribution_idx": "CREATE INDEX migration_impact_log_attribution_idx ON public.migration_impact_log USING btree (job_id, source_id) WHERE (job_id IS NOT NULL)",
"migration_impact_log_pkey": "CREATE UNIQUE INDEX migration_impact_log_pkey ON public.migration_impact_log USING btree (id)",
"migration_impact_log_remediation_idx": "CREATE INDEX migration_impact_log_remediation_idx ON public.migration_impact_log USING btree (remediation_id, applied_at DESC)",
@@ -865,10 +885,12 @@
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
+ "page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
- "page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
+ "page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",
"page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)",
@@ -1737,6 +1759,29 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "mention_gazetteer_entries": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 name_norm text/text NOT NULL",
+ "3 target_slug text/text NOT NULL",
+ "4 case_sensitive boolean/bool NOT NULL DEFAULT false"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "mention_index_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 generation bigint/int8 NOT NULL DEFAULT 0",
+ "3 state text/text NOT NULL DEFAULT 'pending'::text",
+ "4 pending integer/int4 NOT NULL DEFAULT 0",
+ "5 counted_at timestamp with time zone/timestamptz NULL",
+ "6 last_pass_at timestamp with time zone/timestamptz NULL",
+ "7 policy_fingerprint text/text NULL",
+ "8 error text/text NULL",
+ "9 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"migration_impact_log": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('migration_impact_log_id_seq'::regclass)",
@@ -1998,7 +2043,10 @@
"2 source_id text/text NOT NULL",
"3 alias_norm text/text NOT NULL",
"4 slug text/text NOT NULL",
- "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "6 origin text/text NOT NULL DEFAULT 'frontmatter'::text",
+ "7 case_sensitive boolean/bool NOT NULL DEFAULT false",
+ "8 alias_text text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2009,6 +2057,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_mention_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 mention_revision uuid/uuid NULL",
+ "4 mention_version integer/int4 NULL",
+ "5 mention_generation bigint/int8 NULL",
+ "6 mentions_scanned_at timestamp with time zone/timestamptz NULL",
+ "7 alias_revision uuid/uuid NULL",
+ "8 alias_version integer/int4 NULL",
+ "9 aliases_refreshed_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_projection_jobs": {
"columns": [
"1 source_incarnation uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index db8a7c1b35..9ce5f7c374 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -99,6 +99,11 @@
"mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"mcp_spend_reservations.mcp_spend_reservations_pkey": "p PRIMARY KEY (reservation_id)",
"mcp_spend_reservations.mcp_spend_reservations_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'settled'::text, 'expired'::text])))",
+ "mention_gazetteer_entries.mention_gazetteer_entries_pkey": "p PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_gazetteer_entries.mention_gazetteer_entries_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_pkey": "p PRIMARY KEY (source_id)",
+ "mention_index_status.mention_index_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'disabled'::text, 'failed'::text])))",
"migration_impact_log.migration_impact_log_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"migration_impact_log.migration_impact_log_pkey": "p PRIMARY KEY (id)",
"minion_attachments.chk_attachment_size": "c CHECK ((size_bytes >= 0))",
@@ -147,11 +152,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
+ "page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
- "page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
+ "page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
"page_projection_jobs.page_projection_jobs_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",
"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
@@ -456,6 +465,12 @@
"mcp_spend_reservations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "mention_gazetteer_entries": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "mention_index_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"migration_impact_log": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -507,6 +522,9 @@
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_mention_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_projection_jobs": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -834,6 +852,8 @@
"mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",
"mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)",
"mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)",
+ "mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_index_status_pkey": "CREATE UNIQUE INDEX mention_index_status_pkey ON public.mention_index_status USING btree (source_id)",
"migration_impact_log_attribution_idx": "CREATE INDEX migration_impact_log_attribution_idx ON public.migration_impact_log USING btree (job_id, source_id) WHERE (job_id IS NOT NULL)",
"migration_impact_log_pkey": "CREATE UNIQUE INDEX migration_impact_log_pkey ON public.migration_impact_log USING btree (id)",
"migration_impact_log_remediation_idx": "CREATE INDEX migration_impact_log_remediation_idx ON public.migration_impact_log USING btree (remediation_id, applied_at DESC)",
@@ -865,10 +885,12 @@
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
+ "page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
- "page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
+ "page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",
"page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)",
@@ -1737,6 +1759,29 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "mention_gazetteer_entries": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 name_norm text/text NOT NULL",
+ "3 target_slug text/text NOT NULL",
+ "4 case_sensitive boolean/bool NOT NULL DEFAULT false"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "mention_index_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 generation bigint/int8 NOT NULL DEFAULT 0",
+ "3 state text/text NOT NULL DEFAULT 'pending'::text",
+ "4 pending integer/int4 NOT NULL DEFAULT 0",
+ "5 counted_at timestamp with time zone/timestamptz NULL",
+ "6 last_pass_at timestamp with time zone/timestamptz NULL",
+ "7 policy_fingerprint text/text NULL",
+ "8 error text/text NULL",
+ "9 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"migration_impact_log": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('migration_impact_log_id_seq'::regclass)",
@@ -1998,7 +2043,10 @@
"2 source_id text/text NOT NULL",
"3 alias_norm text/text NOT NULL",
"4 slug text/text NOT NULL",
- "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "6 origin text/text NOT NULL DEFAULT 'frontmatter'::text",
+ "7 case_sensitive boolean/bool NOT NULL DEFAULT false",
+ "8 alias_text text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2009,6 +2057,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_mention_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 mention_revision uuid/uuid NULL",
+ "4 mention_version integer/int4 NULL",
+ "5 mention_generation bigint/int8 NULL",
+ "6 mentions_scanned_at timestamp with time zone/timestamptz NULL",
+ "7 alias_revision uuid/uuid NULL",
+ "8 alias_version integer/int4 NULL",
+ "9 aliases_refreshed_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_projection_jobs": {
"columns": [
"1 source_incarnation uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 796685335b..7b95169ed7 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -99,6 +99,11 @@
"mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"mcp_spend_reservations.mcp_spend_reservations_pkey": "p PRIMARY KEY (reservation_id)",
"mcp_spend_reservations.mcp_spend_reservations_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'settled'::text, 'expired'::text])))",
+ "mention_gazetteer_entries.mention_gazetteer_entries_pkey": "p PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_gazetteer_entries.mention_gazetteer_entries_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_pkey": "p PRIMARY KEY (source_id)",
+ "mention_index_status.mention_index_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'disabled'::text, 'failed'::text])))",
"migration_impact_log.migration_impact_log_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"migration_impact_log.migration_impact_log_pkey": "p PRIMARY KEY (id)",
"minion_attachments.chk_attachment_size": "c CHECK ((size_bytes >= 0))",
@@ -147,11 +152,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
+ "page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
- "page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
+ "page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
"page_projection_jobs.page_projection_jobs_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",
"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
@@ -456,6 +465,12 @@
"mcp_spend_reservations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "mention_gazetteer_entries": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "mention_index_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"migration_impact_log": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -507,6 +522,9 @@
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_mention_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_projection_jobs": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -830,6 +848,8 @@
"mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",
"mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)",
"mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)",
+ "mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_index_status_pkey": "CREATE UNIQUE INDEX mention_index_status_pkey ON public.mention_index_status USING btree (source_id)",
"migration_impact_log_attribution_idx": "CREATE INDEX migration_impact_log_attribution_idx ON public.migration_impact_log USING btree (job_id, source_id) WHERE (job_id IS NOT NULL)",
"migration_impact_log_pkey": "CREATE UNIQUE INDEX migration_impact_log_pkey ON public.migration_impact_log USING btree (id)",
"migration_impact_log_remediation_idx": "CREATE INDEX migration_impact_log_remediation_idx ON public.migration_impact_log USING btree (remediation_id, applied_at DESC)",
@@ -861,10 +881,12 @@
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
+ "page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
- "page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
+ "page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",
"page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)",
@@ -1733,6 +1755,29 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "mention_gazetteer_entries": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 name_norm text/text NOT NULL",
+ "3 target_slug text/text NOT NULL",
+ "4 case_sensitive boolean/bool NOT NULL DEFAULT false"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "mention_index_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 generation bigint/int8 NOT NULL DEFAULT 0",
+ "3 state text/text NOT NULL DEFAULT 'pending'::text",
+ "4 pending integer/int4 NOT NULL DEFAULT 0",
+ "5 counted_at timestamp with time zone/timestamptz NULL",
+ "6 last_pass_at timestamp with time zone/timestamptz NULL",
+ "7 policy_fingerprint text/text NULL",
+ "8 error text/text NULL",
+ "9 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"migration_impact_log": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('migration_impact_log_id_seq'::regclass)",
@@ -1994,7 +2039,10 @@
"2 source_id text/text NOT NULL",
"3 alias_norm text/text NOT NULL",
"4 slug text/text NOT NULL",
- "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "6 origin text/text NOT NULL DEFAULT 'frontmatter'::text",
+ "7 case_sensitive boolean/bool NOT NULL DEFAULT false",
+ "8 alias_text text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2005,6 +2053,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_mention_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 mention_revision uuid/uuid NULL",
+ "4 mention_version integer/int4 NULL",
+ "5 mention_generation bigint/int8 NULL",
+ "6 mentions_scanned_at timestamp with time zone/timestamptz NULL",
+ "7 alias_revision uuid/uuid NULL",
+ "8 alias_version integer/int4 NULL",
+ "9 aliases_refreshed_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_projection_jobs": {
"columns": [
"1 source_incarnation uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 65013754c1..ad9f6482c1 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -102,6 +102,11 @@
"mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"mcp_spend_reservations.mcp_spend_reservations_pkey": "p PRIMARY KEY (reservation_id)",
"mcp_spend_reservations.mcp_spend_reservations_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'settled'::text, 'expired'::text])))",
+ "mention_gazetteer_entries.mention_gazetteer_entries_pkey": "p PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_gazetteer_entries.mention_gazetteer_entries_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_pkey": "p PRIMARY KEY (source_id)",
+ "mention_index_status.mention_index_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'disabled'::text, 'failed'::text])))",
"migration_impact_log.migration_impact_log_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"migration_impact_log.migration_impact_log_pkey": "p PRIMARY KEY (id)",
"minion_attachments.chk_attachment_size": "c CHECK ((size_bytes >= 0))",
@@ -151,11 +156,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
+ "page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
- "page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
+ "page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
"page_projection_jobs.page_projection_jobs_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",
"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
@@ -463,6 +472,12 @@
"mcp_spend_reservations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "mention_gazetteer_entries": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "mention_index_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"migration_impact_log": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -514,6 +529,9 @@
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_mention_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_projection_jobs": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -837,6 +855,8 @@
"mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",
"mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)",
"mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)",
+ "mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_index_status_pkey": "CREATE UNIQUE INDEX mention_index_status_pkey ON public.mention_index_status USING btree (source_id)",
"migration_impact_log_attribution_idx": "CREATE INDEX migration_impact_log_attribution_idx ON public.migration_impact_log USING btree (job_id, source_id) WHERE (job_id IS NOT NULL)",
"migration_impact_log_pkey": "CREATE UNIQUE INDEX migration_impact_log_pkey ON public.migration_impact_log USING btree (id)",
"migration_impact_log_remediation_idx": "CREATE INDEX migration_impact_log_remediation_idx ON public.migration_impact_log USING btree (remediation_id, applied_at DESC)",
@@ -869,10 +889,12 @@
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
+ "page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
- "page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
+ "page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",
"page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)",
@@ -1749,6 +1771,29 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "mention_gazetteer_entries": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 name_norm text/text NOT NULL",
+ "3 target_slug text/text NOT NULL",
+ "4 case_sensitive boolean/bool NOT NULL DEFAULT false"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "mention_index_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 generation bigint/int8 NOT NULL DEFAULT 0",
+ "3 state text/text NOT NULL DEFAULT 'pending'::text",
+ "4 pending integer/int4 NOT NULL DEFAULT 0",
+ "5 counted_at timestamp with time zone/timestamptz NULL",
+ "6 last_pass_at timestamp with time zone/timestamptz NULL",
+ "7 policy_fingerprint text/text NULL",
+ "8 error text/text NULL",
+ "9 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"migration_impact_log": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('migration_impact_log_id_seq'::regclass)",
@@ -2010,7 +2055,10 @@
"2 source_id text/text NOT NULL",
"3 alias_norm text/text NOT NULL",
"4 slug text/text NOT NULL",
- "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "6 origin text/text NOT NULL DEFAULT 'frontmatter'::text",
+ "7 case_sensitive boolean/bool NOT NULL DEFAULT false",
+ "8 alias_text text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2021,6 +2069,20 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_mention_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 mention_revision uuid/uuid NULL",
+ "4 mention_version integer/int4 NULL",
+ "5 mention_generation bigint/int8 NULL",
+ "6 mentions_scanned_at timestamp with time zone/timestamptz NULL",
+ "7 alias_revision uuid/uuid NULL",
+ "8 alias_version integer/int4 NULL",
+ "9 aliases_refreshed_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_projection_jobs": {
"columns": [
"1 source_incarnation uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index ecdff86800..c84dc0f19b 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -102,6 +102,11 @@
"mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"mcp_spend_reservations.mcp_spend_reservations_pkey": "p PRIMARY KEY (reservation_id)",
"mcp_spend_reservations.mcp_spend_reservations_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'settled'::text, 'expired'::text])))",
+ "mention_gazetteer_entries.mention_gazetteer_entries_pkey": "p PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_gazetteer_entries.mention_gazetteer_entries_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_pkey": "p PRIMARY KEY (source_id)",
+ "mention_index_status.mention_index_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'disabled'::text, 'failed'::text])))",
"migration_impact_log.migration_impact_log_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"migration_impact_log.migration_impact_log_pkey": "p PRIMARY KEY (id)",
"minion_attachments.chk_attachment_size": "c CHECK ((size_bytes >= 0))",
@@ -151,11 +156,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
+ "page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
- "page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
+ "page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
"page_projection_jobs.page_projection_jobs_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",
"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
@@ -463,6 +472,12 @@
"mcp_spend_reservations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "mention_gazetteer_entries": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "mention_index_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"migration_impact_log": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -514,6 +529,9 @@
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_mention_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_projection_jobs": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -837,6 +855,8 @@
"mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",
"mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)",
"mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)",
+ "mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_index_status_pkey": "CREATE UNIQUE INDEX mention_index_status_pkey ON public.mention_index_status USING btree (source_id)",
"migration_impact_log_attribution_idx": "CREATE INDEX migration_impact_log_attribution_idx ON public.migration_impact_log USING btree (job_id, source_id) WHERE (job_id IS NOT NULL)",
"migration_impact_log_pkey": "CREATE UNIQUE INDEX migration_impact_log_pkey ON public.migration_impact_log USING btree (id)",
"migration_impact_log_remediation_idx": "CREATE INDEX migration_impact_log_remediation_idx ON public.migration_impact_log USING btree (remediation_id, applied_at DESC)",
@@ -869,10 +889,12 @@
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
+ "page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
- "page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
+ "page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",
"page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)",
@@ -1749,6 +1771,29 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "mention_gazetteer_entries": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 name_norm text/text NOT NULL",
+ "3 target_slug text/text NOT NULL",
+ "4 case_sensitive boolean/bool NOT NULL DEFAULT false"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "mention_index_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 generation bigint/int8 NOT NULL DEFAULT 0",
+ "3 state text/text NOT NULL DEFAULT 'pending'::text",
+ "4 pending integer/int4 NOT NULL DEFAULT 0",
+ "5 counted_at timestamp with time zone/timestamptz NULL",
+ "6 last_pass_at timestamp with time zone/timestamptz NULL",
+ "7 policy_fingerprint text/text NULL",
+ "8 error text/text NULL",
+ "9 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"migration_impact_log": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('migration_impact_log_id_seq'::regclass)",
@@ -2010,7 +2055,10 @@
"2 source_id text/text NOT NULL",
"3 alias_norm text/text NOT NULL",
"4 slug text/text NOT NULL",
- "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "6 origin text/text NOT NULL DEFAULT 'frontmatter'::text",
+ "7 case_sensitive boolean/bool NOT NULL DEFAULT false",
+ "8 alias_text text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2021,6 +2069,20 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_mention_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 mention_revision uuid/uuid NULL",
+ "4 mention_version integer/int4 NULL",
+ "5 mention_generation bigint/int8 NULL",
+ "6 mentions_scanned_at timestamp with time zone/timestamptz NULL",
+ "7 alias_revision uuid/uuid NULL",
+ "8 alias_version integer/int4 NULL",
+ "9 aliases_refreshed_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_projection_jobs": {
"columns": [
"1 source_incarnation uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index a815cd1c99..b85d899a3b 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -102,6 +102,11 @@
"mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"mcp_spend_reservations.mcp_spend_reservations_pkey": "p PRIMARY KEY (reservation_id)",
"mcp_spend_reservations.mcp_spend_reservations_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'settled'::text, 'expired'::text])))",
+ "mention_gazetteer_entries.mention_gazetteer_entries_pkey": "p PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_gazetteer_entries.mention_gazetteer_entries_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_pkey": "p PRIMARY KEY (source_id)",
+ "mention_index_status.mention_index_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'disabled'::text, 'failed'::text])))",
"migration_impact_log.migration_impact_log_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"migration_impact_log.migration_impact_log_pkey": "p PRIMARY KEY (id)",
"minion_attachments.chk_attachment_size": "c CHECK ((size_bytes >= 0))",
@@ -151,11 +156,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
+ "page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
- "page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
+ "page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
"page_projection_jobs.page_projection_jobs_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",
"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
@@ -463,6 +472,12 @@
"mcp_spend_reservations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "mention_gazetteer_entries": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "mention_index_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"migration_impact_log": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -514,6 +529,9 @@
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_mention_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_projection_jobs": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -833,6 +851,8 @@
"mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",
"mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)",
"mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)",
+ "mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_index_status_pkey": "CREATE UNIQUE INDEX mention_index_status_pkey ON public.mention_index_status USING btree (source_id)",
"migration_impact_log_attribution_idx": "CREATE INDEX migration_impact_log_attribution_idx ON public.migration_impact_log USING btree (job_id, source_id) WHERE (job_id IS NOT NULL)",
"migration_impact_log_pkey": "CREATE UNIQUE INDEX migration_impact_log_pkey ON public.migration_impact_log USING btree (id)",
"migration_impact_log_remediation_idx": "CREATE INDEX migration_impact_log_remediation_idx ON public.migration_impact_log USING btree (remediation_id, applied_at DESC)",
@@ -865,10 +885,12 @@
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
+ "page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
- "page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
+ "page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",
"page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)",
@@ -1745,6 +1767,29 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "mention_gazetteer_entries": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 name_norm text/text NOT NULL",
+ "3 target_slug text/text NOT NULL",
+ "4 case_sensitive boolean/bool NOT NULL DEFAULT false"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "mention_index_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 generation bigint/int8 NOT NULL DEFAULT 0",
+ "3 state text/text NOT NULL DEFAULT 'pending'::text",
+ "4 pending integer/int4 NOT NULL DEFAULT 0",
+ "5 counted_at timestamp with time zone/timestamptz NULL",
+ "6 last_pass_at timestamp with time zone/timestamptz NULL",
+ "7 policy_fingerprint text/text NULL",
+ "8 error text/text NULL",
+ "9 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"migration_impact_log": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('migration_impact_log_id_seq'::regclass)",
@@ -2006,7 +2051,10 @@
"2 source_id text/text NOT NULL",
"3 alias_norm text/text NOT NULL",
"4 slug text/text NOT NULL",
- "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "6 origin text/text NOT NULL DEFAULT 'frontmatter'::text",
+ "7 case_sensitive boolean/bool NOT NULL DEFAULT false",
+ "8 alias_text text/text NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2017,6 +2065,20 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_mention_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 mention_revision uuid/uuid NULL",
+ "4 mention_version integer/int4 NULL",
+ "5 mention_generation bigint/int8 NULL",
+ "6 mentions_scanned_at timestamp with time zone/timestamptz NULL",
+ "7 alias_revision uuid/uuid NULL",
+ "8 alias_version integer/int4 NULL",
+ "9 aliases_refreshed_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_projection_jobs": {
"columns": [
"1 source_incarnation uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index 2dd82bd490..113f34433e 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -673,21 +673,21 @@
"stdout": [
"Usage: gbrain query <query> [options]",
"",
- "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies; raw transcripts: `gbrain transcripts recent` on the brain host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key, else keyword-only; expansion needs a chat-model key. fields: \"full\" adds diagnostics.",
+ "Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.",
"",
"Options:",
" <query> Question or topic (required unless image).",
- " --image Base64 image for image search.",
+ " --image Base64 image.",
" --image-mime MIME type of image.",
" --limit Default 10/25/50 by search mode.",
" --offset Rows to skip.",
" --types Page types, e.g. ['person'].",
" --snippet-chars Max chars per chunk_text (0 = full).",
- " --return-unit chunk, window, section, page or auto (default; whole page for conversations).",
+ " --return-unit auto (default) returns whole conversations.",
" --return-window Neighbor chunks each side for window (1-3).",
- " --token-budget Token cap on the returned evidence.",
+ " --token-budget Evidence token cap.",
" --expand Default true; false skips the expansion LLM call.",
- " --detail low (compiled truth only), medium (default) or high (all chunks).",
+ " --detail low (compiled truth), medium (default) or high (all chunks).",
" --fields lean (remote default) or full.",
" --mode Local callers only.",
" --lang Code language.",
@@ -701,8 +701,8 @@
" --source-id One source, or '__all__'.",
" --cross-modal Default auto.",
" --embedding-column Registered embedding column.",
- " --adaptive-return true when one specific answer is wanted (fewer rows; never returns empty); omit for breadth.",
- " --autocut Default on (never returns empty); false gives full top-K for breadth. Cuts at the score cliff, unlike adaptive_return.",
+ " --adaptive-return true when one answer is wanted (fewer rows; never returns empty); omit for breadth.",
+ " --autocut Default on (never returns empty); false gives full top-K for breadth, unlike adaptive_return.",
" --relational Relationship-graph arm (default on)."
]
},
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index 8c613f7b27..0f20ccd0b7 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": 197371,
+ "stdoutSha256": "aa63485c6fdaab8f7ec2fd5f61167df74d3a74468e1e5f54b59e04c146224962",
"toolNames": [
"remember",
"entity",
@@ -250,7 +250,7 @@
"scope": "write"
},
{
- "description": "MEMORY VERB (v1): one known person/company/project card, zero LLM. A miss returns found:false with near matches and create_safety, so you do not duplicate a page. Facts: recall.",
+ "description": "MEMORY VERB (v1): person/company/account card, zero LLM. referenced_by: every page linking here, by type, newest first (backlink_count excludes mentions); a group's `next` pages the rest. Previews are not evidence: fetch the page before stating status or dates. Miss: found:false with near matches and create_safety. Facts: recall.",
"idempotent": true,
"local_only": false,
"mutating": false,
@@ -897,7 +897,7 @@
"scope": "write"
},
{
- "description": "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal questions: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.",
+ "description": "Cheap hybrid search (vector + keyword), no LLM expansion, top 20: for exact tokens, names, field values. Results are NOT proof of coverage: concepts or landscape, use `query`; exhaustive lists, list_pages. return_unit returns whole sections or conversations. Personal: get_recent_salience; saved facts: recall. fields: \"full\" adds diagnostics.",
"idempotent": true,
"local_only": false,
"mutating": false,
@@ -954,7 +954,7 @@
"type": "string"
},
"return_unit": {
- "description": "chunk, window, section, page or auto (default; whole page for conversations).",
+ "description": "auto (default) returns whole conversations.",
"enum": [
"chunk",
"window",
@@ -1005,7 +1005,7 @@
"scope": "read"
},
{
- "description": "Ranked hybrid search with multi-query expansion, for concept / synonym / landscape questions: expansion recovers synonym-phrased matches. Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal questions: get_recent_salience, find_anomalies; raw transcripts: `gbrain transcripts recent` on the brain host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key, else keyword-only; expansion needs a chat-model key. fields: \"full\" adds diagnostics.",
+ "description": "Hybrid search plus multi-query expansion for concept or landscape questions (expansion recovers synonym-phrased matches). Still top-K; return_unit returns whole sections or conversations. Lists: list_pages. Exact tokens: `search` is cheaper (no expansion LLM call). Personal: get_recent_salience, find_anomalies; transcripts: `gbrain transcripts recent` on the host. Do NOT assume 'crazy' means impressive (often difficult or emotionally charged). Needs an embedding key (else keyword-only); expansion needs a chat key. fields: \"full\" adds diagnostics.",
"idempotent": true,
"local_only": false,
"mutating": false,
@@ -1044,11 +1044,11 @@
"schema": {
"properties": {
"adaptive_return": {
- "description": "true when one specific answer is wanted (fewer rows; never returns empty); omit for breadth.",
+ "description": "true when one answer is wanted (fewer rows; never returns empty); omit for breadth.",
"type": "boolean"
},
"autocut": {
- "description": "Default on (never returns empty); false gives full top-K for breadth. Cuts at the score cliff, unlike adaptive_return.",
+ "description": "Default on (never returns empty); false gives full top-K for breadth, unlike adaptive_return.",
"type": "boolean"
},
"cross_modal": {
@@ -1062,7 +1062,7 @@
"type": "string"
},
"detail": {
- "description": "low (compiled truth only), medium (default) or high (all chunks).",
+ "description": "low (compiled truth), medium (default) or high (all chunks).",
"type": "string"
},
"embedding_column": {
@@ -1082,7 +1082,7 @@
"type": "string"
},
"image": {
- "description": "Base64 image for image search.",
+ "description": "Base64 image.",
"type": "string"
},
"image_mime": {
@@ -1127,7 +1127,7 @@
"type": "boolean"
},
"return_unit": {
- "description": "chunk, window, section, page or auto (default; whole page for conversations).",
+ "description": "auto (default) returns whole conversations.",
"enum": [
"chunk",
"window",
@@ -1167,7 +1167,7 @@
"type": "string"
},
"token_budget": {
- "description": "Token cap on the returned evidence.",
+ "description": "Evidence token cap.",
"type": "number"
},
"types": {
@@ -1588,15 +1588,19 @@
"scope": "read"
},
{
- "description": "List links pointing to a page. Use when finding what mentions an entity.",
+ "description": "Links to a page; group:\"page\" pages newest first with total and cursor.",
"idempotent": true,
"local_only": false,
"mutating": false,
"name": "get_backlinks",
"parameters": {
"all_sources": "boolean?",
+ "cursor": "string?",
+ "group": "string?",
+ "limit": "number?",
"slug": "string",
- "source_id": "string?"
+ "source_id": "string?",
+ "type": "string?"
},
"required_scopes": [],
"schema": {
@@ -1605,6 +1609,21 @@
"description": "Same as source_id __all__.",
"type": "boolean"
},
+ "cursor": {
+ "description": "From last page.",
+ "type": "string"
+ },
+ "group": {
+ "description": "Row per referrer.",
+ "enum": [
+ "page"
+ ],
+ "type": "string"
+ },
+ "limit": {
+ "description": "Max 500; default 50.",
+ "type": "number"
+ },
"slug": {
"description": "Page slug.",
"type": "string"
@@ -1612,6 +1631,10 @@
"source_id": {
"description": "One source, or '__all__'.",
"type": "string"
+ },
+ "type": {
+ "description": "Referring page type.",
+ "type": "string"
}
},
"required": [
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 22c4a12451..8b43c9ce1f 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -507,7 +507,7 @@
},
{
"category": "meta",
- "message": "Version 200 (latest: 200)",
+ "message": "Version 201 (latest: 201)",
"name": "schema_version",
"status": "ok"
},
@@ -1747,13 +1747,13 @@
},
{
"category": "meta",
- "message": "Active pack [email protected]+6c7be06e is current (no successor declared)",
+ "message": "Active pack [email protected]+a50a67b9 is current (no successor declared)",
"name": "pack_upgrade_available",
"status": "ok"
},
{
"category": "meta",
- "message": "0 distinct typed values (pack declares 19)",
+ "message": "0 distinct typed values (pack declares 20)",
"name": "type_proliferation",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 153d996111..32a944315b 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -510,7 +510,7 @@
},
{
"category": "meta",
- "message": "Version 200 (latest: 200)",
+ "message": "Version 201 (latest: 201)",
"name": "schema_version",
"status": "ok"
},
@@ -1866,13 +1866,13 @@
},
{
"category": "meta",
- "message": "Active pack [email protected]+6c7be06e is current (no successor declared)",
+ "message": "Active pack [email protected]+a50a67b9 is current (no successor declared)",
"name": "pack_upgrade_available",
"status": "ok"
},
{
"category": "meta",
- "message": "0 distinct typed values (pack declares 19)",
+ "message": "0 distinct typed values (pack declares 20)",
"name": "type_proliferation",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 9ebd3e303b..e87d65a7a2 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -497,13 +497,13 @@
},
{
"category": "ops",
- "message": "RLS enabled on 103/103 public tables",
+ "message": "RLS enabled on 106/106 public tables",
"name": "rls",
"status": "ok"
},
{
"category": "meta",
- "message": "Version 200 (latest: 200)",
+ "message": "Version 201 (latest: 201)",
"name": "schema_version",
"status": "ok"
},
@@ -1856,13 +1856,13 @@
},
{
"category": "meta",
- "message": "Active pack [email protected]+6c7be06e is current (no successor declared)",
+ "message": "Active pack [email protected]+a50a67b9 is current (no successor declared)",
"name": "pack_upgrade_available",
"status": "ok"
},
{
"category": "meta",
- "message": "0 distinct typed values (pack declares 19)",
+ "message": "0 distinct typed values (pack declares 20)",
"name": "type_proliferation",
"status": "ok"
},
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index fb4aa5732c..35fdb13fec 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -3029,7 +3029,7 @@
{
"kind": "interface",
"members": [
- "auditSite?: \"addLinksBatch\" | \"addTimelineEntriesBatch\" | \"addTakesBatch\" | \"updateTakeEmbeddings\" | \"upsertChunks\" | \"extract.links_inc\" | \"extract.timeline_inc\" | \"extract.links_fs\" | \"extract.timeline_fs\" | \"extract.links_db\" | \"extract.timeline_db\" | \"extract.by_mention\" | \"extract.by_mention.rebuild\" | \"extract.stale\" | \"cycle.extract_atoms.provenance\" | \"cycle.synthesize_concepts.provenance\" | \"mcp.put_page.autolink\" | \"sync.import_file\" | \"reindex.markdown\" | \"reindex.multimodal\" | \"backfill.outer\" | \"minion-lock\" | undefined",
+ "auditSite?: \"addLinksBatch\" | \"addTimelineEntriesBatch\" | \"addTakesBatch\" | \"updateTakeEmbeddings\" | \"upsertChunks\" | \"extract.links_inc\" | \"extract.timeline_inc\" | \"extract.links_fs\" | \"extract.timeline_fs\" | \"extract.links_db\" | \"extract.timeline_db\" | \"extract.by_mention\" | \"extract.by_mention.rebuild\" | \"extract.mentions\" | \"extract.stale\" | \"cycle.extract_atoms.provenance\" | \"cycle.synthesize_concepts.provenance\" | \"mcp.put_page.autolink\" | \"sync.import_file\" | \"reindex.markdown\" | \"reindex.multimodal\" | \"backfill.outer\" | \"minion-lock\" | undefined",
"signal?: AbortSignal | undefined"
],
"name": "BatchOpts"
@@ -3985,7 +3985,7 @@
{
"kind": "interface",
"members": [
- "auditSite?: \"addLinksBatch\" | \"addTimelineEntriesBatch\" | \"addTakesBatch\" | \"updateTakeEmbeddings\" | \"upsertChunks\" | \"extract.links_inc\" | \"extract.timeline_inc\" | \"extract.links_fs\" | \"extract.timeline_fs\" | \"extract.links_db\" | \"extract.timeline_db\" | \"extract.by_mention\" | \"extract.by_mention.rebuild\" | \"extract.stale\" | \"cycle.extract_atoms.provenance\" | \"cycle.synthesize_concepts.provenance\" | \"mcp.put_page.autolink\" | \"sync.import_file\" | \"reindex.markdown\" | \"reindex.multimodal\" | \"backfill.outer\" | \"minion-lock\" | undefined",
+ "auditSite?: \"addLinksBatch\" | \"addTimelineEntriesBatch\" | \"addTakesBatch\" | \"updateTakeEmbeddings\" | \"upsertChunks\" | \"extract.links_inc\" | \"extract.timeline_inc\" | \"extract.links_fs\" | \"extract.timeline_fs\" | \"extract.links_db\" | \"extract.timeline_db\" | \"extract.by_mention\" | \"extract.by_mention.rebuild\" | \"extract.mentions\" | \"extract.stale\" | \"cycle.extract_atoms.provenance\" | \"cycle.synthesize_concepts.provenance\" | \"mcp.put_page.autolink\" | \"sync.import_file\" | \"reindex.markdown\" | \"reindex.multimodal\" | \"backfill.outer\" | \"minion-lock\" | undefined",
"delayMaxMs?: number | undefined",
"delayMs?: number | undefined",
"jitter?: JitterMode | undefined",
@@ -4028,7 +4028,7 @@
"kind": "function",
"name": "extractStaleFromDB",
"signature": [
- "(engine: BrainEngine, opts: { dryRun: boolean; jsonMode: boolean; quiet?: boolean; includeFrontmatter?: boolean; sourceIdFilter?: string; catchUp: boolean; timeBudgetMs?: number; }) => Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; }>"
+ "(engine: BrainEngine, opts: { dryRun: boolean; jsonMode: boolean; quiet?: boolean; includeFrontmatter?: boolean; sourceIdFilter?: string; catchUp: boolean; timeBudgetMs?: number; }) => Promise<{ linksCreated: number; timelineCreated: number; pagesProcessed: number; staleRemaining: number; skippedMissingTarget?: number; skippedCrossSource?: number; skippedAttendanceIncomplete?: number; skippedChanged?: number; mentions?: MentionPassResult; }>"
]
},
{
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 190c942fa0..70f1b94376 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": "entity_mention_index",
+ "sql": {
+ "length": 2442,
+ "sha256": "c76f74797f3bcc52158c7d8be80ab16bbbd2820d1732203aeaa796f4fec339b6"
+ },
+ "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/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 40df5ecbfd..a9b50141b7 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -99,6 +99,11 @@
"mcp_spend_reservations.mcp_spend_reservations_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"mcp_spend_reservations.mcp_spend_reservations_pkey": "p PRIMARY KEY (reservation_id)",
"mcp_spend_reservations.mcp_spend_reservations_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'settled'::text, 'expired'::text])))",
+ "mention_gazetteer_entries.mention_gazetteer_entries_pkey": "p PRIMARY KEY (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_gazetteer_entries.mention_gazetteer_entries_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_pkey": "p PRIMARY KEY (source_id)",
+ "mention_index_status.mention_index_status_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "mention_index_status.mention_index_status_state_check": "c CHECK ((state = ANY (ARRAY['complete'::text, 'pending'::text, 'disabled'::text, 'failed'::text])))",
"migration_impact_log.migration_impact_log_job_id_fkey": "f FOREIGN KEY (job_id) REFERENCES minion_jobs(id) ON DELETE SET NULL",
"migration_impact_log.migration_impact_log_pkey": "p PRIMARY KEY (id)",
"minion_attachments.chk_attachment_size": "c CHECK ((size_bytes >= 0))",
@@ -147,11 +152,15 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_aliases.page_aliases_origin_check": "c CHECK ((origin = ANY (ARRAY['frontmatter'::text, 'declared'::text, 'subject'::text])))",
+ "page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
- "page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
+ "page_mention_state.page_mention_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_mention_state.page_mention_state_pkey": "p PRIMARY KEY (page_id)",
+ "page_mention_state.page_mention_state_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
"page_projection_jobs.page_projection_jobs_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",
"page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
@@ -456,6 +465,12 @@
"mcp_spend_reservations": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "mention_gazetteer_entries": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
+ "mention_index_status": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"migration_impact_log": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -507,6 +522,9 @@
"page_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_mention_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_projection_jobs": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -834,6 +852,8 @@
"mcp_request_log_pkey": "CREATE UNIQUE INDEX mcp_request_log_pkey ON public.mcp_request_log USING btree (id)",
"mcp_spend_log_pkey": "CREATE UNIQUE INDEX mcp_spend_log_pkey ON public.mcp_spend_log USING btree (id)",
"mcp_spend_reservations_pkey": "CREATE UNIQUE INDEX mcp_spend_reservations_pkey ON public.mcp_spend_reservations USING btree (reservation_id)",
+ "mention_gazetteer_entries_pkey": "CREATE UNIQUE INDEX mention_gazetteer_entries_pkey ON public.mention_gazetteer_entries USING btree (source_id, name_norm, target_slug, case_sensitive)",
+ "mention_index_status_pkey": "CREATE UNIQUE INDEX mention_index_status_pkey ON public.mention_index_status USING btree (source_id)",
"migration_impact_log_attribution_idx": "CREATE INDEX migration_impact_log_attribution_idx ON public.migration_impact_log USING btree (job_id, source_id) WHERE (job_id IS NOT NULL)",
"migration_impact_log_pkey": "CREATE UNIQUE INDEX migration_impact_log_pkey ON public.migration_impact_log USING btree (id)",
"migration_impact_log_remediation_idx": "CREATE INDEX migration_impact_log_remediation_idx ON public.migration_impact_log USING btree (remediation_id, applied_at DESC)",
@@ -865,10 +885,12 @@
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
"page_aliases_lookup_idx": "CREATE INDEX page_aliases_lookup_idx ON public.page_aliases USING btree (source_id, alias_norm)",
+ "page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
- "page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
+ "page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
+ "page_mention_state_source_idx": "CREATE INDEX page_mention_state_source_idx ON public.page_mention_state USING btree (source_id, mention_version)",
"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)",
"page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)",
"page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)",
@@ -1737,6 +1759,29 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "mention_gazetteer_entries": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 name_norm text/text NOT NULL",
+ "3 target_slug text/text NOT NULL",
+ "4 case_sensitive boolean/bool NOT NULL DEFAULT false"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
+ "mention_index_status": {
+ "columns": [
+ "1 source_id text/text NOT NULL",
+ "2 generation bigint/int8 NOT NULL DEFAULT 0",
+ "3 state text/text NOT NULL DEFAULT 'pending'::text",
+ "4 pending integer/int4 NOT NULL DEFAULT 0",
+ "5 counted_at timestamp with time zone/timestamptz NULL",
+ "6 last_pass_at timestamp with time zone/timestamptz NULL",
+ "7 policy_fingerprint text/text NULL",
+ "8 error text/text NULL",
+ "9 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"migration_impact_log": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('migration_impact_log_id_seq'::regclass)",
@@ -1998,7 +2043,10 @@
"2 source_id text/text NOT NULL",
"3 alias_norm text/text NOT NULL",
"4 slug text/text NOT NULL",
- "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ "5 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "6 origin text/text NOT NULL DEFAULT 'frontmatter'::text",
+ "7 case_sensitive boolean/bool NOT NULL DEFAULT false",
+ "8 alias_text text/text NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2009,6 +2057,20 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_mention_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 source_id text/text NOT NULL",
+ "3 mention_revision uuid/uuid NULL",
+ "4 mention_version integer/int4 NULL",
+ "5 mention_generation bigint/int8 NULL",
+ "6 mentions_scanned_at timestamp with time zone/timestamptz NULL",
+ "7 alias_revision uuid/uuid NULL",
+ "8 alias_version integer/int4 NULL",
+ "9 aliases_refreshed_at timestamp with time zone/timestamptz NULL"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_projection_jobs": {
"columns": [
"1 source_incarnation uuid/uuid NOT NULL",
diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.json
index dd5c34accb..5fa6b12285 100644
--- a/test/fixtures/goldens/sql-text/chunks.json
+++ b/test/fixtures/goldens/sql-text/chunks.json
@@ -116,8 +116,8 @@
"array<string>",
"number"
],
- "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND COALESCE(p.chunker_version, 0) >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source FROM chunk_rows c",
- "textSha256": "b9147ddc763f7af2c7b61c6a15c8bcd8d93ac15aa3a33f4343aeb095a3b444d4"
+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND COALESCE(p.chunker_version, 0) >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source FROM chunk_rows c",
+ "textSha256": "f73a20ffe2b70678fb2dd7859d24a65e6970601bb285adadf62d16191a1bac17"
}
]
},
@@ -152,8 +152,8 @@
"string",
"string"
],
- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND COALESCE(p.chunker_version, 0) >= 4 ORDER BY cc.chunk_index",
- "textSha256": "539b974c0068b20926720bde8eac3c79013c52b1d6ac12cc7ddcc443ea7b21a8"
+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND COALESCE(p.chunker_version, 0) >= 4 ORDER BY cc.chunk_index",
+ "textSha256": "dc9350aa261e98be653e74e789926a346c40b95724e3b1fda4b5820405190f5c"
}
],
"includeEmbedding": [
diff --git a/test/fixtures/goldens/sql-text/facts.json b/test/fixtures/goldens/sql-text/facts.json
index 894124b01e..6a20acea68 100644
--- a/test/fixtures/goldens/sql-text/facts.json
+++ b/test/fixtures/goldens/sql-text/facts.json
@@ -151,8 +151,8 @@
"number",
"array<string>"
],
- "sql": "WITH cur AS ( SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id FROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug))))))) ) SELECT entity_slug, dimension, json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values FROM cur GROUP BY entity_slug, dimension HAVING count(DISTINCT value) >= 2 AND count(DISTINCT source) >= 2 ORDER BY entity_slug, dimension",
- "textSha256": "fc3d0ef58a041ac29dbe50454b13a20ac8bb139a970c0369bab3c38e44a10c34"
+ "sql": "WITH cur AS ( SELECT entity_slug, dimension, value, source_markdown_slug AS source, confidence, id AS fact_id FROM facts WHERE dimension IS NOT NULL AND expired_at IS NULL AND valid_until IS NULL AND (dim_status IS NULL OR dim_status = 'active') AND confidence >= $1 AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)))) ) SELECT entity_slug, dimension, json_agg(json_build_object('value', value, 'source', source, 'confidence', confidence, 'fact_id', fact_id)) AS values FROM cur GROUP BY entity_slug, dimension HAVING count(DISTINCT value) >= 2 AND count(DISTINCT source) >= 2 ORDER BY entity_slug, dimension",
+ "textSha256": "e374b10a136c877ebba2bf7d69d604100479ba634a61435465fedd4d01f6108c"
}
]
},
@@ -245,8 +245,8 @@
"number",
"boolean"
],
- "sql": "SELECT DISTINCT ON (dimension) dimension, value, confidence, source_markdown_slug AS source, valid_from, valid_until AS valid_to, COALESCE(dim_status, 'active') AS status, id AS fact_id FROM facts WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug))))))) AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE($3::timestamptz, now()) AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE($4::timestamptz, now()) AND confidence >= $5 AND ($6::boolean OR dim_status IS NULL OR dim_status = 'active') ORDER BY dimension, valid_from DESC NULLS LAST, confidence DESC, id DESC",
- "textSha256": "7370291524eec99aef5a01175eddc82b6fb6c3d6c7196684fa208102c8db604c"
+ "sql": "SELECT DISTINCT ON (dimension) dimension, value, confidence, source_markdown_slug AS source, valid_from, valid_until AS valid_to, COALESCE(dim_status, 'active') AS status, id AS fact_id FROM facts WHERE entity_slug = $1 AND dimension IS NOT NULL AND expired_at IS NULL AND source_id = ANY($2) AND NOT EXISTS (SELECT 1 FROM pages pp WHERE pp.source_id = facts.source_id AND pp.slug = facts.source_markdown_slug AND NOT ((COALESCE(pp.frontmatter->>'visibility', CASE WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pp.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pp.source_id AND derived_origin.slug = pp.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pp.type = 'atom' OR (pp.type = 'concept' AND pp.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pp.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pp.type = 'event' AND pp.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pp.source_id AND chronicle_origin.slug = pp.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pp.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pp.frontmatter->'derived_from') = 'array' THEN pp.frontmatter->'derived_from' ELSE jsonb_build_array(pp.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)))) AND COALESCE(valid_from, '-infinity'::timestamptz) <= COALESCE($3::timestamptz, now()) AND COALESCE(valid_until, 'infinity'::timestamptz) > COALESCE($4::timestamptz, now()) AND confidence >= $5 AND ($6::boolean OR dim_status IS NULL OR dim_status = 'active') ORDER BY dimension, valid_from DESC NULLS LAST, confidence DESC, id DESC",
+ "textSha256": "8514ececcd4415d4346168e82b6345038474208583e5a5266e6ee7c95031835a"
}
]
},
diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.json
index f15cd4c671..b887a1dc5f 100644
--- a/test/fixtures/goldens/sql-text/links.json
+++ b/test/fixtures/goldens/sql-text/links.json
@@ -68,8 +68,8 @@
"params": [
"array<string>"
],
- "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined, p.source_id FROM pages p WHERE p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.source_id = ANY($1::text[]) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL AND (COALESCE(src.frontmatter->>'visibility', CASE WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN src.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = src.source_id AND derived_origin.slug = src.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = src.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN src.type = 'event' AND src.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = src.source_id AND chronicle_origin.slug = src.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(src.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = src.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(src.frontmatter->'derived_from') = 'array' THEN src.frontmatter->'derived_from' ELSE jsonb_build_array(src.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL AND (COALESCE(tgt.frontmatter->>'visibility', CASE WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN tgt.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = tgt.source_id AND derived_origin.slug = tgt.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = tgt.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN tgt.type = 'event' AND tgt.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = tgt.source_id AND chronicle_origin.slug = tgt.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(tgt.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = tgt.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(tgt.frontmatter->'derived_from') = 'array' THEN tgt.frontmatter->'derived_from' ELSE jsonb_build_array(tgt.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ) ORDER BY p.slug",
- "textSha256": "bec416d8435df57a13d416bf9b48931e7d74c9b6801a60509b8dcb43b18138db"
+ "sql": "SELECT p.slug, COALESCE(p.title, p.slug) AS title, p.frontmatter->>'domain' AS domain, p.type, (NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')) AS quarantined, p.source_id FROM pages p WHERE p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.source_id = ANY($1::text[]) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages src ON src.id = l.from_page_id WHERE l.to_page_id = p.id AND src.deleted_at IS NULL AND (COALESCE(src.frontmatter->>'visibility', CASE WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN src.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = src.source_id AND derived_origin.slug = src.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (src.type = 'atom' OR (src.type = 'concept' AND src.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = src.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN src.type = 'event' AND src.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = src.source_id AND chronicle_origin.slug = src.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(src.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = src.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(src.frontmatter->'derived_from') = 'array' THEN src.frontmatter->'derived_from' ELSE jsonb_build_array(src.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ) AND NOT EXISTS ( SELECT 1 FROM links l JOIN pages tgt ON tgt.id = l.to_page_id WHERE l.from_page_id = p.id AND tgt.deleted_at IS NULL AND (COALESCE(tgt.frontmatter->>'visibility', CASE WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN tgt.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = tgt.source_id AND derived_origin.slug = tgt.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (tgt.type = 'atom' OR (tgt.type = 'concept' AND tgt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = tgt.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN tgt.type = 'event' AND tgt.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = tgt.source_id AND chronicle_origin.slug = tgt.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(tgt.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = tgt.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(tgt.frontmatter->'derived_from') = 'array' THEN tgt.frontmatter->'derived_from' ELSE jsonb_build_array(tgt.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ) ORDER BY p.slug",
+ "textSha256": "4e95aeb66c2768f96d9b6c96b91f6146acff64175c3f4ed2ef98a8d83e8bb034"
}
]
},
@@ -90,8 +90,8 @@
"params": [
"string"
],
- "sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE t.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL AND (COALESCE(f.frontmatter->>'visibility', CASE WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN f.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = f.source_id AND derived_origin.slug = f.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = f.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN f.type = 'event' AND f.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = f.source_id AND chronicle_origin.slug = f.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(f.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = f.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') = 'array' THEN f.frontmatter->'derived_from' ELSE jsonb_build_array(f.frontmatter->'derived_from') END) AS declared(slug))))) AND (COALESCE(t.frontmatter->>'visibility', CASE WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN t.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = t.source_id AND derived_origin.slug = t.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = t.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN t.type = 'event' AND t.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = t.source_id AND chronicle_origin.slug = t.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(t.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = t.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') = 'array' THEN t.frontmatter->'derived_from' ELSE jsonb_build_array(t.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY l.id",
- "textSha256": "b2675f9fab43452f1bf53a39bfd4e4842f17657497467d24b8e7e29a93d3d1f1"
+ "sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE t.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL AND (COALESCE(f.frontmatter->>'visibility', CASE WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN f.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = f.source_id AND derived_origin.slug = f.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = f.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN f.type = 'event' AND f.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = f.source_id AND chronicle_origin.slug = f.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = f.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') = 'array' THEN f.frontmatter->'derived_from' ELSE jsonb_build_array(f.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (COALESCE(t.frontmatter->>'visibility', CASE WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN t.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = t.source_id AND derived_origin.slug = t.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = t.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN t.type = 'event' AND t.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = t.source_id AND chronicle_origin.slug = t.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = t.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') = 'array' THEN t.frontmatter->'derived_from' ELSE jsonb_build_array(t.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ORDER BY l.id",
+ "textSha256": "688109a8429d3ce7c4dc1a623ae8934354ceb1b509d0b24ea293f701b6cc5bc3"
}
],
"sourceId": [
@@ -136,8 +136,8 @@
"params": [
"string"
],
- "sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE f.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL AND (COALESCE(f.frontmatter->>'visibility', CASE WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN f.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = f.source_id AND derived_origin.slug = f.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = f.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN f.type = 'event' AND f.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = f.source_id AND chronicle_origin.slug = f.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(f.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = f.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') = 'array' THEN f.frontmatter->'derived_from' ELSE jsonb_build_array(f.frontmatter->'derived_from') END) AS declared(slug))))) AND (COALESCE(t.frontmatter->>'visibility', CASE WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN t.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = t.source_id AND derived_origin.slug = t.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = t.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN t.type = 'event' AND t.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = t.source_id AND chronicle_origin.slug = t.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(t.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = t.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') = 'array' THEN t.frontmatter->'derived_from' ELSE jsonb_build_array(t.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY l.id",
- "textSha256": "c636b80ef601623a19a7fa61d485a30ae7a2b4e3fbbaa70889e2bd303dd40da5"
+ "sql": "SELECT f.slug as from_slug, f.source_id as from_source_id, t.slug as to_slug, t.source_id as to_source_id, l.link_type, l.context, l.link_source, o.slug as origin_slug, o.source_id as origin_source_id, l.origin_field FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id LEFT JOIN pages o ON o.id = l.origin_page_id WHERE f.slug = $1 AND f.deleted_at IS NULL AND t.deleted_at IS NULL AND (COALESCE(f.frontmatter->>'visibility', CASE WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN f.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = f.source_id AND derived_origin.slug = f.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (f.type = 'atom' OR (f.type = 'concept' AND f.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = f.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN f.type = 'event' AND f.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = f.source_id AND chronicle_origin.slug = f.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = f.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(f.frontmatter->'derived_from') = 'array' THEN f.frontmatter->'derived_from' ELSE jsonb_build_array(f.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (COALESCE(t.frontmatter->>'visibility', CASE WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN t.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = t.source_id AND derived_origin.slug = t.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (t.type = 'atom' OR (t.type = 'concept' AND t.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = t.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN t.type = 'event' AND t.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = t.source_id AND chronicle_origin.slug = t.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = t.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(t.frontmatter->'derived_from') = 'array' THEN t.frontmatter->'derived_from' ELSE jsonb_build_array(t.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ORDER BY l.id",
+ "textSha256": "2fc697877a0bedba4efdb4c738679d789bc71c9845fff1c2a40341373fa4ff73"
}
],
"sourceId": [
@@ -381,8 +381,8 @@
"number",
"number"
],
- "sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $2 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL AND (COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p2.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p2.source_id AND derived_origin.slug = p2.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p2.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p2.type = 'event' AND p2.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p2.source_id AND chronicle_origin.slug = p2.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p2.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') = 'array' THEN p2.frontmatter->'derived_from' ELSE jsonb_build_array(p2.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL AND (COALESCE(p3.frontmatter->>'visibility', CASE WHEN (p3.type = 'atom' OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p3.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p3.source_id AND derived_origin.slug = p3.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p3.type = 'atom' OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p3.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p3.type = 'event' AND p3.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p3.source_id AND chronicle_origin.slug = p3.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p3.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p3.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p3.frontmatter->'derived_from') = 'array' THEN p3.frontmatter->'derived_from' ELSE jsonb_build_array(p3.frontmatter->'derived_from') END) AS declared(slug))))) AND (l2.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l2.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $3) capped) g ORDER BY g.depth, g.slug, g.source_id",
- "textSha256": "4e31963ee44b7309d252388f3cb9042ca69c6e06208e2c81c54265791edd8ffb"
+ "sql": "WITH RECURSIVE graph AS ( SELECT p.id, p.slug, p.source_id, p.title, p.type, 0 as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) UNION ALL SELECT p2.id, p2.slug, p2.source_id, p2.title, p2.type, g.depth + 1, g.visited || p2.id FROM graph g JOIN links l ON l.from_page_id = g.id JOIN pages p2 ON p2.id = l.to_page_id WHERE g.depth < $2 AND NOT (p2.id = ANY(g.visited)) AND p2.deleted_at IS NULL AND (COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p2.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p2.source_id AND derived_origin.slug = p2.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p2.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p2.type = 'event' AND p2.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p2.source_id AND chronicle_origin.slug = p2.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p2.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') = 'array' THEN p2.frontmatter->'derived_from' ELSE jsonb_build_array(p2.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ) SELECT DISTINCT g.slug, g.source_id, g.title, g.type, g.depth, coalesce( -- jsonb_agg(DISTINCT ...) collapses duplicate (to_slug, link_type) -- edges that originate from different provenance (markdown body -- vs frontmatter vs auto-extracted). The underlying links table -- preserves every row with its origin_page_id / link_source — -- the dedup is presentation-only for the legacy traverseGraph -- aggregation. traversePaths has its own in-memory dedup at a -- different layer. See plan Bug 6/10. (SELECT jsonb_agg(DISTINCT jsonb_build_object('to_slug', p3.slug, 'link_type', l2.link_type)) FROM links l2 JOIN pages p3 ON p3.id = l2.to_page_id WHERE l2.from_page_id = g.id AND p3.deleted_at IS NULL AND (COALESCE(p3.frontmatter->>'visibility', CASE WHEN (p3.type = 'atom' OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p3.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p3.source_id AND derived_origin.slug = p3.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p3.type = 'atom' OR (p3.type = 'concept' AND p3.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p3.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p3.type = 'event' AND p3.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p3.source_id AND chronicle_origin.slug = p3.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p3.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p3.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p3.frontmatter->'derived_from') = 'array' THEN p3.frontmatter->'derived_from' ELSE jsonb_build_array(p3.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l2.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l2.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ), '[]'::jsonb ) as links FROM (SELECT DISTINCT id, slug, source_id, title, type, depth FROM (SELECT id, slug, source_id, title, type, depth FROM graph LIMIT $3) capped) g ORDER BY g.depth, g.slug, g.source_id",
+ "textSha256": "4dfdbecba7fef1d61aadb092d992b8fe917bc7a311a0ae662cc4a72d16f35eac"
}
],
"frontierCap": [
@@ -489,8 +489,8 @@
"array<string>",
"number"
],
- "sql": "WITH RECURSIVE walk AS ( SELECT p.id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.source_id = ANY($2::text[]) UNION ALL SELECT p2.id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END WHERE w.depth + 1 < $3 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND (COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p2.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p2.source_id AND derived_origin.slug = p2.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p2.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p2.type = 'event' AND p2.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p2.source_id AND chronicle_origin.slug = p2.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p2.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') = 'array' THEN p2.frontmatter->'derived_from' ELSE jsonb_build_array(p2.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) AND ($4 OR l.link_type = $5) AND p2.source_id = ANY($6::text[]) ), capped AS (SELECT id, depth FROM walk LIMIT $7), nodes AS (SELECT DISTINCT id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $8 AS walk_truncated, pf.id as from_id, pf.slug as from_slug, pf.source_id as from_source_id, pt.id as to_id, pt.slug as to_slug, pt.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages pf ON pf.id = l.from_page_id JOIN pages pt ON pt.id = l.to_page_id WHERE w.depth < $9 AND pf.deleted_at IS NULL AND (COALESCE(pf.frontmatter->>'visibility', CASE WHEN (pf.type = 'atom' OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pf.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pf.source_id AND derived_origin.slug = pf.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pf.type = 'atom' OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pf.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pf.type = 'event' AND pf.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pf.source_id AND chronicle_origin.slug = pf.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pf.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pf.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pf.frontmatter->'derived_from') = 'array' THEN pf.frontmatter->'derived_from' ELSE jsonb_build_array(pf.frontmatter->'derived_from') END) AS declared(slug))))) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))))) )) AND pt.deleted_at IS NULL AND (COALESCE(pt.frontmatter->>'visibility', CASE WHEN (pt.type = 'atom' OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pt.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pt.source_id AND derived_origin.slug = pt.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pt.type = 'atom' OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pt.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pt.type = 'event' AND pt.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pt.source_id AND chronicle_origin.slug = pt.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pt.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pt.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pt.frontmatter->'derived_from') = 'array' THEN pt.frontmatter->'derived_from' ELSE jsonb_build_array(pt.frontmatter->'derived_from') END) AS declared(slug))))) AND ($10 OR l.link_type = $11) AND pf.source_id = ANY($12::text[]) AND pt.source_id = ANY($13::text[]) ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $14",
- "textSha256": "a64eb869b6d5b1c54a74bf9330f6bde2921a916361888af77ab05f9ee3fb34de"
+ "sql": "WITH RECURSIVE walk AS ( SELECT p.id, 0::int as depth, ARRAY[p.id] as visited FROM pages p WHERE p.slug = $1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.source_id = ANY($2::text[]) UNION ALL SELECT p2.id, w.depth + 1, w.visited || p2.id FROM walk w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages p2 ON p2.id = CASE WHEN l.from_page_id = w.id THEN l.to_page_id ELSE l.from_page_id END WHERE w.depth + 1 < $3 AND NOT (p2.id = ANY(w.visited)) AND p2.deleted_at IS NULL AND (COALESCE(p2.frontmatter->>'visibility', CASE WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p2.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p2.source_id AND derived_origin.slug = p2.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p2.type = 'atom' OR (p2.type = 'concept' AND p2.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p2.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p2.type = 'event' AND p2.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p2.source_id AND chronicle_origin.slug = p2.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p2.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p2.frontmatter->'derived_from') = 'array' THEN p2.frontmatter->'derived_from' ELSE jsonb_build_array(p2.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) AND ($4 OR l.link_type = $5) AND p2.source_id = ANY($6::text[]) ), capped AS (SELECT id, depth FROM walk LIMIT $7), nodes AS (SELECT DISTINCT id, depth FROM capped) SELECT (SELECT count(*) FROM capped) > $8 AS walk_truncated, pf.id as from_id, pf.slug as from_slug, pf.source_id as from_source_id, pt.id as to_id, pt.slug as to_slug, pt.source_id as to_source_id, l.link_type, l.context, w.depth + 1 as depth FROM nodes w JOIN links l ON (l.from_page_id = w.id OR l.to_page_id = w.id) JOIN pages pf ON pf.id = l.from_page_id JOIN pages pt ON pt.id = l.to_page_id WHERE w.depth < $9 AND pf.deleted_at IS NULL AND (COALESCE(pf.frontmatter->>'visibility', CASE WHEN (pf.type = 'atom' OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pf.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pf.source_id AND derived_origin.slug = pf.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pf.type = 'atom' OR (pf.type = 'concept' AND pf.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pf.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pf.type = 'event' AND pf.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pf.source_id AND chronicle_origin.slug = pf.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pf.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pf.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pf.frontmatter->'derived_from') = 'array' THEN pf.frontmatter->'derived_from' ELSE jsonb_build_array(pf.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (l.origin_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages origin_private WHERE origin_private.id = l.origin_page_id AND (COALESCE(origin_private.frontmatter->>'visibility', CASE WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN origin_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = origin_private.source_id AND derived_origin.slug = origin_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (origin_private.type = 'atom' OR (origin_private.type = 'concept' AND origin_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = origin_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN origin_private.type = 'event' AND origin_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = origin_private.source_id AND chronicle_origin.slug = origin_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = origin_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(origin_private.frontmatter->'derived_from') = 'array' THEN origin_private.frontmatter->'derived_from' ELSE jsonb_build_array(origin_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) AND pt.deleted_at IS NULL AND (COALESCE(pt.frontmatter->>'visibility', CASE WHEN (pt.type = 'atom' OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pt.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pt.source_id AND derived_origin.slug = pt.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pt.type = 'atom' OR (pt.type = 'concept' AND pt.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pt.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pt.type = 'event' AND pt.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pt.source_id AND chronicle_origin.slug = pt.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pt.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pt.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pt.frontmatter->'derived_from') = 'array' THEN pt.frontmatter->'derived_from' ELSE jsonb_build_array(pt.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND ($10 OR l.link_type = $11) AND pf.source_id = ANY($12::text[]) AND pt.source_id = ANY($13::text[]) ORDER BY depth, from_slug, to_slug, from_source_id, to_source_id LIMIT $14",
+ "textSha256": "523e4e9554dc74ebdb112d53fdea7501722c395131fdcdafd635819744b737f0"
}
],
"default": [
diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.json
index a53dbc235b..c72213bbc4 100644
--- a/test/fixtures/goldens/sql-text/pages.json
+++ b/test/fixtures/goldens/sql-text/pages.json
@@ -308,8 +308,8 @@
"params": [
"string"
],
- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND COALESCE(pv.frontmatter->>'visibility', CASE WHEN (pv.type = 'atom' OR (pv.type = 'concept' AND pv.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' ORDER BY pv.snapshot_at DESC",
- "textSha256": "b0496cf78e8a8d641c60cd962799327a7ab3bf2f6a64535d9c2d01f68f45880d"
+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND COALESCE(pv.frontmatter->>'visibility', CASE WHEN (pv.type = 'atom' OR (pv.type = 'concept' AND pv.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' ORDER BY pv.snapshot_at DESC",
+ "textSha256": "c2ec5cf6dbd26923230987037168c8e5f0dd67035a401b5bb512788256a069f2"
}
],
"sourceId": [
@@ -444,8 +444,8 @@
"number",
"number"
],
- "sql": "SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages p WHERE 1=1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) ORDER BY p.updated_at DESC LIMIT $1 OFFSET $2",
- "textSha256": "44a699457de18d5808daa9271eef8d914fd1a1c2bcad3d7803d6577ce2a26e68"
+ "sql": "SELECT p.*, to_char(p.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages p WHERE 1=1 AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ORDER BY p.updated_at DESC LIMIT $1 OFFSET $2",
+ "textSha256": "3964e3fe1c6d286cf5244844a321835cb1e9fbc5d94da1c329fb3a769875004f"
}
],
"includeDeleted": [
@@ -1041,8 +1041,8 @@
"array<string>",
"array<string>"
],
- "sql": "SELECT canonical_slug, source_id FROM slug_aliases WHERE alias_slug = $1 AND source_id = ANY($2::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.slug = slug_aliases.canonical_slug AND p.source_id = slug_aliases.source_id AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))))) ORDER BY array_position($3::text[], source_id), id",
- "textSha256": "eb759b8f0bc2d2d89ede405524774e3a059a9a2f91c446536e920b89a85dcb96"
+ "sql": "SELECT canonical_slug, source_id FROM slug_aliases WHERE alias_slug = $1 AND source_id = ANY($2::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.slug = slug_aliases.canonical_slug AND p.source_id = slug_aliases.source_id AND p.deleted_at IS NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END))) ORDER BY array_position($3::text[], source_id), id",
+ "textSha256": "60532f9ead5c657ecbd0c730e1d827bf346c4edeb72433df9be0586b33a1ee8b"
}
]
},
@@ -1063,8 +1063,8 @@
"params": [
"string"
],
- "sql": "SELECT slug FROM pages WHERE slug = $1 AND deleted_at IS NULL AND (COALESCE(pages.frontmatter->>'visibility', CASE WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pages.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pages.source_id AND derived_origin.slug = pages.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pages.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pages.type = 'event' AND pages.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pages.source_id AND chronicle_origin.slug = pages.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pages.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pages.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') = 'array' THEN pages.frontmatter->'derived_from' ELSE jsonb_build_array(pages.frontmatter->'derived_from') END) AS declared(slug)))))",
- "textSha256": "03df71ab1e8f6626302684377c807924b5a38f6e9c4c283bce2d9021ea459f7e"
+ "sql": "SELECT slug FROM pages WHERE slug = $1 AND deleted_at IS NULL AND (COALESCE(pages.frontmatter->>'visibility', CASE WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pages.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pages.source_id AND derived_origin.slug = pages.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pages.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pages.type = 'event' AND pages.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pages.source_id AND chronicle_origin.slug = pages.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pages.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') = 'array' THEN pages.frontmatter->'derived_from' ELSE jsonb_build_array(pages.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END))",
+ "textSha256": "a6f6bbf1eafea9e24b35ebd13eae7c051f8e15998958ca3c015b943f55f263d0"
},
{
"lane": "pool",
@@ -1073,8 +1073,8 @@
"string",
"string"
],
- "sql": "SELECT slug, similarity(title, $1) AS sim FROM pages WHERE deleted_at IS NULL AND (title % $2 OR slug ILIKE $3) AND (COALESCE(pages.frontmatter->>'visibility', CASE WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pages.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pages.source_id AND derived_origin.slug = pages.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pages.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pages.type = 'event' AND pages.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pages.source_id AND chronicle_origin.slug = pages.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pages.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pages.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') = 'array' THEN pages.frontmatter->'derived_from' ELSE jsonb_build_array(pages.frontmatter->'derived_from') END) AS declared(slug))))) ORDER BY sim DESC LIMIT 5",
- "textSha256": "2f10ffc8782f9817b68a17db4761309e9d7f55888eaccef9291857e8b5a58b22"
+ "sql": "SELECT slug, similarity(title, $1) AS sim FROM pages WHERE deleted_at IS NULL AND (title % $2 OR slug ILIKE $3) AND (COALESCE(pages.frontmatter->>'visibility', CASE WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pages.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pages.source_id AND derived_origin.slug = pages.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pages.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pages.type = 'event' AND pages.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pages.source_id AND chronicle_origin.slug = pages.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pages.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') = 'array' THEN pages.frontmatter->'derived_from' ELSE jsonb_build_array(pages.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ORDER BY sim DESC LIMIT 5",
+ "textSha256": "12b827453ca02b806a918c832c508c976cdcc241db4cc354da7f7f29e5389a13"
}
],
"fuzzy": [
@@ -1250,8 +1250,8 @@
"string",
"string"
],
- "sql": "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2",
- "textSha256": "6da211c8cdf3da0076f9251fb24d538ea62e28960c13455e5515dcf58b372937"
+ "sql": "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 AND origin='frontmatter'",
+ "textSha256": "4e08a734d456bfca77faf68b2ba5e113ba5234cba27a0991b451016d66d17f86"
},
{
"lane": "tx",
@@ -1314,8 +1314,8 @@
"string",
"string"
],
- "sql": "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2",
- "textSha256": "6da211c8cdf3da0076f9251fb24d538ea62e28960c13455e5515dcf58b372937"
+ "sql": "DELETE FROM page_aliases WHERE source_id=$1 AND slug=$2 AND origin='frontmatter'",
+ "textSha256": "4e08a734d456bfca77faf68b2ba5e113ba5234cba27a0991b451016d66d17f86"
},
{
"event": "commit",
@@ -1507,8 +1507,8 @@
"string",
"string"
],
- "sql": "DELETE FROM page_aliases a WHERE a.source_id = $1 AND a.slug = $2 AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $3 AND o.slug = $4 AND o.alias_norm = a.alias_norm)",
- "textSha256": "c534f6c79181120132daf04f1bfa6d7b1a98611b3b1db953da697789b1758bbf"
+ "sql": "DELETE FROM page_aliases a WHERE a.source_id = $1 AND a.slug = $2 AND EXISTS (SELECT 1 FROM page_aliases o WHERE o.source_id = $3 AND o.slug = $4 AND o.alias_norm = a.alias_norm AND o.origin = a.origin)",
+ "textSha256": "584810386449ba564be21a2affc996de1fac7f8fb089faa941936b9827a1b85d"
},
{
"event": "savepoint-release",
diff --git a/test/fixtures/goldens/sql-text/salience.json b/test/fixtures/goldens/sql-text/salience.json
index 3fa5988ea2..b07680ab24 100644
--- a/test/fixtures/goldens/sql-text/salience.json
+++ b/test/fixtures/goldens/sql-text/salience.json
@@ -82,8 +82,8 @@
"string",
"string"
],
- "sql": "WITH days AS ( SELECT day::date FROM generate_series( $1::date, $2::date - 1, '1 day'::interval ) AS day ), cohort_keys AS ( SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_id WHERE p.updated_at >= $3::timestamptz AND p.updated_at < $4::timestamptz AND p.source_id = $5 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) ), touched AS ( SELECT t.tag, date_trunc('day', p.updated_at)::date AS day, COUNT(DISTINCT p.id) AS cnt FROM tags t JOIN pages p ON p.id = t.page_id WHERE p.updated_at >= $6::timestamptz AND p.updated_at < $7::timestamptz AND p.source_id = $8 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1, 2 ) SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count FROM cohort_keys cd CROSS JOIN days d LEFT JOIN touched t ON t.tag = cd.tag AND t.day = d.day",
- "textSha256": "973e4b4f374730a26fc8c43f1814602690a3d09779da52158b61f0b6667a3b15"
+ "sql": "WITH days AS ( SELECT day::date FROM generate_series( $1::date, $2::date - 1, '1 day'::interval ) AS day ), cohort_keys AS ( SELECT DISTINCT t.tag FROM tags t JOIN pages p ON p.id = t.page_id WHERE p.updated_at >= $3::timestamptz AND p.updated_at < $4::timestamptz AND p.source_id = $5 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) ), touched AS ( SELECT t.tag, date_trunc('day', p.updated_at)::date AS day, COUNT(DISTINCT p.id) AS cnt FROM tags t JOIN pages p ON p.id = t.page_id WHERE p.updated_at >= $6::timestamptz AND p.updated_at < $7::timestamptz AND p.source_id = $8 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1, 2 ) SELECT cd.tag AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count FROM cohort_keys cd CROSS JOIN days d LEFT JOIN touched t ON t.tag = cd.tag AND t.day = d.day",
+ "textSha256": "e9f1c5f3d54f19b24454767600639ab7bd645b3da51c2e4f62f92697e57371c3"
},
{
"lane": "pool",
@@ -97,8 +97,8 @@
"string",
"string"
],
- "sql": "WITH days AS ( SELECT day::date FROM generate_series( $1::date, $2::date - 1, '1 day'::interval ) AS day ), cohort_keys AS ( SELECT DISTINCT p.type FROM pages p WHERE p.updated_at >= $3::timestamptz AND p.updated_at < $4::timestamptz AND p.source_id = $5 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) ), touched AS ( SELECT p.type, date_trunc('day', p.updated_at)::date AS day, COUNT(DISTINCT p.id) AS cnt FROM pages p WHERE p.updated_at >= $6::timestamptz AND p.updated_at < $7::timestamptz AND p.source_id = $8 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1, 2 ) SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count FROM cohort_keys cd CROSS JOIN days d LEFT JOIN touched t ON t.type = cd.type AND t.day = d.day",
- "textSha256": "30d2b40f1799df58fb3d200347e11479aedb74b7dad5060851da5bcd9ddd147b"
+ "sql": "WITH days AS ( SELECT day::date FROM generate_series( $1::date, $2::date - 1, '1 day'::interval ) AS day ), cohort_keys AS ( SELECT DISTINCT p.type FROM pages p WHERE p.updated_at >= $3::timestamptz AND p.updated_at < $4::timestamptz AND p.source_id = $5 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) ), touched AS ( SELECT p.type, date_trunc('day', p.updated_at)::date AS day, COUNT(DISTINCT p.id) AS cnt FROM pages p WHERE p.updated_at >= $6::timestamptz AND p.updated_at < $7::timestamptz AND p.source_id = $8 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1, 2 ) SELECT cd.type AS cohort_value, d.day::text AS day, COALESCE(t.cnt, 0)::int AS count FROM cohort_keys cd CROSS JOIN days d LEFT JOIN touched t ON t.type = cd.type AND t.day = d.day",
+ "textSha256": "a4c0a3376dcd274394549c66c93be411c4ccddc0034f091fdebbf0637fd43191"
},
{
"lane": "pool",
@@ -107,8 +107,8 @@
"string",
"string"
],
- "sql": "SELECT t.tag AS cohort_value, COUNT(DISTINCT p.id)::int AS count, array_agg(DISTINCT p.slug) AS slugs FROM tags t JOIN pages p ON p.id = t.page_id WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz AND p.source_id = $3 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1",
- "textSha256": "7d9e9818366b975d69432e05f9adc15860b1a4c7b0a68068d24d7c96b6daaf49"
+ "sql": "SELECT t.tag AS cohort_value, COUNT(DISTINCT p.id)::int AS count, array_agg(DISTINCT p.slug) AS slugs FROM tags t JOIN pages p ON p.id = t.page_id WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz AND p.source_id = $3 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1",
+ "textSha256": "ad46d4b228308206659c6ae0c3be60fad4c3531b5296b7811f8e4ecd3ee90fc3"
},
{
"lane": "pool",
@@ -117,8 +117,8 @@
"string",
"string"
],
- "sql": "SELECT p.type AS cohort_value, COUNT(DISTINCT p.id)::int AS count, array_agg(DISTINCT p.slug) AS slugs FROM pages p WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz AND p.source_id = $3 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1",
- "textSha256": "b8f7cec7eae27c1513dad5d46d1bf938294ad0165bb56155d827088fe1b399ef"
+ "sql": "SELECT p.type AS cohort_value, COUNT(DISTINCT p.id)::int AS count, array_agg(DISTINCT p.slug) AS slugs FROM pages p WHERE p.updated_at >= $1::timestamptz AND p.updated_at < $2::timestamptz AND p.source_id = $3 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY 1",
+ "textSha256": "9810ddcd5394138555fb93f9807f4535045aeed84d612888e5de4eedfcd32393"
}
],
"sourceIds": [
@@ -196,8 +196,8 @@
"string",
"number"
],
- "sql": "SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, 0 AS emotional_weight, COUNT(DISTINCT t.id) AS take_count, COALESCE(AVG(t.weight), 0) AS take_avg_weight, (0 * 5) + ln(1 + COUNT(DISTINCT t.id)) + (CASE WHEN p.slug LIKE 'media/articles/%' THEN 0.5 * 90.0 / (90.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'originals/%' THEN 0.5 * 180.0 / (180.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'companies/%' THEN 0.3 * 365.0 / (365.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'concepts/%' THEN 0 WHEN p.slug LIKE 'meetings/%' THEN 1 * 60.0 / (60.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'writing/%' THEN 0.4 * 365.0 / (365.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'media/x/%' THEN 1.5 * 7.0 / (7.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'people/%' THEN 0.3 * 365.0 / (365.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'daily/%' THEN 1.5 * 14.0 / (14.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'deals/%' THEN 0.5 * 180.0 / (180.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'chat/%' THEN 1 * 7.0 / (7.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) ELSE 0.3 * 90.0 / (90.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) END) AS score FROM pages p LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE AND t.holder = ANY($1::text[]) WHERE p.updated_at >= $2::timestamptz AND p.slug LIKE $3 ESCAPE '\\' AND p.slug NOT LIKE 'briefings/%' AND p.source_id = $4 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY p.id ORDER BY score DESC LIMIT $5",
- "textSha256": "6dbf0201b1c065a8393de5db190b87f099a54ad92c81eb0af7128cd93787c4f6"
+ "sql": "SELECT p.slug, p.source_id, p.title, p.type, p.updated_at, 0 AS emotional_weight, COUNT(DISTINCT t.id) AS take_count, COALESCE(AVG(t.weight), 0) AS take_avg_weight, (0 * 5) + ln(1 + COUNT(DISTINCT t.id)) + (CASE WHEN p.slug LIKE 'media/articles/%' THEN 0.5 * 90.0 / (90.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'originals/%' THEN 0.5 * 180.0 / (180.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'companies/%' THEN 0.3 * 365.0 / (365.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'concepts/%' THEN 0 WHEN p.slug LIKE 'meetings/%' THEN 1 * 60.0 / (60.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'writing/%' THEN 0.4 * 365.0 / (365.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'media/x/%' THEN 1.5 * 7.0 / (7.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'people/%' THEN 0.3 * 365.0 / (365.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'daily/%' THEN 1.5 * 14.0 / (14.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'deals/%' THEN 0.5 * 180.0 / (180.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) WHEN p.slug LIKE 'chat/%' THEN 1 * 7.0 / (7.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) ELSE 0.3 * 90.0 / (90.0 + EXTRACT(EPOCH FROM (NOW() - COALESCE(p.effective_date, p.updated_at))) / 86400.0) END) AS score FROM pages p LEFT JOIN takes t ON t.page_id = p.id AND t.active = TRUE AND t.holder = ANY($1::text[]) WHERE p.updated_at >= $2::timestamptz AND p.slug LIKE $3 ESCAPE '\\' AND p.slug NOT LIKE 'briefings/%' AND p.source_id = $4 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND EXISTS (SELECT 1 FROM sources read_source WHERE read_source.id = p.source_id AND NOT read_source.archived) GROUP BY p.id ORDER BY score DESC LIMIT $5",
+ "textSha256": "88df3cce8f770a91afc0be6ed4635ae3dc56b093c3a4d45353d1c92cd52dcb40"
}
],
"sourceIds": [
diff --git a/test/fixtures/goldens/sql-text/tags.json b/test/fixtures/goldens/sql-text/tags.json
index c3dae4f89f..5051bb50fe 100644
--- a/test/fixtures/goldens/sql-text/tags.json
+++ b/test/fixtures/goldens/sql-text/tags.json
@@ -149,8 +149,8 @@
"string",
"string"
],
- "sql": "SELECT DISTINCT tag FROM tags WHERE page_id IN (SELECT id FROM pages WHERE slug = $1 AND source_id = $2 AND (COALESCE(pages.frontmatter->>'visibility', CASE WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pages.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pages.source_id AND derived_origin.slug = pages.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pages.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pages.type = 'event' AND pages.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pages.source_id AND chronicle_origin.slug = pages.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(pages.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pages.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') = 'array' THEN pages.frontmatter->'derived_from' ELSE jsonb_build_array(pages.frontmatter->'derived_from') END) AS declared(slug))))) AND deleted_at IS NULL) ORDER BY tag",
- "textSha256": "715d385ca0b43b5bd24669e2d2c633072a62dc0ecdd4d2b1690969143a521a78"
+ "sql": "SELECT DISTINCT tag FROM tags WHERE page_id IN (SELECT id FROM pages WHERE slug = $1 AND source_id = $2 AND (COALESCE(pages.frontmatter->>'visibility', CASE WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN pages.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = pages.source_id AND derived_origin.slug = pages.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (pages.type = 'atom' OR (pages.type = 'concept' AND pages.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = pages.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN pages.type = 'event' AND pages.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = pages.source_id AND chronicle_origin.slug = pages.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = pages.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(pages.frontmatter->'derived_from') = 'array' THEN pages.frontmatter->'derived_from' ELSE jsonb_build_array(pages.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND deleted_at IS NULL) ORDER BY tag",
+ "textSha256": "fe24f600a3d212058fa3f2627baab859ef405c0fb42e66ef6efd010ad9e6e371"
}
],
"sourceIds": [
diff --git a/test/fixtures/goldens/sql-text/takes.json b/test/fixtures/goldens/sql-text/takes.json
index 313525b7ec..9e67f41384 100644
--- a/test/fixtures/goldens/sql-text/takes.json
+++ b/test/fixtures/goldens/sql-text/takes.json
@@ -59,8 +59,8 @@
"number",
"number"
],
- "sql": "WITH binned AS ( SELECT LEAST(FLOOR(weight::numeric / $1::numeric)::int, $2::int)::int AS bucket_idx, weight, (resolved_quality = 'correct')::int AS hit FROM takes WHERE resolved_quality IN ('correct','incorrect') AND holder = $3 AND holder = ANY($4::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($5::text[])) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))))) ) SELECT (bucket_idx::numeric * $6::numeric)::float AS bucket_lo, ((bucket_idx + 1)::numeric * $7::numeric)::float AS bucket_hi, COUNT(*)::int AS n, AVG(hit)::float AS observed, AVG(weight)::float AS predicted FROM binned GROUP BY bucket_idx ORDER BY bucket_idx",
- "textSha256": "e049a3a89f8b04246fe57c52e77af5de65cb30432316b4a2f1d12a3d707a05d4"
+ "sql": "WITH binned AS ( SELECT LEAST(FLOOR(weight::numeric / $1::numeric)::int, $2::int)::int AS bucket_idx, weight, (resolved_quality = 'correct')::int AS hit FROM takes WHERE resolved_quality IN ('correct','incorrect') AND holder = $3 AND holder = ANY($4::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($5::text[])) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END))) ) SELECT (bucket_idx::numeric * $6::numeric)::float AS bucket_lo, ((bucket_idx + 1)::numeric * $7::numeric)::float AS bucket_hi, COUNT(*)::int AS n, AVG(hit)::float AS observed, AVG(weight)::float AS predicted FROM binned GROUP BY bucket_idx ORDER BY bucket_idx",
+ "textSha256": "0392a4892c9d876cc85ab861f36f0489ee40f79513398ceb637d42199cb95a58"
}
],
"default": [
@@ -119,8 +119,8 @@
"array<string>",
"array<string>"
],
- "sql": "SELECT COUNT(*) FILTER (WHERE kind = 'bet')::int AS total_bets, COUNT(*) FILTER (WHERE resolved_quality IN ('correct','incorrect','partial'))::int AS resolved, COUNT(*) FILTER (WHERE resolved_quality = 'correct')::int AS correct, COUNT(*) FILTER (WHERE resolved_quality = 'incorrect')::int AS incorrect, COUNT(*) FILTER (WHERE resolved_quality = 'partial')::int AS partial, COUNT(*) FILTER (WHERE resolved_quality = 'unresolvable')::int AS unresolvable_count, AVG( CASE WHEN resolved_quality IN ('correct','incorrect') THEN POWER(weight - (CASE resolved_quality WHEN 'correct' THEN 1 ELSE 0 END), 2) END )::float AS brier FROM takes WHERE 1=1 AND holder = $1 AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.slug LIKE $2) AND since_date >= $3 AND since_date <= $4 AND holder = ANY($5::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($6::text[])) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))))",
- "textSha256": "e8ae64ce47c467175402c8e58a1e1cdf140f45899730a9e2f807993947d98c6d"
+ "sql": "SELECT COUNT(*) FILTER (WHERE kind = 'bet')::int AS total_bets, COUNT(*) FILTER (WHERE resolved_quality IN ('correct','incorrect','partial'))::int AS resolved, COUNT(*) FILTER (WHERE resolved_quality = 'correct')::int AS correct, COUNT(*) FILTER (WHERE resolved_quality = 'incorrect')::int AS incorrect, COUNT(*) FILTER (WHERE resolved_quality = 'partial')::int AS partial, COUNT(*) FILTER (WHERE resolved_quality = 'unresolvable')::int AS unresolvable_count, AVG( CASE WHEN resolved_quality IN ('correct','incorrect') THEN POWER(weight - (CASE resolved_quality WHEN 'correct' THEN 1 ELSE 0 END), 2) END )::float AS brier FROM takes WHERE 1=1 AND holder = $1 AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.slug LIKE $2) AND since_date >= $3 AND since_date <= $4 AND holder = ANY($5::text[]) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND p.source_id = ANY($6::text[])) AND EXISTS (SELECT 1 FROM pages p WHERE p.id = takes.page_id AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)))",
+ "textSha256": "83b9de08487d55f9fcff2bcb4d41da993f979217f39e2ea74d622457a4f728ec"
}
],
"default": [
@@ -283,8 +283,8 @@
"number",
"number"
],
- "sql": "SELECT t.*, p.slug AS page_slug FROM takes t JOIN pages p ON p.id = t.page_id WHERE 1=1 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND ($1::int IS NULL OR t.page_id = $2::int) AND ($3::text IS NULL OR p.slug = $4::text) AND ($5::text IS NULL OR t.holder = $6::text) AND ($7::text IS NULL OR t.kind = $8::text) AND ($9::boolean IS NULL OR t.active = $10::boolean) AND ( $11::boolean IS NULL OR ($12::boolean = true AND t.resolved_at IS NOT NULL) OR ($13::boolean = false AND t.resolved_at IS NULL) ) AND ( $14::text[] IS NULL OR t.holder = ANY($15::text[]) ) AND p.source_id = ANY($16::text[]) ORDER BY CASE WHEN $17 = 'weight' THEN t.weight END DESC NULLS LAST, CASE WHEN $18 = 'since_date' THEN t.since_date END DESC NULLS LAST, CASE WHEN $19 = 'created_at' THEN t.created_at END DESC NULLS LAST LIMIT $20 OFFSET $21",
- "textSha256": "1b9eb0a68a352024cd87880e12f8e2fd031f89c6d4420f813fa0a425c9029fa8"
+ "sql": "SELECT t.*, p.slug AS page_slug FROM takes t JOIN pages p ON p.id = t.page_id WHERE 1=1 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND ($1::int IS NULL OR t.page_id = $2::int) AND ($3::text IS NULL OR p.slug = $4::text) AND ($5::text IS NULL OR t.holder = $6::text) AND ($7::text IS NULL OR t.kind = $8::text) AND ($9::boolean IS NULL OR t.active = $10::boolean) AND ( $11::boolean IS NULL OR ($12::boolean = true AND t.resolved_at IS NOT NULL) OR ($13::boolean = false AND t.resolved_at IS NULL) ) AND ( $14::text[] IS NULL OR t.holder = ANY($15::text[]) ) AND p.source_id = ANY($16::text[]) ORDER BY CASE WHEN $17 = 'weight' THEN t.weight END DESC NULLS LAST, CASE WHEN $18 = 'since_date' THEN t.since_date END DESC NULLS LAST, CASE WHEN $19 = 'created_at' THEN t.created_at END DESC NULLS LAST LIMIT $20 OFFSET $21",
+ "textSha256": "8f7fd0a88c768517a46c6179802a19e0f99b016284ff580503ae9f48f15bb7a6"
}
]
},
@@ -387,8 +387,8 @@
"array<string>",
"number"
],
- "sql": "SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num, t.claim, t.kind, t.holder, t.weight, word_similarity($1, t.claim)::real AS score FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.active AND $2 <% t.claim AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND ( $3::text[] IS NULL OR t.holder = ANY($4::text[]) ) AND p.source_id = ANY($5::text[]) ORDER BY score DESC, t.weight DESC LIMIT $6",
- "textSha256": "44722c65d70768192edb1aac760c8b2f497a2c0b2381466b03f38d94d15698e1"
+ "sql": "SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num, t.claim, t.kind, t.holder, t.weight, word_similarity($1, t.claim)::real AS score FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.active AND $2 <% t.claim AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND ( $3::text[] IS NULL OR t.holder = ANY($4::text[]) ) AND p.source_id = ANY($5::text[]) ORDER BY score DESC, t.weight DESC LIMIT $6",
+ "textSha256": "9a4df8330d3b3ec0e9a9cbcbf73fe417dacc39db2ac10d378f7468e02b491068"
}
]
},
@@ -433,8 +433,8 @@
"string",
"number"
],
- "sql": "SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num, t.claim, t.kind, t.holder, t.weight, (1 - (t.embedding <=> $1::vector))::real AS score FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.active AND t.embedding IS NOT NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND ( $2::text[] IS NULL OR t.holder = ANY($3::text[]) ) AND p.source_id = ANY($4::text[]) ORDER BY t.embedding <=> $5::vector LIMIT $6",
- "textSha256": "70c50636d37c54a600816bc27bd13ec2296b13c8f69412fdd7494b72426e2d7c"
+ "sql": "SELECT t.id AS take_id, t.page_id, p.slug AS page_slug, t.row_num, t.claim, t.kind, t.holder, t.weight, (1 - (t.embedding <=> $1::vector))::real AS score FROM takes t JOIN pages p ON p.id = t.page_id WHERE t.active AND t.embedding IS NOT NULL AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND ( $2::text[] IS NULL OR t.holder = ANY($3::text[]) ) AND p.source_id = ANY($4::text[]) ORDER BY t.embedding <=> $5::vector LIMIT $6",
+ "textSha256": "0aa6701896aa6c022fb3f8353f4e9f4859b47acd3d3a526d34d6abaadbcecbda"
}
]
},
diff --git a/test/fixtures/goldens/sql-text/timeline.json b/test/fixtures/goldens/sql-text/timeline.json
index 58f87be252..c034577950 100644
--- a/test/fixtures/goldens/sql-text/timeline.json
+++ b/test/fixtures/goldens/sql-text/timeline.json
@@ -137,8 +137,8 @@
"string",
"number"
],
- "sql": "SELECT te.* FROM sources s CROSS JOIN LATERAL (SELECT * FROM pages WHERE source_id = s.id AND slug = $1 OFFSET 0) p JOIN timeline_entries te ON te.page_id = p.id WHERE p.slug = $2 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN event_private.type = 'event' AND event_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = event_private.source_id AND chronicle_origin.slug = event_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY te.date DESC, te.id DESC LIMIT $3",
- "textSha256": "ae5c3575a5553937a970825415e0c9ff5bee0f5c2fb4c8c6919888a6f0903156"
+ "sql": "SELECT te.* FROM sources s CROSS JOIN LATERAL (SELECT * FROM pages WHERE source_id = s.id AND slug = $1 OFFSET 0) p JOIN timeline_entries te ON te.page_id = p.id WHERE p.slug = $2 AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN event_private.type = 'event' AND event_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = event_private.source_id AND chronicle_origin.slug = event_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ORDER BY te.date DESC, te.id DESC LIMIT $3",
+ "textSha256": "403ba23be5418e679910242b72046a27ed28982a19287c18759d3dd5439f84db"
}
],
"sourceId": [
@@ -189,8 +189,8 @@
"string",
"number"
],
- "sql": "SELECT te.date::text AS date, te.summary, te.detail, te.source, te.page_id, p.slug AS page_slug, te.event_page_id, ep.slug AS event_slug, ep.effective_date::text AS effective_date, ep.frontmatter->'event'->>'kind' AS kind FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id WHERE te.date >= $1::date AND te.date <= $2::date AND (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN event_private.type = 'event' AND event_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = event_private.source_id AND chronicle_origin.slug = event_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY COALESCE(ep.effective_date, te.date::timestamptz) ASC, te.id ASC LIMIT $3",
- "textSha256": "a70bcad89c41f4e240cba8f8cbab6209fc25693ea4fc18078e20844772bdd59f"
+ "sql": "SELECT te.date::text AS date, te.summary, te.detail, te.source, te.page_id, p.slug AS page_slug, te.event_page_id, ep.slug AS event_slug, ep.effective_date::text AS effective_date, ep.frontmatter->'event'->>'kind' AS kind FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id WHERE te.date >= $1::date AND te.date <= $2::date AND (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN event_private.type = 'event' AND event_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = event_private.source_id AND chronicle_origin.slug = event_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ORDER BY COALESCE(ep.effective_date, te.date::timestamptz) ASC, te.id ASC LIMIT $3",
+ "textSha256": "b04cdcb90c3d09ca61cff24f0a342fe06072286fe633d461a8c701cd8d47d7d4"
}
],
"sourceIds+excludePrivate": [
@@ -203,8 +203,8 @@
"array<string>",
"number"
],
- "sql": "SELECT te.date::text AS date, te.summary, te.detail, te.source, te.page_id, p.slug AS page_slug, te.event_page_id, ep.slug AS event_slug, ep.effective_date::text AS effective_date, ep.frontmatter->'event'->>'kind' AS kind FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id AND ep.source_id = ANY($1::text[]) WHERE te.date >= $2::date AND te.date <= $3::date AND (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND p.source_id = ANY($4::text[]) AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))))) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN event_private.type = 'event' AND event_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = event_private.source_id AND chronicle_origin.slug = event_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))))) ELSE false END) AND NOT (jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') AND EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))))) )) ORDER BY COALESCE(ep.effective_date, te.date::timestamptz) ASC, te.id ASC LIMIT $5",
- "textSha256": "07a3321cbfedc6488a3aba2ba71f1c9dee95d6d217200d0dbc8ca4b47195e7c8"
+ "sql": "SELECT te.date::text AS date, te.summary, te.detail, te.source, te.page_id, p.slug AS page_slug, te.event_page_id, ep.slug AS event_slug, ep.effective_date::text AS effective_date, ep.frontmatter->'event'->>'kind' AS kind FROM timeline_entries te JOIN pages p ON p.id = te.page_id AND p.deleted_at IS NULL LEFT JOIN pages ep ON ep.id = te.event_page_id AND ep.source_id = ANY($1::text[]) WHERE te.date >= $2::date AND te.date <= $3::date AND (te.event_page_id IS NULL OR ep.deleted_at IS NULL) AND p.source_id = ANY($4::text[]) AND (COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type = 'atom' OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) AND (te.event_page_id IS NULL OR EXISTS ( SELECT 1 FROM pages event_private WHERE event_private.id = te.event_page_id AND (COALESCE(event_private.frontmatter->>'visibility', CASE WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN event_private.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = event_private.source_id AND derived_origin.slug = event_private.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (event_private.type = 'atom' OR (event_private.type = 'concept' AND event_private.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = event_private.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN event_private.type = 'event' AND event_private.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = event_private.source_id AND chronicle_origin.slug = event_private.frontmatter->'event'->>'depth' AND COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type = 'atom' OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = event_private.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug IN ( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(event_private.frontmatter->'derived_from') = 'array' THEN event_private.frontmatter->'derived_from' ELSE jsonb_build_array(event_private.frontmatter->'derived_from') END) AS declared(slug))) ELSE false END)) )) ORDER BY COALESCE(ep.effective_date, te.date::timestamptz) ASC, te.id ASC LIMIT $5",
+ "textSha256": "55e34ce17a4c3ffe9e1419a4ded1187f0c8b612f877609658eada50f3982a91e"
}
],
"week+sourceId": [
diff --git a/test/helpers/mention-brain.ts b/test/helpers/mention-brain.ts
new file mode 100644
index 0000000000..517d501249
--- /dev/null
+++ b/test/helpers/mention-brain.ts
@@ -0,0 +1,61 @@
+/**
+ * Entity mention index test helpers: a PGLite brain on the init-default
+ * schema pack (gbrain-base-v2) and small readers for mention links, derived
+ * aliases and status rows.
+ */
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { setCliOptions } from '../../src/core/cli-options.ts';
+import { extractStaleFromDB } from '../../src/commands/extract.ts';
+import type { PageType } from '../../src/core/types.ts';
+
+export async function mentionBrain(): Promise<PGLiteEngine> {
+ setCliOptions({ quiet: true, progressJson: false, progressInterval: 1000, explain: false, timeoutMs: null, brain: null });
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ return engine;
+}
+
+/** Empties every table the tests write (pages cascade to links, aliases and mention state). */
+export async function resetMentionBrain(engine: BrainEngine): Promise<void> {
+ await engine.executeRaw('DELETE FROM links');
+ await engine.executeRaw('DELETE FROM page_aliases');
+ await engine.executeRaw('DELETE FROM pages');
+ await engine.executeRaw('DELETE FROM mention_gazetteer_entries');
+ await engine.executeRaw('DELETE FROM mention_index_status');
+ await engine.executeRaw("DELETE FROM sources WHERE id <> 'default'");
+ for (const key of ['auto_link', 'mentions.auto_link', 'mentions.entity_types', 'mentions.ignore', 'link_resolution.cross_source', 'entity_identity.union']) {
+ await engine.unsetConfig(key);
+ }
+}
+
+export async function page(engine: BrainEngine, slug: string, type: string, title: string, body: string,
+ opts: { frontmatter?: Record<string, unknown>; sourceId?: string; timeline?: string } = {}): Promise<void> {
+ await engine.putPage(slug, { type: type as PageType, title, compiled_truth: body, timeline: opts.timeline ?? '', frontmatter: opts.frontmatter ?? {} },
+ opts.sourceId ? { sourceId: opts.sourceId } : undefined);
+}
+
+export async function sweep(engine: BrainEngine, opts: { sourceIdFilter?: string; timeBudgetMs?: number } = {}) {
+ return extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: opts.timeBudgetMs === undefined, ...opts });
+}
+
+/** `from -> to` for every mention link, sorted; typed_ner rows carry their kind. */
+export async function mentionLinks(engine: BrainEngine): Promise<string[]> {
+ const rows = await engine.executeRaw<{ f: string; t: string; kind: string | null }>(
+ `SELECT f.slug AS f, t.slug AS t, l.link_kind AS kind FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE l.link_source = 'mentions' ORDER BY 1, 2, 3`);
+ return rows.map(r => `${r.f} -> ${r.t}${r.kind === 'typed_ner' ? ' (typed_ner)' : ''}`);
+}
+
+export async function derivedAliases(engine: BrainEngine, slug: string): Promise<string[]> {
+ const rows = await engine.executeRaw<{ alias_norm: string; origin: string; case_sensitive: boolean }>(
+ 'SELECT alias_norm, origin, case_sensitive FROM page_aliases WHERE slug = $1 ORDER BY origin, alias_norm', [slug]);
+ return rows.map(r => `${r.origin}:${r.alias_norm}${r.case_sensitive ? ' (cs)' : ''}`);
+}
+
+export const ctxFor = (engine: BrainEngine, remote: boolean, notices: unknown[] = [], extra: Record<string, unknown> = {}) => ({
+ engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default',
+ emitNotice: (n: unknown) => { notices.push(n); }, ...extra,
+}) as never;
diff --git a/test/lens-pack-manifests.test.ts b/test/lens-pack-manifests.test.ts
index 7404f5db7f..8791394f6b 100644
--- a/test/lens-pack-manifests.test.ts
+++ b/test/lens-pack-manifests.test.ts
@@ -255,8 +255,8 @@ describe('v0.41 T4: gbrain-everything meta-pack shape', () => {
describe('#2117: gbrain-base-v2 ships link-inference regexes + explicit phases', () => {
const pack = loadPack('gbrain-base-v2');
- test('version bumped to 1.2.0 (open-loop link verbs owes_to/awaiting_reply_from)', () => {
- expect(pack.version).toBe('1.2.0');
+ test('version bumped to 1.3.0 (account entity type; 1.2.0 added open-loop link verbs)', () => {
+ expect(pack.version).toBe('1.3.0');
});
test('declares the 4 v1 inference regexes (founded/invested_in/advises/works_at)', () => {
diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.ts
index 4a7eff8069..3c80c4fbbb 100644
--- a/test/mcp-schema-budget.test.ts
+++ b/test/mcp-schema-budget.test.ts
@@ -28,6 +28,12 @@
* the rows the merge raised are the annotation bytes (+22 to +36) plus the
* F10 template text that brought sub-60-character descriptions up to
* purpose + next step + scope, and query's key-dependence sentence.
+ * Entity recall: entity +140 (referenced_by, backlink_count scope, the
+ * previews-are-not-evidence rule) and get_backlinks +250 (type, group, limit,
+ * cursor) are paid by equal budget cuts: query -150 and search -90 (shorter
+ * descriptions and parameter text; every pinned phrase kept), recall -50,
+ * remember -40, get_page -30, list_pages -30 (slack). Served starter list
+ * after: 24,324 model-visible characters, 5,471 tokens, 25,959 JSON characters.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -50,11 +56,11 @@ const PARAM_DESCRIPTION_HARD_CAP = 200;
/** Per-tool budget: JSON.stringify of the served tool definition. */
const TOOL_BUDGETS: Record<string, number> = {
add_timeline_entry: 640, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,
- delete_skill: 810, delta: 830, edit_page: 1090, entity: 460, find_anomalies: 520, forget: 560, get_agent_job: 270,
- get_backlinks: 430, get_ingest_log: 280, get_page: 810, get_recent_salience: 660, get_skill: 910,
+ delete_skill: 810, delta: 830, edit_page: 1090, entity: 600, find_anomalies: 520, forget: 560, get_agent_job: 270,
+ get_backlinks: 680, get_ingest_log: 280, get_page: 780, get_recent_salience: 660, get_skill: 910,
get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,
- list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,
- put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,
+ list_link_sources: 220, list_pages: 1060, list_skills: 670, list_write_requests: 450, put_page: 1320,
+ put_skill: 1420, query: 3100, recall: 1540, remember: 1330, request_tools: 560, resolve_slugs: 410, search: 1670,
submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 680, whoami: 230,
};
diff --git a/test/mentions-card-backlinks.test.ts b/test/mentions-card-backlinks.test.ts
new file mode 100644
index 0000000000..620a53ce40
--- /dev/null
+++ b/test/mentions-card-backlinks.test.ts
@@ -0,0 +1,277 @@
+/**
+ * Entity recall surfaces: the `entity` card's `referenced_by`,
+ * `referenced_by_count` and `coverage`, entity resolution with derived
+ * aliases, and get_backlinks' `type` / `group` / `limit` / `cursor`, through
+ * MCP dispatch on PGLite.
+ *
+ * Protects: a brief can enumerate every page that names an account (grouped
+ * by pack-canonical type, newest first, capped with an exact continuation);
+ * remote callers never see or count private or derived-private referrers or
+ * private fence text in previews; an exact title outranks a derived alias in
+ * every reader; legacy get_backlinks calls keep their array; paging has no
+ * duplicates or gaps; coverage states and their notices. Regression: a card
+ * whose continuation disagrees with its group, a subject alias hijacking an
+ * exact company name, a private memo leaking through `referenced_by`.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
+import { resolveEntitySlug } from '../src/core/entities/resolve.ts';
+import { entityNames } from '../src/core/facts/capture-dedup.ts';
+import { renderAction, cliRenderContext } from '../src/core/agent-output.ts';
+import { mentionCoverageNotice } from '../src/core/mentions/coverage.ts';
+import { linkEntityIdentity } from '../src/core/entity-identity.ts';
+import { mentionBrain, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+const config = { engine: 'pglite' } as never;
+const local = { remote: false, sourceId: 'default', config };
+const remote = { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config };
+
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+async function call(op: string, args: Record<string, unknown>, opts: Record<string, unknown> = local) {
+ const r = await dispatchToolCall(engine, op, args, opts as never);
+ return { result: r, json: r.isError ? null : JSON.parse(r.content[0].text), notices: r.content.slice(1).map(c => c.text) };
+}
+
+const account = () => page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO\nOwner: Dana Example');
+async function tickets(n: number, opts: { type?: string } = {}) {
+ for (let i = 0; i < n; i++) {
+ await page(engine, `tickets/t${String(i).padStart(3, '0')}`, opts.type ?? 'ticket', `Ticket ${i}`,
+ `Customer: QUCO Opened: 2026-01-${String((i % 28) + 1).padStart(2, '0')}\nStatus: ${i === 3 ? 'Open' : 'Closed'}`);
+ }
+}
+
+describe('entity card referenced_by', () => {
+ test('entity("QUCO") resolves the account; rows are grouped by canonical type, newest first, with previews', async () => {
+ await account();
+ await tickets(3);
+ await page(engine, 'meetings/m1', 'meeting', 'Meeting: QUCO renewal prep', '# Meeting: QUCO renewal prep\n\nRenewal blocker: security review.');
+ await sweep(engine);
+ const { json } = await call('entity', { name: 'QUCO' });
+ expect(json.card.entity.slug).toBe('crm/123');
+ expect(json.card.referenced_by_count).toBe(4);
+ expect(json.card.backlink_count).toBe(0);
+ const groups = Object.fromEntries(json.card.referenced_by.map((g: { canonical_type: string }) => [g.canonical_type, g]));
+ expect(groups.ticket.total).toBe(3);
+ expect(groups.ticket.rows.map((r: { slug: string }) => r.slug)).toEqual(['tickets/t002', 'tickets/t001', 'tickets/t000']);
+ expect(groups.ticket.rows[0]).toMatchObject({ title: 'Ticket 2', type: 'ticket', canonical_type: 'ticket', date_source: 'updated_at' });
+ expect(groups.ticket.rows[0].preview).toBe('Customer: QUCO Opened: 2026-01-03 Status: Closed');
+ expect(groups.meeting.rows[0].preview).toBe('Renewal blocker: security review.');
+ expect(json.card.coverage).toEqual({ state: 'complete', pending_pages: 0, last_pass_at: expect.any(String) });
+ });
+
+ test('entity("Quormiro Capital") resolves a record whose slug is not the name', async () => {
+ await account();
+ await sweep(engine);
+ expect((await call('entity', { name: 'Quormiro Capital' })).json.card.entity.slug).toBe('crm/123');
+ });
+
+ test('an exact company title outranks a CRM subject in entity, resolveEntitySlug and capture-dedup', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'crm/9', 'crm', 'CRM record: Acme Example', 'Account code: ACMX');
+ await sweep(engine);
+ expect((await call('entity', { name: 'Acme Example' })).json.card.entity.slug).toBe('companies/acme');
+ expect(await resolveEntitySlug(engine, 'default', 'Acme Example')).toBe('companies/acme');
+ expect(await engine.resolveAliases(['acme example'], { sourceId: 'default' })).toEqual(new Map());
+ expect((await entityNames(engine, 'default', ['companies/acme'])).get('companies/acme')).toEqual(['Acme Example']);
+ });
+
+ test('crm pages group under the pack-canonical type account', async () => {
+ await page(engine, 'people/dana', 'person', 'Dana Example', 'Owner.');
+ await account();
+ await sweep(engine);
+ const { json } = await call('entity', { name: 'Dana Example' });
+ expect(json.card.referenced_by.map((g: { canonical_type: string }) => g.canonical_type)).toEqual(['account']);
+ expect(json.card.referenced_by[0].rows[0]).toMatchObject({ type: 'crm', canonical_type: 'account' });
+ });
+
+ test('a group capped at 10 rows carries its total and a get_backlinks continuation that reproduces the group', async () => {
+ await account();
+ await tickets(14);
+ await sweep(engine);
+ const card = (await call('entity', { name: 'QUCO' }, remote)).json.card;
+ const group = card.referenced_by.find((g: { canonical_type: string }) => g.canonical_type === 'ticket');
+ expect(group.total).toBe(14);
+ expect(group.rows.length).toBe(10);
+ expect(group.next).toMatchObject({ tool: 'get_backlinks', arguments: { slug: 'crm/123', source_id: 'default', type: 'ticket', group: 'page', limit: 50 } });
+ const rest = (await call('get_backlinks', group.next.arguments, remote)).json;
+ expect(rest.total).toBe(14);
+ expect(rest.truncated).toBe(false);
+ const { cursor: _c, ...fromStart } = group.next.arguments;
+ const all = (await call('get_backlinks', fromStart, remote)).json;
+ expect(all.total).toBe(14);
+ expect(all.rows.slice(0, 10).map((r: { slug: string }) => r.slug)).toEqual(group.rows.map((r: { slug: string }) => r.slug));
+ expect([...group.rows, ...rest.rows].map((r: { slug: string }) => r.slug)).toEqual(all.rows.map((r: { slug: string }) => r.slug));
+ });
+
+ test('the whole card holds at most 50 rows across groups; every group keeps rows and a continuation', async () => {
+ await account();
+ for (const type of ['ticket', 'email', 'meeting', 'note', 'contract', 'invoice', 'call']) await tickets(9, { type });
+ await engine.executeRaw(`UPDATE pages SET slug = slug || '-' || type WHERE type <> 'crm'`);
+ await sweep(engine);
+ const card = (await call('entity', { name: 'QUCO' })).json.card;
+ expect(card.referenced_by_count).toBe(9);
+ expect(card.referenced_by.reduce((n: number, g: { rows: unknown[] }) => n + g.rows.length, 0)).toBeLessThanOrEqual(50);
+ });
+
+ test('remote callers: a private memo, a digest derived from it, an atom and a synthesized concept neither appear nor count; previews drop private fences', async () => {
+ await account();
+ await page(engine, 'notes/public', 'note', 'Public', 'QUCO renewal is on track.\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n| 1 | SECRETFACT churn risk | fact | 1.0 | private | medium | 2026-01-01 | | test | |\n<!--- gbrain:facts:end -->');
+ await page(engine, 'notes/memo', 'note', 'Board memo', 'QUCO layoffs MEMOMARKER.', { frontmatter: { visibility: 'private' } });
+ await page(engine, 'notes/digest', 'note', 'Digest', 'Summary of the QUCO memo DIGESTMARKER.', { frontmatter: { derived_from: 'notes/memo' } });
+ await page(engine, 'atoms/a1', 'atom', 'Atom', 'QUCO ATOMMARKER.');
+ await page(engine, 'concepts/c1', 'concept', 'Concept', 'QUCO CONCEPTMARKER.', { frontmatter: { synthesized_by: 'dream' } });
+ await sweep(engine);
+ const remoteText = (await dispatchToolCall(engine, 'entity', { name: 'QUCO' }, remote as never)).content[0].text;
+ for (const marker of ['notes/memo', 'MEMOMARKER', 'notes/digest', 'DIGESTMARKER', 'ATOMMARKER', 'CONCEPTMARKER', 'SECRETFACT']) expect(remoteText).not.toContain(marker);
+ expect(JSON.parse(remoteText).card.referenced_by_count).toBe(1);
+ const page1 = (await call('get_backlinks', { slug: 'crm/123', group: 'page' }, remote)).json;
+ expect(page1.total).toBe(1);
+ expect(JSON.stringify(page1)).not.toContain('SECRETFACT');
+ expect((await call('entity', { name: 'QUCO' })).json.card.referenced_by_count).toBe(5);
+ });
+
+ test('context_pack does not compute referenced_by (ambient callers stay cheap)', async () => {
+ await account();
+ await tickets(2);
+ await sweep(engine);
+ const card = (await buildEntityCard(engine, 'default', 'QUCO', { remote: false })).card!;
+ expect(card.referenced_by).toBeUndefined();
+ expect(card.coverage).toBeUndefined();
+ const pack = (await call('context_pack', { entities: 'QUCO' })).result.content[0].text;
+ expect(pack).not.toContain('referenced_by');
+ });
+
+ test('on the verbs surface a continuation names the starter surface', async () => {
+ await account();
+ await tickets(12);
+ await sweep(engine);
+ const card = (await buildEntityCard(engine, 'default', 'QUCO', { remote: true, includeReferences: true, surfaceCeiling: 'verbs' })).card!;
+ expect(card.referenced_by!.find(g => g.canonical_type === 'ticket')!.next!.requires_surface).toBe('starter');
+ });
+});
+
+describe('coverage states', () => {
+ test('pending on a miss before any pass, with a notice whose fix the local CLI runs and a remote agent relays', async () => {
+ await account();
+ const { json, notices } = await call('entity', { name: 'cat40 coverage probe' }, remote);
+ expect(json.found).toBe(false);
+ expect(json.coverage).toMatchObject({ state: 'pending', pending_pages: 1, degraded: true });
+ expect(notices.join('\n')).toContain('[gbrain notice mention_index');
+ const notice = mentionCoverageNotice(json.coverage)!;
+ expect(renderAction(notice.fix!, cliRenderContext()).next).toBe('run');
+ expect(notices.join('\n')).toContain('tell_user_to_run');
+ });
+
+ test('complete after a sweep; disabled when off; failed after a failed pass; type_not_linkable on a non-entity card', async () => {
+ await account();
+ await page(engine, 'projects/apollo', 'project', 'Project Apollo', 'Mentions QUCO.');
+ await sweep(engine);
+ expect((await call('entity', { name: 'cat40 coverage probe' })).json.coverage.state).toBe('complete');
+ const proj = (await call('entity', { name: 'Project Apollo' }, remote));
+ expect(proj.json.card.coverage.state).toBe('type_not_linkable');
+ expect(proj.notices.join('\n')).toContain('mentions.entity_types');
+ await engine.executeRaw("UPDATE mention_index_status SET state = 'failed', error = 'x'");
+ expect((await call('entity', { name: 'QUCO' }, remote)).json.card.coverage.state).toBe('failed');
+ await engine.setConfig('mentions.auto_link', 'false');
+ const off = await call('entity', { name: 'QUCO' }, remote);
+ expect(off.json.card.coverage).toMatchObject({ state: 'disabled', degraded: true });
+ expect(off.notices.join('\n')).toContain('mentions.auto_link');
+ });
+});
+
+describe('get_backlinks', () => {
+ test('without the new parameters the response is the unchanged link array', async () => {
+ await account();
+ await tickets(2);
+ await sweep(engine);
+ const { json } = await call('get_backlinks', { slug: 'crm/123' });
+ expect(Array.isArray(json)).toBe(true);
+ expect(json).toEqual(await engine.getBacklinks('crm/123', { sourceId: 'default' }));
+ });
+
+ test('type filters the array mode; a limit cut names the paged call', async () => {
+ await account();
+ await tickets(3);
+ await page(engine, 'meetings/m1', 'meeting', 'Meeting: QUCO', 'x');
+ await sweep(engine);
+ const meetings = (await call('get_backlinks', { slug: 'crm/123', type: 'meeting' })).json;
+ expect(meetings.map((l: { from_slug: string }) => l.from_slug)).toEqual(['meetings/m1']);
+ const cut = await call('get_backlinks', { slug: 'crm/123', limit: 2 }, remote);
+ expect(cut.json.length).toBe(2);
+ expect(cut.notices.join('\n')).toContain('listing_truncated');
+ });
+
+ test('limit over 500 and an unknown type are agent-operator errors naming the valid values', async () => {
+ await account();
+ await tickets(1);
+ await sweep(engine);
+ const big = await call('get_backlinks', { slug: 'crm/123', group: 'page', limit: 501 });
+ expect(big.result.isError).toBe(true);
+ expect(big.result.content[0].text).toContain('1 to 500');
+ const bad = await call('get_backlinks', { slug: 'crm/123', type: 'bogus' });
+ expect(bad.result.isError).toBe(true);
+ expect(bad.result.content[0].text).toContain('ticket');
+ });
+
+ test('pack aliases and observed types are accepted; untyped pages group as untyped', async () => {
+ await page(engine, 'people/dana', 'person', 'Dana Example', 'x');
+ await account();
+ await page(engine, 'misc/raw', '', 'Raw', 'Dana Example called.');
+ await sweep(engine);
+ expect((await call('get_backlinks', { slug: 'people/dana', group: 'page', type: 'crm' })).json.rows[0].canonical_type).toBe('account');
+ expect((await call('get_backlinks', { slug: 'people/dana', group: 'page', type: 'account' })).json.total).toBe(1);
+ const card = (await call('entity', { name: 'Dana Example' })).json.card;
+ expect(card.referenced_by.map((g: { canonical_type: string }) => g.canonical_type).sort()).toEqual(['account', 'untyped']);
+ expect((await call('get_backlinks', { slug: 'people/dana', group: 'page', type: 'untyped' })).json.rows[0].slug).toBe('misc/raw');
+ });
+
+ test('identity union: off counts the page alone; on, the card and its continuation both include co-member referrers', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'x');
+ await page(engine, 'companies/acme-inc', 'company', 'Acme Incorporated', 'x');
+ await page(engine, 'notes/a', 'note', 'a', 'Acme Example signed.');
+ await page(engine, 'notes/b', 'note', 'b', 'Acme Incorporated paid.');
+ await sweep(engine);
+ await linkEntityIdentity(engine, { entityId: 'acme-group', slug: 'companies/acme', sourceId: 'default' });
+ await linkEntityIdentity(engine, { entityId: 'acme-group', slug: 'companies/acme-inc', sourceId: 'default' });
+ const counts = async () => [
+ (await call('entity', { name: 'companies/acme' })).json.card.referenced_by_count,
+ (await call('get_backlinks', { slug: 'companies/acme', group: 'page' })).json.total,
+ ];
+ expect(await counts()).toEqual([1, 1]);
+ await engine.setConfig('entity_identity.union', 'true');
+ expect(await counts()).toEqual([2, 2]);
+ });
+
+ test('more than 500 referrers across two sources with equal dates page without duplicates or gaps', async () => {
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING");
+ await page(engine, 'people/hub', 'person', 'Hub Person', 'x');
+ const [hub] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'people/hub'");
+ // Same slugs in both sources, one shared date: order falls to (source_id, slug).
+ for (const source of ['default', 'other']) {
+ await engine.executeRaw(
+ `INSERT INTO pages (source_id, slug, type, title, compiled_truth, updated_at)
+ SELECT $1, 'notes/r' || lpad(g::text, 4, '0'), 'note', 'R' || g, 'x', '2026-01-01T00:00:00Z' FROM generate_series(1, 300) g`, [source]);
+ await engine.executeRaw(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, link_source)
+ SELECT p.id, $2, 'mentions', 'mentions' FROM pages p WHERE p.source_id = $1 AND p.slug LIKE 'notes/r%'`, [source, hub.id]);
+ }
+ const scope = { remote: false, config, sourceId: 'default' };
+ const seen: string[] = [];
+ let cursor: string | undefined;
+ for (let i = 0; i < 10; i++) {
+ const { json } = await call('get_backlinks', { slug: 'people/hub', all_sources: true, group: 'page', limit: 137, ...(cursor ? { cursor } : {}) }, scope);
+ expect(json.total).toBe(600);
+ seen.push(...json.rows.map((r: { source_id: string; slug: string }) => `${r.source_id}:${r.slug}`));
+ if (!json.truncated) break;
+ cursor = json.cursor;
+ }
+ expect(seen.length).toBe(600);
+ expect(new Set(seen).size).toBe(600);
+ });
+});
diff --git a/test/mentions-explain.test.ts b/test/mentions-explain.test.ts
new file mode 100644
index 0000000000..2896193798
--- /dev/null
+++ b/test/mentions-explain.test.ts
@@ -0,0 +1,106 @@
+/**
+ * `gbrain extract mentions --explain <name|slug> [--page <slug>]`.
+ *
+ * Protects: one reason code per rejection class, so an agent debugging
+ * "why isn't this page listed?" gets the guard that applied and is never told
+ * to rerun extraction for a policy rejection; `extract --explain <kind>`
+ * keeps its own meaning. Regression: an explain that reports "links" for a
+ * name the gazetteer dropped, or `pending` for a policy rejection.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { explainMention } from '../src/commands/extract-mentions-explain.ts';
+import { runExtract } from '../src/commands/extract.ts';
+import { mentionBrain, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+const account = () => page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO. Ticker: QCO.');
+
+describe('extract mentions --explain reason codes', () => {
+ test('a linking name reports its entry and origin', async () => {
+ await account();
+ await sweep(engine);
+ const r = await explainMention(engine, 'QUCO');
+ expect(r.reason).toBeNull();
+ expect(r.entries).toEqual([{ name: 'QUCO', slug: 'crm/123', origin: 'declared', case_sensitive: true }]);
+ });
+
+ test('case_mismatch', async () => {
+ await account();
+ await sweep(engine);
+ expect((await explainMention(engine, 'quco')).reason).toBe('case_mismatch');
+ });
+
+ test('ambiguous_first_word', async () => {
+ await account();
+ await sweep(engine);
+ expect((await explainMention(engine, 'Quormiro')).reason).toBe('ambiguous_first_word');
+ });
+
+ test('below_min_length (a 3-character declared code)', async () => {
+ await account();
+ await sweep(engine);
+ expect((await explainMention(engine, 'QCO')).reason).toBe('below_min_length');
+ });
+
+ test('generic_token', async () => {
+ await page(engine, 'people/will', 'person', 'Will', 'x');
+ expect((await explainMention(engine, 'Will')).reason).toBe('generic_token');
+ });
+
+ test('alias_collision', async () => {
+ await page(engine, 'crm/a', 'crm', 'CRM record: Alpha Holdings', 'Account code: DUPE');
+ await page(engine, 'crm/b', 'crm', 'CRM record: Beta Holdings', 'Account code: DUPE');
+ await sweep(engine);
+ expect((await explainMention(engine, 'DUPE')).reason).toBe('alias_collision');
+ });
+
+ test('type_not_linkable', async () => {
+ await page(engine, 'projects/apollo', 'project', 'Project Apollo', 'x');
+ expect((await explainMention(engine, 'projects/apollo')).reason).toBe('type_not_linkable');
+ });
+
+ test('linking_disabled', async () => {
+ await account();
+ await engine.setConfig('mentions.auto_link', 'false');
+ expect((await explainMention(engine, 'QUCO')).reason).toBe('linking_disabled');
+ });
+
+ test('pending names the sweep; a policy rejection never does', async () => {
+ await account();
+ await sweep(engine);
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ const r = await explainMention(engine, 'QUCO', { page: 'tickets/t1' });
+ expect(r).toMatchObject({ reason: 'pending', page: { slug: 'tickets/t1', linked: false }, next: 'gbrain extract --stale' });
+ expect((await explainMention(engine, 'quco')).next).toBeUndefined();
+ await sweep(engine);
+ expect(await explainMention(engine, 'QUCO', { page: 'tickets/t1' })).toMatchObject({ reason: null, page: { linked: true } });
+ });
+
+ test('ignored_by_page', async () => {
+ await account();
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO', { frontmatter: { mention_ignore: ['QUCO'] } });
+ await sweep(engine);
+ expect((await explainMention(engine, 'QUCO', { page: 'tickets/t1' })).reason).toBe('ignored_by_page');
+ });
+
+ test('ignored_by_config and not_a_known_name', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'x');
+ await engine.setConfig('mentions.ignore', 'Acme Example');
+ expect((await explainMention(engine, 'Acme Example')).reason).toBe('ignored_by_config');
+ expect((await explainMention(engine, 'Nobody Holdings')).reason).toBe('not_a_known_name');
+ });
+
+ test('`gbrain extract --explain <kind>` keeps its own meaning', async () => {
+ const out: string[] = [];
+ const log = console.log;
+ console.log = (m?: unknown) => { out.push(String(m)); };
+ try { await runExtract(engine, ['--explain', 'atoms', '--json']); }
+ finally { console.log = log; }
+ expect(JSON.parse(out.join('\n'))).toMatchObject({ schema_version: 1, kind: 'atoms' });
+ });
+});
diff --git a/test/mentions-managed.test.ts b/test/mentions-managed.test.ts
new file mode 100644
index 0000000000..84fa534ee0
--- /dev/null
+++ b/test/mentions-managed.test.ts
@@ -0,0 +1,43 @@
+/**
+ * Entity mention index on a managed-persistence brain (the slot builds'
+ * shape: a git-backed source with a claimed worktree). `page_aliases` is
+ * guarded by the managed-writer trigger, so derived alias rows must be
+ * written through the coordinated writer, both at import and in the stale
+ * sweep; sync's inline extraction runs links only.
+ *
+ * Regression: a derived alias write outside the coordinator (refused by the
+ * guard, failing the sweep), or sync writing mention rows.
+ */
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { extractManagedStaleLinks } from '../src/core/persistence/links-maintenance.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+import { runReindexAliases } from '../src/commands/reindex-aliases.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { derivedAliases, mentionLinks } from './helpers/mention-brain.ts';
+
+const put = (ctx: OperationContext, slug: string, type: string, title: string, body: string) => submitPageMutation(ctx, { operation: 'put_page',
+ params: { slug, request_id: randomUUID(), content: `---\ntype: ${type}\ntitle: "${title}"\n---\n\n${body}\n` } });
+
+test('managed brain: import writes derived aliases; sync-style extraction writes no mention rows; extract --stale links them', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await engine.setConfig('schema_pack', 'gbrain-base-v2');
+ await put(ctx, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO');
+ await put(ctx, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO\nStatus: Open');
+ await disposePersistenceConsumer(engine);
+ expect(await derivedAliases(engine, 'crm/123')).toEqual(['declared:quco (cs)', 'subject:quormiro capital']);
+ await extractManagedStaleLinks(engine, { sourceId: 'default', mentions: false });
+ expect(await mentionLinks(engine)).toEqual([]);
+ const r = await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: true });
+ expect(r.mentions).toMatchObject({ state: 'complete', remaining: 0 });
+ expect(await mentionLinks(engine)).toEqual(['tickets/t1 -> crm/123']);
+ // Derived rows refresh through the coordinated writer in the sweep and in reindex --aliases.
+ await engine.executeRaw("UPDATE page_mention_state SET alias_revision = NULL");
+ await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: true });
+ await runReindexAliases(engine, ['--json']);
+ expect(await derivedAliases(engine, 'crm/123')).toEqual(['declared:quco (cs)', 'subject:quormiro capital']);
+ });
+}, 180_000);
diff --git a/test/mentions-pass.test.ts b/test/mentions-pass.test.ts
new file mode 100644
index 0000000000..35657d8e11
--- /dev/null
+++ b/test/mentions-pass.test.ts
@@ -0,0 +1,363 @@
+/**
+ * Entity mention index, the pass (mentions/pass.ts) as `gbrain extract
+ * --stale` runs it on PGLite.
+ *
+ * Protects: default-on mention links from the stale sweep alone; incremental
+ * convergence (later entity, edited page, deleted and recreated entity,
+ * removed last entity) without rescanning unaffected pages; the reconcile
+ * touching only plain mention rows (typed_ner survives, also across off/on);
+ * the off switch; conditional publish (an edit during the scan leaves the
+ * page due); fail-closed index builds; an upgraded brain whose links are
+ * current; a slot-style build leaving 0 pages due; dry-run counts matching
+ * the real run. Regression: a sweep that skips mentions when links are
+ * current, a reconcile that deletes typed_ner rows, a pass that publishes
+ * links computed from a stale page or gazetteer.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { extractStaleFromDB } from '../src/commands/extract.ts';
+import { countMentionDuePages, runMentionPass } from '../src/core/mentions/pass.ts';
+import { buildGazetteer } from '../src/core/by-mention.ts';
+import { readMentionCoverage } from '../src/core/mentions/coverage.ts';
+import { mentionIndexUpgradeNotice } from '../src/core/mentions/upgrade-notice.ts';
+import { derivedAliases, mentionBrain, mentionLinks, page, resetMentionBrain, sweep } from './helpers/mention-brain.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = await mentionBrain(); }, 120_000);
+afterAll(async () => { await engine.disconnect(); });
+beforeEach(async () => { await resetMentionBrain(engine); });
+
+const account = () => page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO\nOwner: Dana Example');
+
+describe('the stale sweep links mentions by default', () => {
+ test('a fresh brain: an account page and a ticket naming it by code get a mention link from extract --stale alone', async () => {
+ await account();
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO\nStatus: Open');
+ const r = await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['tickets/t1 -> crm/123']);
+ expect(await derivedAliases(engine, 'crm/123')).toEqual(['declared:quco (cs)', 'subject:quormiro capital']);
+ expect(r.mentions).toMatchObject({ state: 'complete', remaining: 0 });
+ expect(await countMentionDuePages(engine)).toBe(0);
+ });
+
+ test('page titles are scanned: a meeting titled with the code links', async () => {
+ await account();
+ await page(engine, 'meetings/m1', 'meeting', 'Meeting: QUCO renewal prep', 'Notes.');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['meetings/m1 -> crm/123']);
+ });
+
+ test('a code linked only as written: lowercase prose does not link', async () => {
+ await account();
+ await page(engine, 'notes/n1', 'note', 'n1', 'we used quco as a placeholder');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ });
+
+ test('an older page links to a later-added entity on the next sweep; unaffected pages are not rescanned', async () => {
+ await page(engine, 'notes/n1', 'note', 'n1', 'Met Zebra Holdings today.');
+ await page(engine, 'notes/n2', 'note', 'n2', 'Nothing relevant.');
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await sweep(engine);
+ await page(engine, 'companies/zebra', 'company', 'Zebra Holdings', 'Another company.');
+ const r = await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> companies/zebra']);
+ // The new entity page itself plus the one page whose text names it.
+ expect(r.mentions?.pages).toBe(2);
+ });
+
+ test('an edited page loses a mention it no longer contains', async () => {
+ await account();
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ await sweep(engine);
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer unknown.');
+ const r = await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ expect(r.mentions?.removed).toBe(1);
+ });
+
+ test('an entity deleted and recreated under another slug with the same title retargets older pages', async () => {
+ await page(engine, 'companies/old', 'company', 'Acme Example', 'v1');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Talked to Acme Example.');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> companies/old']);
+ await engine.softDeletePage('companies/old');
+ await page(engine, 'companies/new', 'company', 'Acme Example', 'v2');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> companies/new']);
+ });
+
+ test('removing the last entity removes its links (an empty gazetteer still reconciles)', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Talked to Acme Example.');
+ await sweep(engine);
+ await engine.softDeletePage('companies/acme');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ });
+
+ test('Unicode and punctuation variants of a new name are found', async () => {
+ await page(engine, 'companies/seed', 'company', 'Seed Company', 'x');
+ await page(engine, 'notes/nfd', 'note', 'nfd', 'Visited Ha\u0300 Nô\u0323i Labs yesterday.');
+ await page(engine, 'notes/dash', 'note', 'dash', 'The Widget-Works deal closed.');
+ await sweep(engine);
+ await page(engine, 'companies/hn', 'company', 'Hà Nội Labs', 'x');
+ await page(engine, 'companies/ww', 'company', 'Widget Works', 'x');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/dash -> companies/ww', 'notes/nfd -> companies/hn']);
+ });
+});
+
+describe('reconcile scope, off switch and failure', () => {
+ test('typed_ner rows survive a reconcile and an off/on cycle while an obsolete plain mention goes', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'people/alice', 'person', 'Alice Example', 'Alice works at Acme Example.');
+ await sweep(engine);
+ await engine.addLinksBatch([{ from_slug: 'people/alice', to_slug: 'companies/acme', link_type: 'works_at', link_source: 'mentions', link_kind: 'typed_ner', context: 'works at' } as never]);
+ await page(engine, 'people/alice', 'person', 'Alice Example', 'Alice moved on.');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['people/alice -> companies/acme (typed_ner)']);
+ await engine.setConfig('mentions.auto_link', 'false');
+ await sweep(engine);
+ await engine.unsetConfig('mentions.auto_link');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['people/alice -> companies/acme (typed_ner)']);
+ });
+
+ test('enabled → disabled → enabled without page edits: links and derived aliases go, then come back', async () => {
+ await account();
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ await sweep(engine);
+ await engine.setConfig('mentions.auto_link', 'false');
+ const off = await sweep(engine);
+ expect(off.mentions?.state).toBe('disabled');
+ expect(await mentionLinks(engine)).toEqual([]);
+ expect(await derivedAliases(engine, 'crm/123')).toEqual([]);
+ expect((await readMentionCoverage(engine, ['default'])).state).toBe('disabled');
+ await engine.setConfig('mentions.auto_link', 'true');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['tickets/t1 -> crm/123']);
+ expect(await derivedAliases(engine, 'crm/123')).toEqual(['declared:quco (cs)', 'subject:quormiro capital']);
+ });
+
+ test('global auto_link=false also stops the pass', async () => {
+ await account();
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ await engine.setConfig('auto_link', 'false');
+ expect((await sweep(engine)).mentions?.state).toBe('disabled');
+ expect(await mentionLinks(engine)).toEqual([]);
+ });
+
+ test('an edit committed during the scan leaves the page due; the next pass publishes it', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Acme Example called.');
+ let edited = false;
+ const r = await runMentionPass(engine, { beforePublish: async () => {
+ if (edited) return;
+ edited = true;
+ await page(engine, 'notes/n1', 'note', 'n1', 'Nobody called.');
+ } });
+ expect(r.skipped).toBeGreaterThan(0);
+ expect(await mentionLinks(engine)).toEqual([]);
+ expect(await countMentionDuePages(engine)).toBe(1);
+ await runMentionPass(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ expect(await countMentionDuePages(engine)).toBe(0);
+ });
+
+ test('a gazetteer change saved during the scan fails the publish (generation check)', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Acme Example and Zebra Holdings.');
+ await runMentionPass(engine);
+ await page(engine, 'notes/n2', 'note', 'n2', 'Acme Example again.');
+ let raced = false;
+ const r = await runMentionPass(engine, { beforePublish: async () => {
+ if (raced) return;
+ raced = true;
+ await page(engine, 'companies/zebra', 'company', 'Zebra Holdings', 'x');
+ await runMentionPass(engine);
+ } });
+ expect(r.skipped).toBeGreaterThan(0);
+ await runMentionPass(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> companies/acme', 'notes/n1 -> companies/zebra', 'notes/n2 -> companies/acme']);
+ });
+
+ test('overlapping sweeps converge to one consistent result', async () => {
+ await account();
+ for (let i = 0; i < 30; i++) await page(engine, `tickets/t${i}`, 'ticket', `Ticket ${i}`, `Customer: QUCO, ticket ${i}`);
+ await Promise.all([runMentionPass(engine), runMentionPass(engine)]);
+ await runMentionPass(engine);
+ expect((await mentionLinks(engine)).length).toBe(30);
+ expect(await countMentionDuePages(engine)).toBe(0);
+ });
+
+ test('an alias read failure writes nothing and records failed', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Acme Example called.');
+ await sweep(engine);
+ await page(engine, 'notes/n1', 'note', 'n1', 'Nobody called.');
+ const raw = engine.executeRaw.bind(engine);
+ (engine as unknown as { executeRaw: typeof raw }).executeRaw = (async (sql: string, params?: unknown[]) => {
+ if (/FROM page_aliases pa\s+JOIN pages p/.test(sql)) throw new Error('simulated alias read failure');
+ return raw(sql, params);
+ }) as typeof raw;
+ try {
+ const r = await runMentionPass(engine);
+ expect(r.state).toBe('failed');
+ expect(r.error).toContain('simulated alias read failure');
+ } finally {
+ // Drop the own-property shadow: transaction clones must read the engine's own method again.
+ delete (engine as unknown as { executeRaw?: typeof raw }).executeRaw;
+ }
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> companies/acme']);
+ expect((await readMentionCoverage(engine, ['default'])).state).toBe('failed');
+ await runMentionPass(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ });
+
+ test('a retyped page loses its derived aliases; frontmatter aliases survive the cleanup', async () => {
+ await page(engine, 'crm/123', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO', { frontmatter: { aliases: ['QC Holdings'] } });
+ await engine.setPageAliases('crm/123', 'default', ['qc holdings']);
+ await sweep(engine);
+ expect(await derivedAliases(engine, 'crm/123')).toEqual(['declared:quco (cs)', 'frontmatter:qc holdings', 'subject:quormiro capital']);
+ await page(engine, 'crm/123', 'note', 'CRM record: Quormiro Capital', 'Account code: QUCO', { frontmatter: { aliases: ['QC Holdings'] } });
+ await sweep(engine);
+ expect(await derivedAliases(engine, 'crm/123')).toEqual(['frontmatter:qc holdings']);
+ });
+
+ test('a contract that declares the same code contributes nothing', async () => {
+ await account();
+ await page(engine, 'contracts/c1', 'contract', 'Contract: Quormiro Capital MSA', 'Account code: QUCO');
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ await sweep(engine);
+ expect(await derivedAliases(engine, 'contracts/c1')).toEqual([]);
+ expect(await mentionLinks(engine)).toEqual(['contracts/c1 -> crm/123', 'tickets/t1 -> crm/123']);
+ });
+});
+
+describe('upgrade, slot builds and dry runs', () => {
+ test('an upgraded brain whose links are current gets aliases and mention links from one sweep', async () => {
+ await account();
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: Quormiro Capital');
+ // The previous release: links extracted and stamped, no mention state.
+ await extractStaleFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, catchUp: true });
+ await engine.executeRaw('DELETE FROM links');
+ await engine.executeRaw("DELETE FROM page_aliases WHERE origin <> 'frontmatter'");
+ await engine.executeRaw('DELETE FROM page_mention_state');
+ await engine.executeRaw('DELETE FROM mention_gazetteer_entries');
+ await engine.executeRaw('DELETE FROM mention_index_status');
+ expect(await engine.countStalePagesForExtraction({ versionTs: '1970-01-01T00:00:00Z' })).toBe(0);
+ expect((await mentionIndexUpgradeNotice(engine))?.join('\n')).toContain('gbrain extract --stale --catch-up');
+ const r = await sweep(engine);
+ expect(r.pagesProcessed).toBe(0);
+ expect(await mentionLinks(engine)).toEqual(['tickets/t1 -> crm/123']);
+ expect(await mentionIndexUpgradeNotice(engine)).toBeNull();
+ });
+
+ test('a budgeted (cycle) sweep makes mention progress when links are current', async () => {
+ await account();
+ for (let i = 0; i < 5; i++) await page(engine, `tickets/t${i}`, 'ticket', `Ticket ${i}`, 'Customer: QUCO');
+ await sweep(engine, { timeBudgetMs: 60_000 });
+ expect((await mentionLinks(engine)).length).toBe(5);
+ });
+
+ test('a slot-style build (over 1,000 pages, then extract --stale) leaves 0 pages due and complete coverage', async () => {
+ await account();
+ for (let i = 0; i < 1_050; i++) await page(engine, `mail/m${i}`, 'email', `Mail ${i}`, i % 50 === 0 ? 'Re: QUCO renewal' : 'Weekly digest');
+ const dry = await extractStaleFromDB(engine, { dryRun: true, jsonMode: false, quiet: true, catchUp: true });
+ const r = await sweep(engine);
+ expect(await countMentionDuePages(engine)).toBe(0);
+ expect(r.mentions?.pages).toBe(1_051);
+ expect(dry.staleRemaining - (r.pagesProcessed)).toBe(1_051);
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'complete', pending_pages: 0 });
+ expect((await mentionLinks(engine)).length).toBe(21);
+ }, 180_000);
+
+ test('coverage counts pages written since the last pass', async () => {
+ await account();
+ await sweep(engine);
+ await page(engine, 'tickets/t1', 'ticket', 'Ticket 1', 'Customer: QUCO');
+ expect(await readMentionCoverage(engine, ['default'])).toMatchObject({ state: 'pending', pending_pages: 1, degraded: true });
+ });
+});
+
+describe('gazetteer guards', () => {
+ test('two entities sharing a first word: the shared word alone never links', async () => {
+ await page(engine, 'crm/a', 'crm', 'CRM record: Quormiro Capital', 'Account code: QUCO');
+ await page(engine, 'crm/b', 'crm', 'CRM record: Quormiro Labs', 'Account code: QULA');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Quormiro asked about pricing. Later Quormiro Labs replied.');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> crm/b']);
+ });
+
+ test('a code declared by two accounts is dropped as a collision', async () => {
+ await page(engine, 'crm/a', 'crm', 'CRM record: Alpha Holdings', 'Account code: DUPE');
+ await page(engine, 'crm/b', 'crm', 'CRM record: Beta Holdings', 'Account code: DUPE');
+ await page(engine, 'notes/n1', 'note', 'n1', 'DUPE escalated.');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ });
+
+ test('an exact company title outranks a CRM subject in the gazetteer', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'crm/9', 'crm', 'CRM record: Acme Example', 'Account code: ACMX');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Acme Example signed. ACMX renewal.');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> companies/acme', 'notes/n1 -> crm/9']);
+ });
+
+ test('mentions.ignore drops a name; frontmatter mention_ignore drops it for one page', async () => {
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'A company.');
+ await page(engine, 'companies/zebra', 'company', 'Zebra Holdings', 'x');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Acme Example and Zebra Holdings.', { frontmatter: { mention_ignore: ['Zebra Holdings'] } });
+ await page(engine, 'notes/n2', 'note', 'n2', 'Acme Example and Zebra Holdings.');
+ await engine.setConfig('mentions.ignore', 'Acme Example');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n2 -> companies/zebra']);
+ });
+
+ test('mentions.entity_types opts a type in', async () => {
+ await page(engine, 'projects/apollo', 'project', 'Project Apollo', 'x');
+ await page(engine, 'notes/n1', 'note', 'n1', 'Project Apollo shipped.');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual([]);
+ await engine.setConfig('mentions.entity_types', '+project');
+ await sweep(engine);
+ expect(await mentionLinks(engine)).toEqual(['notes/n1 -> projects/apollo']);
+ });
+
+ test('independent fixture: status buried mid-body, duplicate records, undeclared aliases, people named Will and Grace', async () => {
+ await page(engine, 'accounts/northwind', 'account', 'Northwind Traders', 'Primary account. Account code: NWTR');
+ await page(engine, 'accounts/northwind-2', 'account', 'Northwind Traders', 'Duplicate record created by an import.');
+ await page(engine, 'people/will', 'person', 'Will Turner', 'Sales lead.');
+ await page(engine, 'people/grace', 'person', 'Grace Hopper-Example', 'Engineer.');
+ await page(engine, 'tickets/x1', 'ticket', 'Escalation', 'Opened Monday.\nWe will follow up. Grace period ends Friday.\nStatus: Open\nNW asked again; NWTR is blocked.');
+ await sweep(engine);
+ const links = await mentionLinks(engine);
+ expect(links).toContain('tickets/x1 -> accounts/northwind');
+ expect(links.some(l => l.includes('people/will') || l.includes('people/grace'))).toBe(false);
+ // Both duplicate records keep the same title; the scanner picks one deterministically, never both.
+ expect(links.filter(l => l.startsWith('tickets/x1')).length).toBe(1);
+ });
+
+ test('extract-ner and meeting timeline extraction read the wider gazetteer', async () => {
+ await account();
+ const g = await buildGazetteer(engine);
+ await sweep(engine);
+ const g2 = await buildGazetteer(engine);
+ // Before the sweep only the full title is a name; the sweep derives the subject and the code.
+ expect([...g.keys()]).toEqual(['crm']);
+ expect([...g2.keys()]).toEqual(expect.arrayContaining(['crm', 'quormiro', 'quco']));
+ const { extractNerLinks } = await import('../src/core/extract-ner.ts');
+ await page(engine, 'companies/acme', 'company', 'Acme Example', 'Ticker: ACMX');
+ await page(engine, 'people/dana', 'person', 'Dana Example', 'Dana works at ACMX.');
+ await sweep(engine);
+ const ner = await extractNerLinks(engine);
+ expect(ner.created).toBe(1);
+ expect(await mentionLinks(engine)).toContain('people/dana -> companies/acme (typed_ner)');
+ const { extractTimelineFromMeetings } = await import('../src/core/extract-timeline-from-meetings.ts');
+ await page(engine, 'meetings/2026-04-03', 'meeting', 'Renewal prep', 'Reviewed the QUCO renewal.', { frontmatter: { date: '2026-04-03' } });
+ const meetings = await extractTimelineFromMeetings(engine, { dryRun: true });
+ expect(meetings.entries_created).toBeGreaterThanOrEqual(1);
+ });
+});
diff --git a/test/mentions-policy-aliases.test.ts b/test/mentions-policy-aliases.test.ts
new file mode 100644
index 0000000000..620a01073d
--- /dev/null
+++ b/test/mentions-policy-aliases.test.ts
@@ -0,0 +1,114 @@
+/**
+ * Entity mention index, pure layer: the pack-aware linkable-type resolver
+ * (mentions/policy.ts) and derived alias extraction (mentions/aliases.ts).
+ *
+ * Protects: which page types become linkable entities per bundled pack (a
+ * `type: crm` page links under the init-default pack, `product` never does,
+ * the four legacy types always do) and which names an entity page
+ * contributes (title subject, body declarations, private fences stripped,
+ * case-sensitive single-token codes, the first-word and length guards).
+ * Regression: a hard-coded type list again, a private code becoming a public
+ * alias, "also known as Quormiro Capital" adding "Quormiro".
+ */
+import { describe, expect, test } from 'bun:test';
+import { loadResolvedPackByName } from '../src/core/schema-pack/load-active.ts';
+import {
+ ALWAYS_LINKABLE_TYPES, canonicalTypeOf, linkableTypesFor, parseNameList, typeAliasPairs,
+} from '../src/core/mentions/policy.ts';
+import { aliasRejection, declaredNames, deriveEntityAliases, titleSubject } from '../src/core/mentions/aliases.ts';
+import { aliasDeclarations } from '../src/core/ops/search.ts';
+
+const none = { typeAdds: [], typeRemoves: [] };
+const pack = async (name: string) => (await loadResolvedPackByName(name)).manifest;
+
+describe('linkable entity types', () => {
+ test('gbrain-base-v2 (init default): account and its alias crm are linkable; product is not', async () => {
+ const types = linkableTypesFor(await pack('gbrain-base-v2'), none);
+ for (const t of ['person', 'company', 'organization', 'entity', 'account', 'crm', 'contact', 'startup']) expect(types).toContain(t);
+ expect(types).not.toContain('product');
+ expect(types).not.toContain('project');
+ expect(types).not.toContain('deal');
+ });
+
+ test('company-brain marks customer, competitor, supplier and distributor', async () => {
+ const types = linkableTypesFor(await pack('company-brain'), none);
+ for (const t of ['customer', 'competitor', 'supplier', 'distributor', 'entity']) expect(types).toContain(t);
+ });
+
+ test('legacy gbrain-base keeps its own entity types; no pack keeps the four', async () => {
+ const legacy = linkableTypesFor(await pack('gbrain-base'), none);
+ expect(legacy).toContain('person');
+ expect(legacy).not.toContain('account');
+ expect(linkableTypesFor(null, none)).toEqual([...ALWAYS_LINKABLE_TYPES].sort());
+ });
+
+ test('a type: entity page stays linkable under every bundled pack', async () => {
+ for (const name of ['gbrain-base', 'gbrain-base-v2', 'company-brain', 'gbrain-recommended', 'gbrain-everything']) {
+ expect(linkableTypesFor(await pack(name), none)).toContain('entity');
+ }
+ });
+
+ test('mentions.entity_types adds and removes, but never the four always-linkable types', async () => {
+ const v2 = await pack('gbrain-base-v2');
+ const types = linkableTypesFor(v2, { typeAdds: ['project'], typeRemoves: ['account', 'person'] });
+ expect(types).toContain('project');
+ expect(types).not.toContain('account');
+ expect(types).toContain('person');
+ });
+
+ test('config lists parse as JSON arrays or comma lists', () => {
+ expect(parseNameList('["+project", "-account"]')).toEqual(['+project', '-account']);
+ expect(parseNameList('Acme, Widget Co\nfund-a')).toEqual(['Acme', 'Widget Co', 'fund-a']);
+ expect(parseNameList(null)).toEqual([]);
+ });
+
+ test('canonical type maps stored aliases through the pack; untyped pages group as untyped', async () => {
+ const v2 = await pack('gbrain-base-v2');
+ expect(canonicalTypeOf('crm', v2)).toBe('account');
+ expect(canonicalTypeOf('account', v2)).toBe('account');
+ expect(canonicalTypeOf('ticket', v2)).toBe('ticket');
+ expect(canonicalTypeOf('', v2)).toBe('untyped');
+ const pairs = typeAliasPairs(v2);
+ expect(pairs.canonical[pairs.stored.indexOf('crm')]).toBe('account');
+ });
+});
+
+describe('derived aliases', () => {
+ test('title subject and a body code; the full title is not repeated', () => {
+ const { aliases } = deriveEntityAliases({ title: 'CRM record: Quormiro Capital', compiled_truth: 'Account code: QUCO\nOwner: Dana' });
+ expect(aliases).toEqual([
+ { alias_norm: 'quormiro capital', alias_text: 'Quormiro Capital', origin: 'subject', case_sensitive: false },
+ { alias_norm: 'quco', alias_text: 'QUCO', origin: 'declared', case_sensitive: true },
+ ]);
+ expect(titleSubject('Acme Example')).toBeNull();
+ });
+
+ test('a code inside a private facts fence is never derived', () => {
+ const body = 'Account code: PUBL\n\n## Facts\n\n<!--- gbrain:facts:begin -->\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|---|---|---|---|---|---|---|---|---|\n| 1 | Ticker: SECR | fact | 1.0 | private | medium | 2026-01-01 | | test | |\n<!--- gbrain:facts:end -->\n';
+ const norms = deriveEntityAliases({ title: 'CRM record: Widget Co', compiled_truth: body }).aliases.map(a => a.alias_norm);
+ expect(norms).toContain('publ');
+ expect(norms).not.toContain('secr');
+ });
+
+ test('guards: 3-character code, first word of the own name, generic word', () => {
+ const r = deriveEntityAliases({ title: 'CRM record: Quormiro Capital', compiled_truth: 'Ticker: QCO. Also known as Quormiro Capital. aka Team' });
+ expect(r.aliases.map(a => a.alias_text)).toEqual(['Quormiro Capital']);
+ expect(r.rejected).toEqual(expect.arrayContaining([
+ { alias: 'QCO', origin: 'declared', reason: 'below_min_length' },
+ { alias: 'Quormiro', origin: 'declared', reason: 'ambiguous_first_word' },
+ { alias: 'Team', origin: 'declared', reason: 'generic_token' },
+ ]));
+ expect(aliasRejection('Grace', 'Grace Hopper-Example')).toBe('ambiguous_first_word');
+ });
+
+ test('"aka Mark" is a case-sensitive single-token alias', () => {
+ const [mark] = deriveEntityAliases({ title: 'Marcus Example', compiled_truth: 'Marcus, aka Mark, runs sales.' }).aliases;
+ expect(mark).toMatchObject({ alias_text: 'Mark', case_sensitive: true, origin: 'declared' });
+ });
+
+ test('search\'s declared-name fan-out reads the same parser', () => {
+ expect(declaredNames('Account code: QUCO.', 'Quormiro Capital')).toEqual(['QUCO']);
+ expect(aliasDeclarations([{ slug: 'crm/1', title: 'CRM record: Quormiro Capital', chunk_text: 'Account code: QUCO.' }], 'QUCO renewal'))
+ .toEqual([{ name: 'Quormiro Capital', alias: 'QUCO', slug: 'crm/1' }]);
+ });
+});
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index f3824b72a4..ee2f17b457 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -859,6 +859,13 @@ test('every CREATE INDEX column in PGLITE_SCHEMA_SQL is covered by CREATE TABLE
// ─────────────────────────────────────────────────────────────────
const COLUMN_EXEMPTIONS = new Set<string>([
+ // page_aliases origin / case_sensitive / alias_text (entity mention index,
+ // migration v201): page_aliases is a PGLite bootstrap table and a
+ // Postgres migration-only table; no schema blob references these columns
+ // (no index or view reads them), so there is nothing to forward-reference.
+ 'page_aliases.origin',
+ 'page_aliases.case_sensitive',
+ 'page_aliases.alias_text',
// takes.embedding: the takes table is migration-only (no CREATE TABLE in
// PGLITE_SCHEMA_SQL / src/schema.sql), so there is no schema-blob forward
// reference for the bootstrap to trip on. The column is created inline in
diff --git a/test/schema-cli-db-config.serial.test.ts b/test/schema-cli-db-config.serial.test.ts
index 2f80578a54..a0a97aa1b5 100644
--- a/test/schema-cli-db-config.serial.test.ts
+++ b/test/schema-cli-db-config.serial.test.ts
@@ -61,7 +61,7 @@ describe('#4653 schema inspection verbs honor DB-config schema_pack (tier 4)', (
test('schema show prints the DB-configured pack header', () => {
const r = runSchema('show');
expect(r.status).toBe(0);
- expect((r.stdout ?? '').split('\n')[0]).toBe('# gbrain-base-v2 v1.2.0');
+ expect((r.stdout ?? '').split('\n')[0]).toBe('# gbrain-base-v2 v1.3.0');
}, 90_000);
test('schema explain <v2-only type> exits 0', () => {
diff --git a/test/schema-cli.test.ts b/test/schema-cli.test.ts
index e4a06e9d7a..304130c13e 100644
--- a/test/schema-cli.test.ts
+++ b/test/schema-cli.test.ts
@@ -130,7 +130,8 @@ describe('gbrain schema CLI (Phase C)', () => {
expect(r.exitCode).toBe(0);
// v1.2.0 (v0.47 open-loop engine): +owes_to +awaiting_reply_from — 15
// link verbs became 17. (#2117 history: 14 became 15 with `advises`.)
- expect(r.stdout).toContain('gbrain-base-v2 v1.2.0');
+ // v1.3.0 (entity recall): +account page type (alias crm).
+ expect(r.stdout).toContain('gbrain-base-v2 v1.3.0');
expect(r.stdout).toContain('Page types (');
expect(r.stdout).toContain('Link verbs (17)');
});
diff --git a/test/schema-pack-stats.test.ts b/test/schema-pack-stats.test.ts
index 01637f59b6..929105a15c 100644
--- a/test/schema-pack-stats.test.ts
+++ b/test/schema-pack-stats.test.ts
@@ -339,7 +339,7 @@ describe('runStatsCore — #4653 DB-plane schema_pack tier', () => {
await engine.setConfig('schema_pack', 'gbrain-base-v2');
const result = await runStatsCore(ctxOf());
// Pre-fix: loadActivePackBestEffort never read the engine → '[email protected]+…'.
- expect(result.pack_identity).toStartWith('[email protected]');
+ expect(result.pack_identity).toStartWith('[email protected]');
});
});
});