Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Non-ranking amends link and link-type ranking participation policy

garrytanfa759083ff23
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f87d752f54..0aade22d11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,12 @@ 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).
+## [Unreleased: cat40 next wave part 1, version stamped at merge] - 2026-10-12
+
+- **A record can say it amends another without changing how either ranks.** A schema pack declares `amends` (`temporal: event`) and maps it from frontmatter per page type, so `amends: [{name, since}]` links the amendment to the record it changes and records when the new terms take effect (`link_relationships.first_start`). Amends edges are references only: every link-counting ranking reader skips them through one policy (`src/core/link-ranking-policy.ts`): backlink, in-set and cross-source adjacency boosts, relational fanout and chain hops, chain hub degree, enrich inbound order, entity-resolution connection count, generated-page demotion and entity anchoring. `get_links`, `get_backlinks`, `traverse_graph`, card edges, `backlink_count` and `referenced_by` still return them, and `supersedes` keeps its 0.5 down-rank for whole-record replacement. An amends edge whose `since` is still ahead is never hidden by the default liveness filter (`LIVENESS_EXEMPT_LINK_TYPES` in `src/core/link-validity.ts`), and card edges rank it beside events. Example pack: `examples/schema-packs/amends-example/pack.yaml`; guide: [amendments](docs/guides/temporal-edges.md#amendments-the-amends-link); existing pages pick it up with `gbrain extract links --source db --include-frontmatter`.
+- **Frontmatter `since`/`until` dates only the exact target when several objects match.** `src/core/link-temporal-evidence.ts` still accepts a slug-prefix name (`Acme` for `acme-example`) when it is the only match, but when several objects in one field match one target only the exact name dates it, so `{name: MSA Example}` no longer dates `msa-example-renewal`.
+- Tests: `test/amends-link.test.ts` (PGLite) and `test/e2e/amends-link-postgres.test.ts` (Postgres) share `test/helpers/amends-ranking-scenarios.ts`: one final-output invariance row per link-counting consumer, each with a ranking-type control that crosses its threshold; amendments versus `supersedes` through final search scores and labels; frontmatter `since` per exact target; and a frozen-clock check that a future-`since` amends edge stays in `get_backlinks`, `traverse_graph` and card edges. `test/link-temporal-evidence.test.ts` adds the prefix-sharing target pair.
+
## [0.60.180.0] - 2026-10-12
**When `remember` refuses a forgotten claim, the refusal now says when and how widely it was forgotten.** An agent that re-saves a claim the user forgot gets `fact_withdrawn` as before, and the refusal now carries `withdrawn: { at, subject, visibility }`, where `subject` is the entity the claim was forgotten for or `all_entities`. The agent can tell the user "you asked me to forget that on <date>" instead of retrying. The object rides the immediate refusal, the batch item error, the failed write receipt and `get_write_request`. It covers the exact claim only, the message, code and suggestion are unchanged, and nothing is ever restored.
diff --git a/docs/architecture/RETRIEVAL.md b/docs/architecture/RETRIEVAL.md
index a255d1fc45..7bdc323e16 100644
--- a/docs/architecture/RETRIEVAL.md
+++ b/docs/architecture/RETRIEVAL.md
@@ -427,6 +427,15 @@ relational re-pin and the page-1 evidence slot; intermediate and origin pages
never claim them. The planner keys fold into the query-cache key only when on
(`rp=1`, `ro=1`). Guide: [multi-hop relationship questions](../guides/multi-hop.md).
+### Link types that take no part in ranking
+
+Every reader that turns links into a ranking signal (backlink and adjacency
+boosts, relational fanout and chain hops, chain hub degree, enrich order,
+canonical entity picks, generated-page demotion, entity anchoring) skips the
+link types in `NON_RANKING_LINK_TYPES` (`src/core/link-ranking-policy.ts`):
+today `amends`. Those edges stay ordinary references in graph reads and cards.
+Guide: [amendments](../guides/temporal-edges.md#amendments-the-amends-link).
+
### Metadata boost gate: vector-only voters keep the vector order
The post-fusion metadata boosts (backlink, salience, recency + chronicle,
diff --git a/docs/architecture/key-files/commands-3.md b/docs/architecture/key-files/commands-3.md
index 9e6dcdd07d..e35b0ac442 100644
--- a/docs/architecture/key-files/commands-3.md
+++ b/docs/architecture/key-files/commands-3.md
@@ -5,7 +5,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/engine-status.ts` — `gbrain engine status [--json] [--probe] [--brain <id>]`: the ENGINE-FREE detection primitive (CLI_ONLY, dispatched in handleCliOnly BEFORE connectEngine like pglite-repair; deliberately NOT an operations.ts op — an MCP server can't serve a status call when its DB is down). Zero round-trips without `--probe`: reports (JSON `schema_version: 1`) `effective_engine` vs `config_file_engine` (can differ under a transient env URL), `db_url_source`, env-shadow + both-env-URLs precedence note, redacted URLs only, brain id from the engine-free resolver (NOT `get_brain_identity`, which needs an engine), thin-client flag, and a Postgres pooler block (supabase-pooler detection, `resolvePrepare`, direct/session-pooler derivability, `GBRAIN_DISABLE_DIRECT_POOL`, pool sizes). `--brain <id>`/mount resolution reports the MOUNT's engine/URL, never the host's. `--probe` is a SINGLE bounded connect + `SELECT 1` (the driver's built-in `connect_timeout` — never a custom race; `noRetry`, never the 3-attempt ladder); Postgres success also reports `ConnectionManager.describeMode()`; failure returns a classified `PgAccessDiagnosis`. PGLite probe is LOCK-AWARE: a live serve holding the single-writer data-dir lock reports `locked_by_serve` (healthy-with-note) instead of hanging ~30s and misreporting a healthy brain. Exit 0 healthy, 1 on config diagnosis or failed probe, 2 on flag errors. Pinned by `test/engine-status.test.ts`.
-- `src/commands/enrich.ts` + `src/core/enrich/thin.ts` + `src/core/cycle/enrich-thin.ts` — `gbrain enrich --thin`: batch-develops stub (thin) pages via **brain-internal grounded synthesis**. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONE `gateway.chat` call per page; web research stays the agent-driven `enrich` SKILL's job. `runEnrichCore(engine, opts, signal)` refuses managed mutation before provider work until its resume cursor can retain prepared writes (dry-run remains available); legacy writes expose pending/failed request IDs. It is strict per-source (multi-source iteration is the caller's job) and drives `enrichOne` per candidate: `withRefreshingLock('enrich:<src>:<slug>')` → coherent `readPageSnapshot` (content, tags, revision) → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized via `INJECTION_PATTERNS`) → `assessGrounding` gate (skip < `MIN_CONTEXT_CHARS`, no LLM) → `buildEnrichPrompt` (grounded dossier, `[Source: slug]` citations, SKIP sentinel) → synth → `put_page` handler (`remote:false`, observed revision and caller-allocated request UUID, atomic projections and receipt) stamping `enriched_at` + `enriched_by:'cli:enrich'`. Candidate selection is the SQL-native `engine.listEnrichCandidates(opts)` (`src/core/engine.ts` interface + `EnrichCandidate`/`EnrichCandidatesOpts`/`ENRICH_ORDER_SQL` in `src/core/types.ts` + pg/pglite impls): thin-filter + per-page source-correct inbound count (`to_page_id = p.id`, `mentions` excluded) + `enriched_at` recency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume via `src/core/op-checkpoint.ts` (local `enrichFingerprint`); budget via `BudgetTracker` + `withBudgetTracker` (best-effort under `--workers > 1` — `runSlidingPool` aborts new claims on `BUDGET_EXHAUSTED` but does NOT cancel in-flight `gateway.chat`; pin `--workers 1` for a hard ceiling). `sanitizeContext` (thin.ts) neutralizes the `<context>…</context>` data-envelope delimiters (injection escape, mirrors the `</trajectory>` convention); `--background` asks consent first and stores a spend group; the `--background` multi-source fan-out idempotency key carries the run fingerprint via exported `backgroundIdempotencyKey(sid, args)` (a bare `enrich:${sid}` would return stale completed jobs); `runEnrichCore` flags `budget_exhausted` post-hoc when `tracker.totalSpent > tracker.cap` even when the gateway swallowed the final-call throw (via read-only `BudgetTracker.cap` getter); `body()` flushes the checkpoint on `BudgetExhausted` before it propagates so resume doesn't re-charge. The opt-in `enrich_thin` cycle phase (default OFF via `cycle.enrich_thin.enabled`) trickles `max_pages_per_tick` (default 3) per source with per-source cost cap enforced as `min(per_source_cap, brain_wide_remaining)` + brain-wide total + walltime caps. Wired into `cycle.ts` (`CyclePhase`/`ALL_PHASES` between `conversation_facts_backfill` and `skillopt`/`embed`; `PHASE_SCOPE='source'`; `NEEDS_LOCK`; dispatch), `cli.ts` (`CLI_ONLY` + `CLI_ONLY_SELF_HELP` + `THIN_CLIENT_REFUSED_COMMANDS` + dispatch), `jobs.ts` (Minion `enrich` handler, strict per-source, NOT in `PROTECTED_JOB_NAMES`). DI seam `opts.synthesizeFn` keeps tests hermetic (no API key, no mock.module). Pinned by `test/enrich/thin.test.ts`, `test/enrich/idempotency.test.ts`, `test/enrich-cycle-phase.test.ts`, `test/e2e/enrich-pglite.test.ts` (grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance), `test/e2e/engine-parity.test.ts` (`listEnrichCandidates` pg↔pglite parity).
+- `src/commands/enrich.ts` + `src/core/enrich/thin.ts` + `src/core/cycle/enrich-thin.ts` — `gbrain enrich --thin`: batch-develops stub (thin) pages via **brain-internal grounded synthesis**. gbrain's model tooling sees only brain-internal context (search / get_page / facts / backlinks), not the web, so enrich consolidates what the brain ALREADY knows about an entity (scattered across meetings, other pages, deals, facts) into one cited page via ONE `gateway.chat` call per page; web research stays the agent-driven `enrich` SKILL's job. `runEnrichCore(engine, opts, signal)` refuses managed mutation before provider work until its resume cursor can retain prepared writes (dry-run remains available); legacy writes expose pending/failed request IDs. It is strict per-source (multi-source iteration is the caller's job) and drives `enrichOne` per candidate: `withRefreshingLock('enrich:<src>:<slug>')` → coherent `readPageSnapshot` (content, tags, revision) → deterministic retrieve (hybridSearch + getBacklinks + facts + raw_data, source-scoped, sanitized via `INJECTION_PATTERNS`) → `assessGrounding` gate (skip < `MIN_CONTEXT_CHARS`, no LLM) → `buildEnrichPrompt` (grounded dossier, `[Source: slug]` citations, SKIP sentinel) → synth → `put_page` handler (`remote:false`, observed revision and caller-allocated request UUID, atomic projections and receipt) stamping `enriched_at` + `enriched_by:'cli:enrich'`. Candidate selection is the SQL-native `engine.listEnrichCandidates(opts)` (`src/core/engine.ts` interface + `EnrichCandidate`/`EnrichCandidatesOpts`/`ENRICH_ORDER_SQL` in `src/core/types.ts` + pg/pglite impls): thin-filter + per-page source-correct inbound count (`to_page_id = p.id`, `mentions` and non-ranking link types excluded) + `enriched_at` recency guard + whitelisted ORDER BY + LIMIT, lightweight projection (NO bodies). Resume via `src/core/op-checkpoint.ts` (local `enrichFingerprint`); budget via `BudgetTracker` + `withBudgetTracker` (best-effort under `--workers > 1` — `runSlidingPool` aborts new claims on `BUDGET_EXHAUSTED` but does NOT cancel in-flight `gateway.chat`; pin `--workers 1` for a hard ceiling). `sanitizeContext` (thin.ts) neutralizes the `<context>…</context>` data-envelope delimiters (injection escape, mirrors the `</trajectory>` convention); `--background` asks consent first and stores a spend group; the `--background` multi-source fan-out idempotency key carries the run fingerprint via exported `backgroundIdempotencyKey(sid, args)` (a bare `enrich:${sid}` would return stale completed jobs); `runEnrichCore` flags `budget_exhausted` post-hoc when `tracker.totalSpent > tracker.cap` even when the gateway swallowed the final-call throw (via read-only `BudgetTracker.cap` getter); `body()` flushes the checkpoint on `BudgetExhausted` before it propagates so resume doesn't re-charge. The opt-in `enrich_thin` cycle phase (default OFF via `cycle.enrich_thin.enabled`) trickles `max_pages_per_tick` (default 3) per source with per-source cost cap enforced as `min(per_source_cap, brain_wide_remaining)` + brain-wide total + walltime caps. Wired into `cycle.ts` (`CyclePhase`/`ALL_PHASES` between `conversation_facts_backfill` and `skillopt`/`embed`; `PHASE_SCOPE='source'`; `NEEDS_LOCK`; dispatch), `cli.ts` (`CLI_ONLY` + `CLI_ONLY_SELF_HELP` + `THIN_CLIENT_REFUSED_COMMANDS` + dispatch), `jobs.ts` (Minion `enrich` handler, strict per-source, NOT in `PROTECTED_JOB_NAMES`). DI seam `opts.synthesizeFn` keeps tests hermetic (no API key, no mock.module). Pinned by `test/enrich/thin.test.ts`, `test/enrich/idempotency.test.ts`, `test/enrich-cycle-phase.test.ts`, `test/e2e/enrich-pglite.test.ts` (grew-cited, skip, ordering, multi-source, recency, resume, budget abort + checkpoint flush, final-call overage, lock-skip, provenance), `test/e2e/engine-parity.test.ts` (`listEnrichCandidates` pg↔pglite parity).
- `src/commands/eval-compare.ts` — `gbrain eval compare [--suite S] [--modes ...] [--runs ...] [--baseline RUN_ID --candidate RUN_ID] [--draws N] [--seed N] [--md|--json] [--input PATH]`. Reads the run ledger `<repo>/.gbrain-evals/eval-results.jsonl`, keeps the newest record per (suite, mode) and renders the mode table plus any aggregate `metrics`. Paired statistics come only from per-query rows: a record whose `params.output` names its per-question JSONL (`gbrain eval longmemeval --record --output`) is joined with its pair on `question_id`, and each per-query metric both rows carry (`recall_all@k`, `recall_any@k`, `qa_accuracy` from `judge_correct`) gets a paired cluster bootstrap 95% CI, a two-sided sign-flip p-value and a Holm p-value across the report's comparisons (`src/core/eval/paired-bootstrap.ts`). Pairs are every mode pair in a suite, or exactly `--baseline`/`--candidate`. Significant means Holm p ≤ 0.05 and a CI that excludes 0. A `params.output` path must resolve inside the repository root after following symlinks (`pathWithinRoot`); a `..`, absolute or symlinked path outside it is refused and never read. Runs without rows are listed in `paired_unavailable`, and a report with no comparisons says it is aggregate-only; `_meta.methodology` describes only what was computed. Pinned by `test/eval-compare.test.ts`.
diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.md
index a15332a8ed..d76c8cc982 100644
--- a/docs/architecture/key-files/core-search-1.md
+++ b/docs/architecture/key-files/core-search-1.md
@@ -73,6 +73,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/query-intent.ts` — Deterministic query classifiers (pure, no LLM): `classifyQuery`/`classifyQueryIntent` (entity/temporal/event/concept/general → auto-selects detail level, salience/recency/modality axes; `concept` fires on definitional-paraphrase OR landscape/quantifier cues with a proper-noun name-guard — capitalized names, quoted phrases, slugs, and sub-3-word queries never trigger — and ranks vector-lean via the RRF-k tilt in `intent-weights.ts`), `isAmbiguousModalityQuery` (LLM-escalation gate), and the concept-shape pair — `looksConceptShaped` (fuzzy-quantifier/landscape cues minus exact-identifier anti-signals, tuned to favor false-negatives; cues owned by other routers like "who are the"/find_experts and bare "anything"/salience are deliberately excluded) + `conceptNudge` (full one-line CLI hint string steering a concept-shaped `search` toward `query`; consumed by `maybePrintConceptNudge` in `src/cli.ts` on BOTH the local-engine and thin-client result paths, stderr-only, `--quiet`-gated). Pinned by `test/query-intent-concept.test.ts` + `test/cli-concept-nudge.test.ts`.
-- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults. `readChainHop` (behind `BrainEngine.relationalChainHop`) is one oriented, authorized, bounded expansion step of a multi-hop chain: fenced LATERAL link scans and primary-key page lookups (a statistics-less planner otherwise joins pages on source_id quadratically), relationship page-type signatures (`stored` / `flipped` / `uncertain`; frontmatter, manual and attendance-section links keep stored direction), logical-edge collapse, `neighborCap` per frontier page, degree saturating at `CHAIN_DEGREE_SATURATION` (300) link rows, and edge context only from pages whose text the caller may read. Pinned by `test/relational-chain.test.ts`, `test/relational-chain-hub.slow.test.ts` and the engine-parity chain case.
+- `src/core/search/read-enrichment.ts` — narrow query helpers shared by PGLite and Postgres. Recursive relational reads authorize seeds, hops and link origins before limits; seed identity constraints remain separate from caller grants. Batched IDs or `(source_id, slug)` pairs authorize backlinks (counted as DISTINCT linking pages: no self-links, no duplicate edges, mentions excluded; a read policy also requires live, authorized contributors), adjacency, dates, flags, extraction state and take-derived salience. Restricted holders use permitted active takes and zero stored emotional-weight contribution; required expert admission runs after optional enrichment, uses an authorized effective-date map and propagates query failures. Callers omit failed optional signals or apply their existing neutral defaults. Backlink counts, adjacency, relational fanout, chain hops and chain degree skip non-ranking link types (`rankingLinkSql`, `src/core/link-ranking-policy.ts`). `readChainHop` (behind `BrainEngine.relationalChainHop`) is one oriented, authorized, bounded expansion step of a multi-hop chain: fenced LATERAL link scans and primary-key page lookups (a statistics-less planner otherwise joins pages on source_id quadratically), relationship page-type signatures (`stored` / `flipped` / `uncertain`; frontmatter, manual and attendance-section links keep stored direction), logical-edge collapse, `neighborCap` per frontier page, degree saturating at `CHAIN_DEGREE_SATURATION` (300) link rows, and edge context only from pages whose text the caller may read. Pinned by `test/relational-chain.test.ts`, `test/relational-chain-hub.slow.test.ts` and the engine-parity chain case.
- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.md
index c586397b33..72dadfce47 100644
--- a/docs/architecture/key-files/core-search-2.md
+++ b/docs/architecture/key-files/core-search-2.md
@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/evidence-delivery.ts` — the `return_unit` evidence assembler (default `auto`: conversation pages by type or `chat/`/`conversations/` slug come back whole under `search.return_budget_conversation` (24,000), every other hit is its unchanged chunk; `effectivePlan` skips the stage when an implied `auto` sees no conversation hit, so that path and `chunk` stay byte-identical). `resolveEvidencePlan` validates `return_unit` / `return_window` (invalid_params naming the allowed values and an example), reads `search.return_unit` / `think.return_unit`, `search.return_window`, `search.return_budget_default` (6,000), `search.return_budget_conversation` (24,000) and clamps remote budgets to `search.return_budget_max_remote` (32,000, reported). Snippet precedence: explicit `snippet_chars` > explicit `return_unit` > subagent default cap > config unit. `deliverEvidence` groups hits by page_id (one block per page at its best rank), makes ONE `engine.getChunkWindows` call (re-authorizes every page; unauthorized pages are dropped, never served from hit text), builds the page text from the stored body sanitized whole and passed through `credentialSafeProjection` before slicing (`pageEvidenceText`: compiled truth + serializer timeline sentinel + timeline; frontmatter excluded; private-key spans become newline-padded `<REDACTED:private_key_pem>` tokens, the same text the chunkers cut from), locates the hit chunks in it (`locateChunks`: exact, then whitespace-insensitive, since the chunker trims and folds whitespace), cuts `window` / `section` (ATX headings outside code fences, or conversation rounds detected structurally, never by page type) / `page` / `auto` (fenced-code hits are placed by their code minus the chunker's synthesized header), counts tokens as the sum of per-line cl100k counts, reserves each page's matching span before enriching by rank, caps blocks at 60,000 characters, redacts secrets before final accounting, and returns NEW rows with `delivered` plus a `delivery` meta. The plan records `budgetExplicit` (the caller passed the budget) and the resolved `packing` (`search.auto_packing` or the library override); `capEngaged` (unit `auto`, explicit budget, packing not `off`) routes allocation to `allocateCapped`: global rank one first (cut with `EVIDENCE_CUT_MARKER` when it alone exceeds the budget), the rank-order prefix of other non-conversation chunks that fits (rest `budget_note`), then conversations by `cap_only` (floors, then enrichment), `breadth_capped` (longest prefix whose title + floor + `return_window` target window fits; rest `breadth_cap`) or `depth_first` (each session grown in turn); nothing spills. `capEvidenceToBudget` recounts title + `chunk_text` at the final boundary (after redaction and `capDeliveredSnippets`, whose marker is paid from the row's own allocation) and rewrites `budget_used`. Without an explicit budget none of this runs and the bytes are the pre-cap path's. Fetch failure/timeout (5 s) falls back to the hit chunk only for live hits. `assembleEvidenceForHits` / op `assemble_evidence` deliver the exact evidence `query` returns for a frozen `(source_id, slug, chunk_id)` list, `effective_date` included (`applyEffectiveDate`, the live rows' normalizer); `evidenceFingerprint` hashes it (gbrain-evals E1/E3 parity). With `search.evidence_date_header` on (`plan.dateHeader`), each block (including `auto` passthrough chunks) starts with its one-line date header from `evidence-date.ts`, reserved in the block floor like the title, counted in `delivered.tokens`, with spans shifted past it and `delivery.date_header: true`; a failed date read renders `unknown` and adds `date_header_unavailable`. Normative spec: `docs/evidence-delivery.md`. Tests: `test/evidence-delivery.test.ts`, `test/evidence-delivery-golden.test.ts`, `test/e2e/evidence-delivery-leak.test.ts`, `test/e2e/evidence-delivery-parity.test.ts`; bench `scripts/bench-evidence-delivery.ts`.
- `src/core/search/evidence-date.ts` — C1 dated evidence blocks: the fixed header grammar (`[observed YYYY-MM-DD|unknown]` for page blocks; `[observed unknown; valid FROM to UNTIL]` for `recall` facts), `pageObservationDate` (effective-date precedence with `event_date` removed and no row-timestamp fallback; mirrors #6020's `resolveObservationDate`, the seam to swap once it lands), `formatBrainDay` from `effective-date.ts` (midnight UTC renders as written, other instants in `brain.timezone`; the one function think's `<page date>` also renders through, while the header's `observed` stays when the text was said, never the content date), `loadPageDateHeaders` (one `pages` read per delivery; only the derived day leaves it) and `evidenceDateHeaderEnabled` (`search.evidence_date_header`, default off). Tests: `test/evidence-date-header.test.ts`.
-- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.
+- `src/core/search/entity-anchor.ts` — entity-anchored retrieval: `entityAnchoredPages` (the entity page plus up to 10 pages that link to it by a ranking link type or name it as a word, newest by `COALESCE(effective_date, updated_at)`; question/synthesis/pinned-question pages excluded) and `prefixAnchoredPages`, shared by pinned-question refresh (`questions/refresh.ts` `anchoredSlugs`) and the `query`/`search` ops; `asksForCurrentState` (deterministic cue regex), `namedEntity` (exactly one `isFactEntityPage` page whose title `isTitleMentionedInQuery` matches, the title match before the read-policy filter; a title inside a longer matched title is the same mention); `applyEntityAnchoring` (anchored rows first, at most half the row count, organic rows of the same page moved up, missing pages read through `getChunkWindows` under the caller's scope, rows stamped `entity_anchored`, token budget re-applied, fail-open); `entityAnchoringEnabled` (`search.entity_anchoring`, default off). Tests: `test/search-entity-anchor.test.ts`. Gates: `docs/eval/decisions/entity-anchoring-query/`.
- `src/core/search/facts-arm.ts` — the `query` facts arm behind `search.query_facts_arm` (default on since gates 1b and 2 passed; `false` turns it off). `matchQueryFacts` reads the candidate pool from `fact-relevance.ts` (active facts under recall's read policy) and matches them by query-embedding cosine (`FACT_COSINE_MIN` 0.6, the embedding `hybridSearch` already computed, via `HybridSearchOpts.onQueryEmbedding`) or by query-term share (half the terms, substring match) or a named entity (in that page's source), newest `valid_from` first, at most `MAX_FACT_ROWS` (3). `applyFactsArm` adds them as `fact_row` rows in spare capacity only: free slots under the caller's row count, and whole rows that fit in what the page rows leave of the token budget; a page row is never displaced `factRowOutput` strips page fields (slug, id, type, chunk_id) from fact rows on output, leaving `result_type: 'fact'`, `fact_id`, `follow_up` (`recall` by entity, or `grep` without one) and `page_slug` when the caller can read the entity page (`readableEntityPages`); and stamps `superseded_claim` on page rows whose typed `claim_metric` (plus `claim_period` when both carry it) a newer active fact covers. No model call. Tests: `test/search-facts-arm.test.ts`. Gates and verdict: `docs/eval/decisions/query-facts-arm/`. Temporal fact reserve: `applyTemporalFactReserve` behind `search.temporal_fact_reserve` (default off): `hasTemporalCue` (the preregistered word, phrase, ISO date and month-name regex), candidates from `collectFactCandidates` (50 cosine, 50 keyword, 20 entity facts, cosine for every candidate), scored and ordered by the shared `scoreFactCandidates` and kept by its `reserve` admission rule (fail-open on any error), packed into 15% of the token budget and 30% of the row count (1-20), rendered as fact rows whose text starts with `factDateHeader` (evidence delivery adds no second header), oldest first after the pages. Tests: `test/search-temporal-fact-reserve.test.ts`. Gates: `docs/eval/decisions/temporal-fact-reserve/`.
- `src/core/search/fact-relevance.ts` — question relevance for saved facts, shared by recall's `question` (`facts/question-recall.ts`), the temporal fact reserve and (pool only) the facts arm. `collectFactCandidates`: one bounded pool under recall's read policy (source scope, active and not superseded, audit rows excluded, quarantine and rederive hiding through `projectionEligibleSql`, the trust floor, remote world-only, `privateProvenanceFilterFragment` when `excludePrivate`) plus recall's filters inside every arm before its LIMIT (`(source_id, entity_slug)` pairs, `source_session`, event-time since, escaped `ILIKE` grep); arms, run concurrently and merged in a fixed order, are keyword FTS (`factsFtsDocument`, served by `idx_facts_fts`), cosine (cast to the facts column type, filtered on model only so the HNSW index serves it, a stale hash or other dimensions yielding no similarity; `ef_search` sized to the depth and pgvector's iterative scan when `hnswIterativeScan` is set) and the named entity page's facts in its own source; depths are bound parameters; `cosineForAll` scores every candidate's cosine whichever arm found it. A missing embedding column or other dimensions skips the cosine arm; any other DB error throws. `scoreFactCandidates`: cosine + whole-word term share + 0.1 when dated, the share's denominator growing past `TERM_STUFFING_RATIO` times the question's terms for a long fact; order score, newest valid_from, id. `admitted`: the `reserve` rule (cosine >= 0.5 or share >= 0.34) or the `facts_arm` rule (cosine >= 0.6, half the terms, or the named entity). `countUncomparableFacts` counts the pool's facts the cosine arm cannot compare, per source: candidates from `idx_facts_unembedded` and `idx_facts_embedding_model` first, the read policy on those rows only. The keyword arm and the count run under `customPlan` (`plan_cache_mode = force_custom_plan` in a transaction): a cached generic plan cannot see the source arrays and nests the policy anti-joins over every match. p95 at 100k facts: Postgres 51 ms local / 65 ms remote, PGLite 152 / 139 ms. Tests: `test/fact-relevance.test.ts`, `test/recall-question.test.ts`.
- `src/core/search/query-arms.ts` — `applyQueryArms`: the `query` op's post-retrieval arms in order (entity anchoring, then the facts arm), each behind its own key (entity anchoring default off, the facts arm default on); a temporal-cue query with a token budget takes the temporal fact reserve instead of the facts arm when `search.temporal_fact_reserve` is on; with all off it returns the rows untouched.
@@ -26,7 +26,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain.
- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.
-- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.
+- `src/core/link-ranking-policy.ts` — the link-type ranking participation policy: `NON_RANKING_LINK_TYPES` (`amends`), `linkTypeRanks`, and `rankingLinkSql(alias)`, the inlined predicate every link-counting ranking reader applies (read-enrichment backlinks, adjacency, fanout, chain hops and degree; enrich inbound order; entity-resolution connection count; generated-page demotion; entity anchoring). Reference reads (graph ops, cards, `backlink_count`, referrers) keep these edges. Tests: `test/amends-link.test.ts` (+ Postgres twin), one invariance row per consumer.
+- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it by a ranking link type, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.
- `src/core/search/sql-ranking.ts` — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash is Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text. `buildBestPerPagePoolCte(...)` is the shared per-page max-pool CTE both engines' `searchVector` inject — instead of returning the single best chunk per page from an inner `ORDER BY embedding <=> vec LIMIT N` (which lets a page lose to a neighbor on ONE weak chunk while its strong chunk sits just below the inner cut), the CTE pools the BEST chunk score per `(source_id, slug)` composite key so a page surfaces on its strongest evidence; composite key (not bare slug) keeps multi-source brains correct; single source of truth so the two engines can't drift.
- `src/core/search/keyword-chunk-match.ts` — `buildKeywordChunkMatch(ftsLang, excludePrivate)`: the chunk side of `PostgresEngine.searchKeyword`'s statement (FROM source for `cc`, the full-text match, the `modality = 'text'` filter). For excludePrivate callers it puts the match in an `OFFSET 0` subquery the planner plans on its own: the private-visibility subplans otherwise inflate every join plan's cost so a cheaper bitmap scan fell within the planner's 1% fuzz of a serial seq scan that detoasts every chunk's `search_vector` (~1.1 s → ~0.2 s for a common term at 250k chunks). Local callers keep the unfenced join, which can plan in parallel (an OFFSET subquery forbids that). PGLite does not use it. Pinned by `test/search/keyword-arm-ranking.test.ts` and `test/e2e/keyword-arm-ranking-postgres.test.ts`.
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index c67094fa0e..d8372bafd7 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -17,7 +17,7 @@ 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, 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_TEST_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. `context_pack` cards add `newer_mentions` (next entry). 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/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, live first, then events, references and liveness-exempt `amends`, then ended, 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_TEST_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. `context_pack` cards add `newer_mentions` (next entry). 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/mentions/newer-mentions.ts` — `readNewerMentions(engine, sourceId, slug, {excludePrivate, keepVisibility, charBudget, eligibility, includeQuarantined})`: the entity page's `COALESCE(effective_date, updated_at)`, then `readReferrerPage` (limit `NEWER_MENTIONS_CAP` 8, the card's own source, its private-page and private-origin filters) cut to referrers dated after it, newest first, within `NEWER_MENTIONS_CARD_CHARS` (2,000) of rendered rows; `more` when further newer referrers exist; null when none or on any read failure. #5575: the pack passes its proactive eligibility and authorized `include_quarantined`; `renderNewerMentionRow` labels each preview with its page's trust fields (`renderTrustedInline`; a quarantined one as external data). `isNewerMentionsEnabled` reads `mentions.newer_on_cards` (unset = on). `assemblePack` (`src/core/context/turn-context.ts`) reads them after cards and hot facts under the pack deadline and `NEWER_MENTIONS_PACK_CHARS` (6,000), `renderPack` puts them in a section after hot memory, and the `context_pack` op packs them last under `budget_tokens`. Test: `test/context-pack-newer-mentions.test.ts`.
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index ddde1acd0e..47292c3507 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -83,7 +83,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts `conventions/quality.md` and `_brain-filing-rules.md`). `extractTriggers()` delegates to the shared SKILL.md parser, so MECE gap detection and the trigger index agree on block lists, single-line flow sequences, wrapped flow sequences, and CRLF input. `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`. `parseResolverEntries` accepts BOTH the markdown table AND a compact list format (`- **skill-name**: trigger1 | trigger2 | trigger3` or `- skill-name: trigger1 | trigger2`); shapes can mix in one file, folded by the multi-resolver merge. Skill name MUST be kebab-lowercase (regex `[a-z][a-z0-9-]+`) so prose bullets like `- **Note**:`/`- **Convention**:`/`- **TODO**:` don't false-match as skill rows. `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`: an optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from the trigger but NOT honored as the path — two consumers (`routing-eval.ts:skillSlugFromPath`, the manifest lookup) assume the convention; use the table format for non-conventional paths. Multi-trigger rows fan out to one entry per trigger sharing the same `skillPath`; `checkResolvable` dedupes so the reachability count counts each skill once. Pinned by `test/check-resolvable.test.ts` (resolver shapes plus trigger array syntax cases) + `test/check-resolvable-openclaw-compact.test.ts` (8 cases over `test/fixtures/openclaw-compact-resolver/` and `test/fixtures/openclaw-mixed-merge/`). Tutorial: `docs/guides/scaling-skills.md` (three-tier scaling: ~300-skill agent to ~4K tokens/turn from ~25K). `checkResolvable(skillsDir, opts?)` takes an optional `skillsDirSource` (the detection tier from `autoDetectSkillsDir`, threaded by both callers: doctor.ts and the check-resolvable command; an explicit `--skills-dir` passes `null`). An `unreachable` issue downgrades from `error` to `warning` only when ALL hold: the directory was found via the ungated `cwd_walk_up` tier, no resolver file contributes rows (no `RESOLVER.md`; a generic `AGENTS.md` with zero table rows counts as absent), unreachable skills outnumber reachable ones, and no `manifest.json` exists on disk. This keeps a foreign tool's `skills/` dir walked up to from cwd from being scored as a broken gbrain skillpack, while a real skillpack (RESOLVER.md present, higher-confidence tier, dense trigger coverage, or any manifest.json, even a corrupted one) stays strict. A foreign dir with zero `triggers:` and no resolver file still hard-fails via the `missing_file` branch (separate follow-up).
-- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC`. Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities.
+- `src/core/entities/resolve.ts` — Free-form entity name → canonical slug resolution. `resolveEntitySlug(engine, source_id, raw)`: exact slug (slug-shaped input via `looksLikeSlug`: lowercase Unicode letters and numbers plus `/`, `_`, `-`, so non-Latin slugs match exactly) → alias-exact (an unambiguous `page_aliases` hit via `resolveAliases`, verified against LIVE pages since `page_aliases` has no FK — a stale alias row can never point at a deleted page; fail-open on pre-v110 brains missing the table; `ResolutionSource` reports `alias_exact`) → unique source-scoped full-basename match for multi-token names across people/companies/hosts/projects/concepts → unambiguous bare-name prefix expansion across `people/<token>-%` + `companies/<token>-%` (when several candidates share one directory, the single page titled exactly the bare name wins: "Acme" over "Acme Labs", gbrain-evals N9-5; cross-directory collisions and duplicate exact titles stay ambiguous) (tagged `prefix_expansion`, not `fuzzy_match`: the sole candidate is chosen by cardinality, so `facts/backstop.ts` appends an unverified-resolution note to the fact's context cell) → fuzzy candidates for multi-token input taken only when `sameEntityName` holds (same name tokens ignoring case, punctuation, order, accents and corporate suffixes), the candidate is an entity page (person/company/fund/org, host, project, concept or deal — never a meeting or note), and it is the only such candidate, so a near-name such as "Alicia Example" never lands on Alice and a person without a page never lands on a meeting page → deterministic `slugify` holding fallback. Bare-name collisions never use popularity as confidence. `isIdentityEntity(slug, type)` (person/company/fund/organization types or their directories) and `sameEntityName` are shared with `makeResolver`. The phantom-redirect helper takes a fuzzy hit only at trigram ≥ 0.7 with a 0.1 margin over the runner-up. Two helpers for the phantom-redirect pass: `resolvePhantomCanonical(engine, sourceId, phantomSlug)` SKIPS the exact-slug step (a phantom slug `'alice'` would exact-match itself and no-op the redirect); returns the canonical only when non-null AND contains `/`. `findPrefixCandidates(engine, sourceId, token)` is a standalone SQL query returning ALL candidates across `PREFIX_EXPANSION_DIRS` (hardcoded `['people', 'companies']`) via `slug LIKE ANY($N::text[])` over patterns `dir/token` + `dir/token-%`, cap of 10 ordered by `connection_count DESC, slug ASC` (non-ranking link types never count). Pinned by `test/entity-resolve.test.ts` (explicit, unique, ambiguous-person, and shared-token-company cases) plus `test/phantom-redirect.test.ts` (resolvePhantomCanonical 3 cases + findPrefixCandidates 6 cases incl. multi-dir ambiguity and the `people/aliceberg`-doesn't-match-`alice` false-positive guard). When a name resolves to two or three pages that form one identity-sibling group (`mentions/siblings.ts` `siblingCanonical`), the alias and basename arms of `resolveEntitySlugWithSource` and `resolveStrictEntityReference` return the group's lowest slug instead of an ambiguity or a fallback slug; `resolveStrictEntityReference` also accepts the source pack's linkable entity types (accounts, CRM records) as fact entities.
- `src/core/facts/subject-infer.ts` — zero-LLM fact subject inference shared by the write paths (remember, the facts backstop) and `gbrain facts relink`. `inferFactSubject(engine, sourceId, { fact, pageSlug?, mode, excludePrivate? })` returns `{ slug, via: 'page' | 'mention' }` or a miss reason (`ambiguous`, `unverified_match`, `no_mention`, `no_page`). Page tier: the trusted page the fact came from, when it is a live fact-entity page. Mention tier: strong `extractCandidates` names plus slugs written in the text, resolved through `resolveStrictEntityReference` (exact slug, unique basename, unique alias; `relink` mode adds the same-name trigram arm); exactly one entity links. Any other real name that does not resolve to the same entity (including names with no page and bare first names) vetoes the link; sentence-start capitals, weekdays/months and role terms (CEO, Q3) do not. `excludePrivate` removes private pages before uniqueness is counted. Also `appendContextNote`/`contextHead` (the `" — "` note convention), `recordedPageSlug` (page provenance of page-extraction rows only) and `isEntityInferenceEnabled` (`facts.entity_inference` kill switch for write-time inference; relink ignores it). `resolveStrictEntityReference` in `entities/resolve.ts` never guesses from a bare-name prefix and never slug-falls-back. Pinned by `test/facts-subject-infer.test.ts` (a 40+ fact labeled fixture: write precision >= 0.99, relink free tiers >= 0.95).
@@ -119,7 +119,7 @@ rejection of serve-only flags before a brain opens.
- `src/core/schema-pack/field-usage.ts` — `gbrain schema detect --fields`: per page type (top 50, up to 500 sampled pages each), frontmatter key, fact-category and relation-type usage; share 1 → required, >= 0.25 → optional. Identity and write-provenance keys are ignored. Read-only. Pinned by `test/schema-field-usage.test.ts`.
-- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-semantics-pack.ts` installs pack-declared `link_types[].temporal` semantics (union of the active and per-source packs, `state` wins) over the built-in table; `replaceDerivedLinks`, `add_link`/`remove_link` and the extract sweep prime it before deriving or refreshing state (lint rule `link_types_temporal`; `test/link-semantics-pack.test.ts`). `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.
+- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live; `LIVENESS_EXEMPT_LINK_TYPES` (`amends`) never hide outside `ended` reads). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-semantics-pack.ts` installs pack-declared `link_types[].temporal` semantics (union of the active and per-source packs, `state` wins) over the built-in table; `replaceDerivedLinks`, `add_link`/`remove_link` and the extract sweep prime it before deriving or refreshing state (lint rule `link_types_temporal`; `test/link-semantics-pack.test.ts`). `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.
- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. `list` reads `--status` and `--limit` as `--flag value` or `--flag=value`; `--limit` is a positive integer (`intFlagValue`, a bad or missing value is `invalid_params` before any query) capped at 1000 (`test/edge-proposals-list-flags.test.ts`). Budget through the cycle `BudgetMeter`. The CLI's `rows()` normalizes proposal ids at the row boundary (Postgres returns `bigint` as BigInt: a safe integer becomes a number, anything larger an exact string) and `--json` output also passes `bigintToStringReplacer`, so `list/show --json` never crash on Postgres (#6193). Pinned by `test/cycle-edge-contradictions.test.ts`, the managed phase matrix, `test/edge-proposals-json-bigint.test.ts` and `test/e2e/edge-proposals-json-postgres.test.ts`. `edge-proposals <sub> --help` prints usage before any engine read (router help, `src/cli/subcommands.ts`). #6311: a judge failure writes an `error` row whose detail is `attempt N/3; <class>: <message>` (provider keys, connection info and labeled credentials redacted, message ≤ 200 chars); skip-known treats it as known for 24 h (`updated_at`), then the pair is judged again and `recordProposal`'s upsert replaces only an `error` row; after `JUDGE_MAX_ATTEMPTS` (3) the detail reads `held after 3 attempts; …` and the pair is skipped until `gbrain edge-proposals retry <id> | --all-held` deletes the row (or the evidence hash changes). No migration. Pinned by `test/cycle-edge-contradictions.test.ts`.
- `src/core/link-single-value.ts` — declared single-value relations ([guide](../../guides/temporal-edges.md#declared-single-value-relations)). A pack's `cardinality: one_per_from` on a state relation, built in or declared `temporal: state` (manifest-v1 `LinkTypeSchema`; lint rule `link_types_cardinality` rejects it elsewhere) makes `edge_contradictions` close that type's competing live relationships without a model: `planSingleValueClosures` orders members by latest dated start and applies `closeContradiction` to each consecutive pair (undated and same-date members stay open as proposals). `declaredSingleValueTypes` reads the source's resolved pack; `previewSingleValue` backs the read-only `gbrain schema cardinality-preview`. `dream.single_value.mode` propose (default) / apply / off. Pinned by `test/link-single-value.test.ts`.
diff --git a/docs/guides/temporal-edges.md b/docs/guides/temporal-edges.md
index a230b40590..6583336313 100644
--- a/docs/guides/temporal-edges.md
+++ b/docs/guides/temporal-edges.md
@@ -70,7 +70,9 @@ the page states:
- **Frontmatter `since` / `until`** on relationship objects:
`company: [{ name: Acme, since: 2021-04, until: 2024-02-15 }]` (partial dates
normalize to the first day of the month or year). List the company twice for a
- rejoin.
+ rejoin. A name dates the target it names exactly or by slug prefix (`Acme` for
+ `acme-example`); when several objects in one field match a target, only the exact
+ match dates it.
- **Past-tense prose.** "previously at", "former CTO of", "used to work at" mark the
page's assertion as past ("has worked at" and "was promoted to CTO at" stay present).
A relationship with no dated evidence at all then reads as ended at an unknown date;
@@ -295,6 +297,68 @@ reversible timeline line.
Older gbrain releases reject a pack that uses `cardinality`, so set the pack's
`gbrain_min_version` to the release that adds it.
+## Amendments: the amends link
+
+A record that changes some terms of an earlier record (a contract amendment, a
+revised policy) links to it with `amends`. The earlier record still governs the
+terms the amendment did not change, so `amends` is metadata, not a ranking input:
+
+- **No ranking effect.** Adding amends edges leaves every final search score and
+ ranking signal unchanged: the backlink boost, the in-set and cross-source adjacency
+ boosts, relational fanout and chain hops, the typed (hub) degree, the enrich
+ inbound-link order, canonical entity picks, generated-page demotion and entity
+ anchoring. The list of non-ranking link types is in code
+ (`src/core/link-ranking-policy.ts`); a pack needs no field for it.
+- **Still a reference.** `get_links`, `get_backlinks`, `traverse_graph`, entity-card
+ edges, `backlink_count` and `referenced_by` return amends edges as usual.
+- **`since` is when the amended terms take effect.** Declare `amends` with
+ `temporal: event`, and `since` on each frontmatter object records the start
+ (`link_relationships.first_start`, in the `all` and `world` read scopes).
+- **Never hidden for starting later.** A default or `as_of` read keeps an amends
+ edge whose `since` is still ahead (status `not_started` in history reads), and so
+ does a `during` window that ends before it. `status: "ended"` never returns one.
+- **`supersedes` is different.** It marks a record replaced as a whole: search
+ halves the replaced record's score and labels it `superseded`. Use `amends`
+ whenever the earlier record still governs part of the terms.
+
+The frontmatter mapping is per page type (`frontmatter_links` names one
+`page_type`), so you write it for your own record types. The bundled example
+[`examples/schema-packs/amends-example/pack.yaml`](../../examples/schema-packs/amends-example/pack.yaml)
+maps `amends` (and `supersedes`) on `contract` pages under `contracts/`:
+
+```yaml
+link_types:
+ - name: amends
+ temporal: event
+frontmatter_links:
+ - page_type: contract
+ fields: [amends]
+ link_type: amends
+```
+
+A page then states what it amends and from when:
+
+```markdown
+---
+type: contract
+title: MSA Amendment 2
+amends:
+ - name: MSA Example
+ since: 2026-11-01
+---
+```
+
+Pages written before the mapping was active get their amends links when you
+re-extract them:
+
+```bash
+gbrain extract links --source db --include-frontmatter
+```
+
+Older gbrain releases load the same pack, but they rank amends edges like any
+typed link and hide future-dated ones, so set the pack's `gbrain_min_version` to
+the release that adds this policy (the example does).
+
## Turning it off
- `gbrain config set graph.edge_validity off`: graph reads return every edge, as
diff --git a/examples/schema-packs/amends-example/pack.yaml b/examples/schema-packs/amends-example/pack.yaml
new file mode 100644
index 0000000000..d756ce2b37
--- /dev/null
+++ b/examples/schema-packs/amends-example/pack.yaml
@@ -0,0 +1,56 @@
+# Example schema pack: dated records that amend other records.
+#
+# A contract page lists the records it amends in frontmatter:
+#
+# ---
+# type: contract
+# title: MSA Amendment 2
+# amends:
+# - name: MSA Example
+# since: 2026-11-01
+# ---
+#
+# Each entry becomes an `amends` link from this page to the named page; its
+# `since` records when the amended terms take effect (link_relationships
+# first_start). `amends` takes no part in ranking and future-dated amends
+# edges stay visible in default graph reads; both policies live in gbrain's
+# code, so this pack needs no ranking field.
+#
+# `supersedes: [name]` is for a record that replaces another one entirely:
+# search halves the replaced record's score and labels it superseded. Use
+# `amends` when the earlier record still governs the terms it did not change.
+#
+# Copy this directory to ~/.gbrain/schema-packs/amends-example/, rename the page
+# type and prefixes to your layout, then: gbrain schema use amends-example.
+# Existing pages gain their amends links after:
+# gbrain extract links --source db --include-frontmatter
+# Guide: docs/guides/temporal-edges.md ("Amendments: the amends link").
+
+api_version: gbrain-schema-pack-v1
+name: amends-example
+version: 1.0.0
+description: Contracts and other dated records that amend earlier records
+gbrain_min_version: 0.60.181.0
+extends: gbrain-base
+
+page_types:
+ - name: contract
+ primitive: temporal
+ path_prefixes:
+ - contracts/
+ aliases: []
+ extractable: false
+ expert_routing: false
+
+link_types:
+ - name: amends
+ temporal: event
+ - name: supersedes
+
+frontmatter_links:
+ - page_type: contract
+ fields: [amends]
+ link_type: amends
+ - page_type: contract
+ fields: [supersedes]
+ link_type: supersedes
diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.ts
index 035cb2e399..25f4caa705 100644
--- a/scripts/check-engine-sql-dynamic.ts
+++ b/scripts/check-engine-sql-dynamic.ts
@@ -66,6 +66,7 @@ const VETTED_BUILDERS: Record<string, string> = {
privateTimelineEventFilterFragment: 'src/core/search/private-visibility.ts: constant timeline-event visibility predicate over a caller alias',
privateSnapshotFilterFragment: 'src/core/search/private-visibility.ts: constant snapshot visibility predicate over a caller alias',
privateProvenanceFilterFragment: 'src/core/search/private-visibility.ts: constant fact-provenance visibility predicate over a caller alias',
+ rankingLinkSql: 'src/core/link-ranking-policy.ts: constant non-ranking link-type predicate (code-constant type names) over a caller alias',
vectorLiteralSql: 'src/core/engine-sql/facts.ts: master\'s inlined vector literal; toPgVectorLiteral output (numbers joined by commas) + a ::vector/::halfvec constant',
temporalLinkJoinSql: 'src/core/link-validity.ts: constant LEFT JOIN onto link_relationships over a caller alias; scope is one of two literals',
projectionEligibleSql: 'src/core/eligibility/sql.ts: read-eligibility predicate over a caller alias; splices only closed tier and reason-family vocabularies (no values)',
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index e1859121e8..e408c0552f 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,7 +16,7 @@ src/commands/sync.ts 519 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3303 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts)
src/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)
src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count
-src/core/engine.ts 2787 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts)
+src/core/engine.ts 2789 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts)
src/core/import-file.ts 2025 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured)
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index bc34ae7ce0..f163f00241 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -470,6 +470,9 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.180.0', text: 'A `remember` refused with `fact_withdrawn` now carries an additive `withdrawn` object (`at`, `subject`: the entity slug or `all_entities`, `visibility`) on the immediate refusal, the batch item error, the failed write receipt and `get_write_request`, so an agent can tell the user when and how widely the exact claim was forgotten instead of retrying. The message, code and suggestion are unchanged; the object is absent when the caller cannot read the forgotten rows.' },
{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },
{ since: '0.60.179.0', text: 'A managed sync no longer parks forever on a pinned import whose canonical correction (a fixable fence, reflowed frontmatter) would rewrite a file that holds newer uncommitted bytes: the file is held `worktree_dirty` with the rest of the source synced, the cursor finishes, and committing the file (or `gbrain sync unblock --source <id> --apply`) imports it. Before, that refusal (`source_changed` / `pinned_git_worktree_conflict`, "Canonical sanitization cannot overwrite newer working-tree bytes.") blocked the cursor with no exit: `--retry-failed` replayed the same pin, `sources refresh` refused `sync_in_progress` and `--acknowledge-managed` refused `cursor_unfinished`. A cursor an older release left blocked this way converts on its next `--retry-failed` run. Working-tree bytes that already are the correction (gbrain\'s own writeback, published before its request settled) import without a second write.' },
+ // The non-ranking amends link. `since` is provisional; the integrator restamps it at the merge slot.
+ { since: '0.60.180.0', text: '`amends` links (a record amending another, declared in a schema pack) no longer feed any ranking signal (backlink and adjacency boosts, relational hops and degree, enrich order, entity resolution, generated-page demotion, entity anchoring), and an amends edge whose `since` is still ahead now shows in default graph reads instead of being hidden. They stay references in get_backlinks, cards and `referenced_by`; `supersedes` still down-ranks a replaced record.' },
+ { since: '0.60.180.0', text: 'When several frontmatter relationship objects in one field match the same target, only the one whose name matches it exactly dates it: `{name: MSA, since}` no longer dates `msa-renewal` beside `{name: MSA Renewal, since}`. Re-extracting such a page (`gbrain extract links --source db --include-frontmatter`) records the corrected dates.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 5aa2a76d90..bc23543afb 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -47,7 +47,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--timeout', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],
'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],
- 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-rebase', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
+ 'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--auto-fix', '--background', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-usd', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--contacts-dir', '--content-audit', '--content-root', '--count', '--dataset', '--db-url', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--diff-filter', '--dim', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--end-of-options', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--from-pages', '--full', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--group', '--hard', '--hard-deadline', '--harness', '--help', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lanes', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--mode', '--multimodal', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-lanes', '--no-llm', '--no-migrate', '--no-pull', '--no-rebase', '--no-renames', '--no-repair', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--page', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--question', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--replace', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--reverse', '--review-lower', '--revision', '--rollback-to-source', '--scope', '--scopes', '--seat', '--section', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-prefix', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--stdin', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--url-env', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edge-proposals': ['--access', '--add', '--all-applied', '--all-held', '--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', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
@@ -72,7 +72,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'graph-query': ['--brain', '--depth', '--direction', '--help', '--hop', '--include-foreign', '--json', '--mcp-only', '--source', '--type'],
'hook': ['--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--count', '--diff-filter', '--enable', '--end-of-options', '--env', '--get', '--harness', '--help', '--jq', '--json', '--limit', '--name-only', '--others', '--pat-file', '--path', '--porcelain', '--pure', '--quiet', '--remove', '--seat', '--session', '--show-current', '--show-toplevel', '--since', '--source', '--yes'],
'import': ['--accept-pending', '--admin-intent', '--allow-empty', '--allow-noncanonical-root', '--apply', '--background', '--brain', '--cached', '--confirm-relocated-root', '--diff-filter', '--dim', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--format', '--fresh', '--help', '--include-gitignored', '--is-shallow-repository', '--json', '--log-noop', '--manifest', '--name-only', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-gpg-sign', '--no-pull', '--no-renames', '--no-verify', '--only', '--others', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--self-transfer', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--url', '--verify', '--wait', '--workers'],
- 'init': ['--access', '--acknowledge-managed', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
+ 'init': ['--access', '--acknowledge-managed', '--adopt', '--allow-create-db', '--allow-docker', '--apply', '--assign-corpus', '--auto', '--background', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--budget-usd', '--chat-model', '--check', '--confirm-relocated-root', '--content-root', '--db-only', '--dest', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--expansion-model', '--facts', '--fix', '--force', '--from-meetings', '--full', '--git', '--grant-types', '--harness', '--help', '--http', '--id', '--images', '--include-frontmatter', '--issuer-url', '--json', '--key', '--lanes', '--limit', '--list', '--local-postgres', '--markdown', '--max-usd', '--mcp-only', '--mcp-url', '--migrate-only', '--migration', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-git', '--no-llm', '--no-repair', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--once', '--only', '--page', '--params', '--pat-file', '--path', '--pglite', '--phase', '--plan', '--prefer-postgres', '--preview', '--probe', '--profile', '--provenance', '--query', '--question', '--quiet', '--rebase', '--reference-date', '--remediate', '--remove', '--reset', '--retry-failed', '--save', '--schema-pack', '--scope', '--scopes', '--section', '--self-transfer', '--show-toplevel', '--skip-embed-check', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--url-env', '--version', '--wait', '--warn-only', '--workspace', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--accept-pending', '--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--probe', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url', '--wait'],
'jobs': ['--abbrev-ref', '--access', '--acknowledge-managed', '--add', '--admin-intent', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--check', '--cli-path', '--client', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-quiesced', '--cost-estimate', '--date', '--dated-since', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--expected-state', '--explain', '--facts', '--federated-read', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--fuzzy', '--grammar-diagnostics', '--group', '--hard-deadline', '--health-interval', '--help', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--lanes', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--probe', '--prune-orphans', '--purge', '--queue', '--queue-only', '--quiet', '--reason', '--rebuild', '--recent', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--replace', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--retry-held', '--review-lower', '--row', '--scopes', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
diff --git a/src/core/engine-sql/salience.ts b/src/core/engine-sql/salience.ts
index 1610aa7c11..02e56a2b7a 100644
--- a/src/core/engine-sql/salience.ts
+++ b/src/core/engine-sql/salience.ts
@@ -22,6 +22,7 @@ import { computeAnomaliesFromBuckets } from '../cycle/anomaly.ts';
import type { SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead } from './brands.ts';
import { sqlFragment, trustedSql } from './fragment.ts';
+import { rankingLinkSql } from '../link-ranking-policy.ts';
export async function batchLoadEmotionalInputs(exec: LegacyUnscopedRead, slugs?: string[]): Promise<EmotionalWeightInputRow[]> {
// Two CTEs avoid the N×M cartesian product (codex C4#4): a page with N tags
@@ -226,6 +227,7 @@ export async function listEnrichCandidates(exec: LegacyUnscopedRead, opts: Enric
FROM links l
WHERE l.to_page_id = p.id
AND l.link_source IS DISTINCT FROM 'mentions'
+ AND ${trustedSql(rankingLinkSql('l'))}
), 0)::int AS inbound_count
FROM pages p
WHERE p.deleted_at IS NULL
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 2fb0089b3f..b098b4d4fe 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -1629,6 +1629,7 @@ export interface BrainEngine {
* feature.
* - `link_source='mentions'` edges are EXCLUDED by default (noisy + the
* densest fan-out source); opt in via `includeMentions`.
+ * - Non-ranking link types (src/core/link-ranking-policy.ts) are never walked.
* - `deleted_at IS NULL` at seed, every neighbor, and every returned node.
* - Deterministic ordering: hop ASC, edge_count DESC, source_id, slug.
* Must move in lockstep with the PGLite implementation
@@ -1644,13 +1645,13 @@ export interface BrainEngine {
* the relation's subject (`toward: 'object'`) or object (`toward:
* 'subject'`), with every endpoint and origin authorized by the read policy
* BEFORE the caller scores anything, at most `neighborCap` edges per frontier
- * node, same-source edges only, mentions excluded. Deterministic order:
- * frontier id, lowest link id. Pinned by test/e2e/engine-parity.test.ts.
+ * node, same-source edges only, mentions and non-ranking link types
+ * excluded (hops and degree). Deterministic order: frontier id, lowest link id. Pinned by test/e2e/engine-parity.test.ts.
*/
relationalChainHop(frontierPageIds: number[], opts: ChainHopOpts): Promise<ChainHopEdge[]>;
/**
- * For a list of page ids, return how many inbound links each has.
- * Used by hybrid search backlink boost. Single SQL query, not N+1.
+ * For a list of page ids, return how many pages link to each (mentions
+ * and non-ranking link types excluded). Used by hybrid search backlink boost. Single SQL query, not N+1.
* Keyed by page id — NOT slug — so namesake slugs across sources never
* share or sum counts (#4380). Ids with zero links map to 0.
*/
@@ -1662,7 +1663,8 @@ export interface BrainEngine {
* Map, no SQL.
*
* Returned shape per page (AdjacencyRow):
- * - `hits`: distinct from_page_id count, in-set
+ * - `hits`: distinct from_page_id count, in-set (non-ranking link
+ * types excluded, src/core/link-ranking-policy.ts)
* - `cross_source_hits`: distinct OTHER source_ids count (excluding
* target's own source), in-set
*
diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.ts
index 87199fb034..c03aa92fc0 100644
--- a/src/core/entities/resolve.ts
+++ b/src/core/entities/resolve.ts
@@ -30,6 +30,7 @@ const siblingCanonical: typeof import('../mentions/siblings.ts').siblingCanonica
(await import('../mentions/siblings.ts')).siblingCanonical(...args);
import { isUndefinedTableError } from '../utils.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
+import { rankingLinkSql } from '../link-ranking-policy.ts';
/**
* Canonicalize a free-form entity reference to a page slug.
@@ -505,8 +506,8 @@ export async function findPrefixCandidates(
connection_count: number;
}>(
`SELECT p.slug,
- ((SELECT COUNT(*)::int FROM links WHERE to_page_id = p.id)
- + (SELECT COUNT(*)::int FROM links WHERE from_page_id = p.id)
+ ((SELECT COUNT(*)::int FROM links l WHERE l.to_page_id = p.id AND ${rankingLinkSql('l')})
+ + (SELECT COUNT(*)::int FROM links l WHERE l.from_page_id = p.id AND ${rankingLinkSql('l')})
+ (SELECT COUNT(*)::int FROM content_chunks WHERE page_id = p.id))
AS connection_count
FROM pages p
@@ -604,8 +605,8 @@ async function tryPrefixExpansion(
// directly. Even on a pathological prefix matching 1000+ pages,
// work is bounded per-candidate, not whole-table.
`SELECT p.slug,
- ((SELECT COUNT(*)::int FROM links WHERE to_page_id = p.id)
- + (SELECT COUNT(*)::int FROM links WHERE from_page_id = p.id)
+ ((SELECT COUNT(*)::int FROM links l WHERE l.to_page_id = p.id AND ${rankingLinkSql('l')})
+ + (SELECT COUNT(*)::int FROM links l WHERE l.from_page_id = p.id AND ${rankingLinkSql('l')})
+ (SELECT COUNT(*)::int FROM content_chunks WHERE page_id = p.id))
AS connection_count
FROM pages p
diff --git a/src/core/link-ranking-policy.ts b/src/core/link-ranking-policy.ts
new file mode 100644
index 0000000000..a6db96b20d
--- /dev/null
+++ b/src/core/link-ranking-policy.ts
@@ -0,0 +1,35 @@
+/**
+ * Link-type ranking participation: the one policy every reader that turns
+ * links into a ranking signal honors.
+ *
+ * A non-ranking link type records metadata about a page (for example that a
+ * record amends another record) without saying the target matters more. Its
+ * edges stay ordinary references: get_links, get_backlinks, graph traversal,
+ * entity-card edges and backlink_count, and the referrer path still return
+ * them. They never feed a ranking signal: the backlink boost, the in-set and
+ * cross-source adjacency boosts, relational fanout hops, relational chain
+ * hops and the typed (hub) degree, the enrich inbound-link order, the
+ * connection count that picks a canonical entity, generated-page demotion and
+ * entity anchoring.
+ *
+ * The policy lives in code, not in a schema pack field, so a pack that
+ * declares one of these types loads on any gbrain. Contract:
+ * docs/guides/temporal-edges.md ("Amendments: the amends link").
+ */
+
+/** Link types that take no part in ranking. */
+export const NON_RANKING_LINK_TYPES: readonly string[] = Object.freeze(['amends']);
+
+/** True when edges of this type may feed a ranking signal. */
+export function linkTypeRanks(linkType: string): boolean {
+ return !NON_RANKING_LINK_TYPES.includes(linkType);
+}
+
+/**
+ * SQL predicate over a `links` row alias: TRUE when the row may feed a
+ * ranking signal. The type names are code constants inlined as literals, so
+ * the fragment composes into statements with any parameter numbering.
+ */
+export function rankingLinkSql(alias: string): string {
+ return `${alias}.link_type <> ALL(ARRAY[${NON_RANKING_LINK_TYPES.map(t => `'${t}'`).join(', ')}]::text[])`;
+}
diff --git a/src/core/link-temporal-evidence.ts b/src/core/link-temporal-evidence.ts
index e7328c3159..c8d1c2b4b6 100644
--- a/src/core/link-temporal-evidence.ts
+++ b/src/core/link-temporal-evidence.ts
@@ -276,16 +276,21 @@ export function deriveTemporalEvidence(page: PageForEvidence, rows: readonly Own
}
// 3. Frontmatter since/until on relationship objects ({name, since, until}).
+ // A name matches its target exactly or as a slug prefix ("Acme" for
+ // acme-example); when several objects in the field match one target, only
+ // the exact matches date it, so "MSA" never dates msa-renewal beside "MSA Renewal".
const fm = page.frontmatter ?? {};
for (const r of temporalRows) {
if (r.link_source !== 'frontmatter' || !r.origin_field) continue;
const field = fm[r.origin_field];
- const items = Array.isArray(field) ? field : [field];
- for (const item of items) {
- if (!item || typeof item !== 'object') continue;
+ const named = (Array.isArray(field) ? field : [field]).flatMap(item => {
+ if (!item || typeof item !== 'object') return [];
const obj = item as Record<string, unknown>;
const name = typeof obj.name === 'string' ? obj.name : typeof obj.slug === 'string' ? obj.slug : null;
- if (!name || !nameMatches(name, other(r))) continue;
+ const match = name ? nameMatch(name, other(r)) : null;
+ return name && match ? [{ obj, name, exact: match === 'exact' }] : [];
+ });
+ for (const { obj, name } of named.length > 1 ? named.filter(n => n.exact) : named) {
for (const [key, kind] of [['since', 'start'], ['until', 'end']] as const) {
const d = normalizePartialDate(stringish(obj[key]));
if (!d) continue;
@@ -325,8 +330,9 @@ function stringish(v: unknown): string | null {
return /^\d{4}-\d{2}-\d{2}T00:00:00(?:\.0+)?Z$/.test(v) ? v.slice(0, 10) : v;
}
-function nameMatches(name: string, slug: string): boolean {
+function nameMatch(name: string, slug: string): 'exact' | 'prefix' | null {
const base = slug.split('/').pop()!.toLowerCase();
const norm = name.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
- return norm === base || base.startsWith(`${norm}-`) || normalizeLinkTarget(name).toLowerCase() === slug.toLowerCase();
+ if (norm === base || normalizeLinkTarget(name).toLowerCase() === slug.toLowerCase()) return 'exact';
+ return base.startsWith(`${norm}-`) ? 'prefix' : null;
}
diff --git a/src/core/link-validity.ts b/src/core/link-validity.ts
index ff38fa83eb..9f95f48ad5 100644
--- a/src/core/link-validity.ts
+++ b/src/core/link-validity.ts
@@ -57,6 +57,17 @@ export function setPackRelationSemantics(semantics: ReadonlyMap<string, 'state'
packSemantics = semantics;
}
+/**
+ * Relation types that record when something takes effect rather than a
+ * relationship that starts and ends: their edges are never hidden for not
+ * having started (or for falling outside a `during` window). Status reads
+ * still report `not_started` and the stints; only filtering treats them like
+ * reference edges (never part of an `ended` read). docs/guides/temporal-edges.md.
+ */
+export const LIVENESS_EXEMPT_LINK_TYPES: readonly string[] = Object.freeze(['amends']);
+
+const livenessExemptSql = `lr.link_type <> ALL(ARRAY[${LIVENESS_EXEMPT_LINK_TYPES.map(t => `'${t}'`).join(', ')}]::text[])`;
+
export function relationSemantics(linkType: string | null | undefined): RelationSemantics {
if (!linkType) return 'reference';
return packSemantics.get(linkType) ?? RELATION_SEMANTICS[linkType] ?? 'reference';
@@ -363,7 +374,8 @@ function dateLiteral(date: string): string {
* fragment composes into statements with any parameter numbering.
*
* A row passes when its relationship has no state row (reference type, or not
- * yet refreshed) or its state row matches the requested status.
+ * yet refreshed), its type is liveness-exempt (outside `ended` reads), or its
+ * state row matches the requested status.
*/
export function relationshipFilterSql(linkAlias: string, opts: EdgeTemporalOpts = {}): string {
const status = opts.status ?? 'live';
@@ -374,14 +386,14 @@ export function relationshipFilterSql(linkAlias: string, opts: EdgeTemporalOpts
AND lr.link_type = ${linkAlias}.link_type AND lr.scope = '${scope}'`;
if (opts.during) {
const range = `daterange(${dateLiteral(opts.during.from)}, ${dateLiteral(opts.during.until)})`;
- return `NOT EXISTS (SELECT 1 FROM link_relationships lr WHERE ${probe} AND NOT (lr.valid_ranges && ${range}))`;
+ return `NOT EXISTS (SELECT 1 FROM link_relationships lr WHERE ${probe} AND ${livenessExemptSql} AND NOT (lr.valid_ranges && ${range}))`;
}
if (status === 'ended') {
return `EXISTS (SELECT 1 FROM link_relationships lr WHERE ${probe} AND lr.semantics = 'state'
AND NOT (lr.valid_ranges @> ${day}) AND (lr.first_start IS NULL OR lr.first_start <= ${day}))`;
}
const disputedClause = opts.asOf ? ' OR lr.disputed' : '';
- return `NOT EXISTS (SELECT 1 FROM link_relationships lr WHERE ${probe} AND (NOT (lr.valid_ranges @> ${day})${disputedClause}))`;
+ return `NOT EXISTS (SELECT 1 FROM link_relationships lr WHERE ${probe} AND ${livenessExemptSql} AND (NOT (lr.valid_ranges @> ${day})${disputedClause}))`;
}
/** Validate op-level temporal params; returns normalized opts or an error message. */
@@ -484,10 +496,11 @@ export function annotateTemporalRow<T extends { link_type: string }>(row: T, asO
* Used where the read is bounded (one page's edges) so callers can also count
* what they hid.
*/
-export function edgeMatchesTemporal(row: TemporalAnnotation & { first_start?: string | null }, opts: EdgeTemporalOpts = {}): boolean {
+export function edgeMatchesTemporal(row: TemporalAnnotation & { first_start?: string | null; link_type?: string }, opts: EdgeTemporalOpts = {}): boolean {
const status = opts.status ?? 'live';
if (opts.disabled) return true;
if (row.status === 'reference') return status !== 'ended';
+ if (row.link_type && LIVENESS_EXEMPT_LINK_TYPES.includes(row.link_type) && status !== 'ended') return true;
if (opts.during) {
if (!row.stints) return true;
return row.stints.some(s => (s.from === null || s.from < opts.during!.until) && (s.until === null || s.until > opts.during!.from));
diff --git a/src/core/search/entity-anchor.ts b/src/core/search/entity-anchor.ts
index d716a56b44..3c76b8ebc8 100644
--- a/src/core/search/entity-anchor.ts
+++ b/src/core/search/entity-anchor.ts
@@ -22,6 +22,7 @@ import type { PageReadScope, SearchResult } from '../types.ts';
import { PINNED_QUESTION_MARKER } from '../questions/identity.ts';
import { isFactEntityPage } from '../entities/resolve.ts';
import { pageReadFilter } from './read-policy-sql.ts';
+import { rankingLinkSql } from '../link-ranking-policy.ts';
import { containsTokenRun, isTitleMentionedInQuery, tokenizeTitle } from './title-match.ts';
import { enforceTokenBudget } from './token-budget.ts';
@@ -42,7 +43,7 @@ export async function entityAnchoredPages(engine: BrainEngine, sourceId: string,
const rows = await engine.executeRaw<{ id: number; slug: string }>(
`SELECT p.id, p.slug FROM pages p WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.slug <> $2
AND p.type NOT IN ('question', 'synthesis') AND NOT (p.frontmatter ? '${PINNED_QUESTION_MARKER}')
- AND (p.compiled_truth ~* $3 OR ($4::integer IS NOT NULL AND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id AND l.to_page_id = $4::integer)))
+ AND (p.compiled_truth ~* $3 OR ($4::integer IS NOT NULL AND EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = p.id AND l.to_page_id = $4::integer AND ${rankingLinkSql('l')})))
ORDER BY COALESCE(p.effective_date, p.updated_at) DESC, p.id DESC LIMIT ${limit}`,
[sourceId, entitySlug, pattern, entity?.id ?? null]);
return { entity: entity ? { id: Number(entity.id), slug: entitySlug } : null, pages: rows.map(r => ({ id: Number(r.id), slug: r.slug })) };
diff --git a/src/core/search/provenance-demotion.ts b/src/core/search/provenance-demotion.ts
index 6e046290ed..f08393fd2c 100644
--- a/src/core/search/provenance-demotion.ts
+++ b/src/core/search/provenance-demotion.ts
@@ -22,6 +22,7 @@
import type { BrainEngine } from '../engine.ts';
import type { SearchResult } from '../types.ts';
import { parseFactsFence } from '../facts-fence.ts';
+import { rankingLinkSql } from '../link-ranking-policy.ts';
import { resolveQueryEntity } from './alias-fanout.ts';
export const GENERATED_FACTOR = 0.5;
@@ -60,7 +61,7 @@ export async function applyGeneratedDemotion(engine: BrainEngine, list: SearchRe
const targetIds = targets.map(t => Number(t.id));
if (!targetIds.length) return;
const linking = new Set((await engine.executeRaw<{ id: number }>(
- `SELECT DISTINCT from_page_id AS id FROM links WHERE from_page_id = ANY($1::int[]) AND to_page_id = ANY($2::int[])`,
+ `SELECT DISTINCT l.from_page_id AS id FROM links l WHERE l.from_page_id = ANY($1::int[]) AND l.to_page_id = ANY($2::int[]) AND ${rankingLinkSql('l')}`,
[ids, targetIds])).map(r => Number(r.id)));
const primaryPresent = list.some(r => !generatedIds.has(r.page_id) && (targetIds.includes(r.page_id) || linking.has(r.page_id)));
if (!primaryPresent) return;
diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.ts
index a2537dac63..a18a1e614c 100644
--- a/src/core/search/read-enrichment.ts
+++ b/src/core/search/read-enrichment.ts
@@ -3,6 +3,7 @@ import { unverifiedExtractionFragment } from '../extraction-review.ts';
import { currentTextProjectionFilter, protectedBodyFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';
import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';
import { relationshipFilterSql } from '../link-validity.ts';
+import { rankingLinkSql } from '../link-ranking-policy.ts';
/** Narrow query dependency shared by both engines. */
export type ReadQuery = <T = Record<string, unknown>>(sql: string, params?: unknown[]) => Promise<T[]>;
@@ -61,7 +62,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], op
FROM walk w ${recurStep}
WHERE w.depth < $2 AND NOT (p2.id = ANY(w.visited))
AND p2.source_id = w.seed_source AND p2.deleted_at IS NULL
- AND ${step} AND ${origin} ${mentionsFilter} ${typeFilter} ${temporalFilter}
+ AND ${step} AND ${origin} AND ${rankingLinkSql('l')} ${mentionsFilter} ${typeFilter} ${temporalFilter}
)
SELECT n.source_id, n.slug, MIN(n.depth) AS hop,
COUNT(DISTINCT n.last_link_type) AS edge_count,
@@ -132,7 +133,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: C
${a}l.link_source, ${a}f.type AS from_type, ${a}t.type AS to_type, ${a}f.source_id
FROM f CROSS JOIN LATERAL (
SELECT x.* FROM links x WHERE x.${frontierCol} = f.id AND x.link_type = ANY($1::text[])
- AND x.from_page_id <> x.to_page_id AND x.link_source IS DISTINCT FROM 'mentions'
+ AND x.from_page_id <> x.to_page_id AND x.link_source IS DISTINCT FROM 'mentions' AND ${rankingLinkSql('x')}
OFFSET 0
) ${a}l
CROSS JOIN LATERAL ${byId(`${a}l.from_page_id`)} ${a}f
@@ -194,7 +195,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: C
SELECT CASE WHEN dl.from_page_id = f.id THEN dl.to_page_id ELSE dl.from_page_id END AS nb_id, dl.id AS lid, dl.origin_page_id
FROM links dl
WHERE (dl.from_page_id = f.id OR dl.to_page_id = f.id) AND dl.from_page_id <> dl.to_page_id
- AND dl.link_type = ANY($4::text[]) AND dl.link_source IS DISTINCT FROM 'mentions' ${degreeLive}
+ AND dl.link_type = ANY($4::text[]) AND dl.link_source IS DISTINCT FROM 'mentions' AND ${rankingLinkSql('dl')} ${degreeLive}
OFFSET 0
) dn
CROSS JOIN LATERAL ${byId('dn.nb_id')} nb
@@ -254,7 +255,7 @@ export async function readBacklinkCounts(query: ReadQuery, ids: number[], scope?
SELECT p.id AS page_id, COUNT(DISTINCT l.from_page_id)::int AS cnt
FROM pages p LEFT JOIN links l ON l.to_page_id = p.id
AND l.from_page_id <> p.id
- AND l.link_source IS DISTINCT FROM 'mentions'
+ AND l.link_source IS DISTINCT FROM 'mentions' AND ${rankingLinkSql('l')}
${scope ? `AND EXISTS (SELECT 1 FROM pages contributor WHERE contributor.id = l.from_page_id AND ${contributor}) AND ${origin}` : ''}
WHERE p.id = ANY($1::int[]) AND ${target} GROUP BY p.id`, params);
for (const row of rows) result.set(Number(row.page_id), Number(row.cnt));
@@ -281,7 +282,7 @@ export async function readAdjacencyBoosts(query: ReadQuery, ids: number[], scope
FROM links l JOIN pages p ON p.id = l.from_page_id AND p.deleted_at IS NULL
JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL
WHERE l.from_page_id = ANY(${idArray}) AND l.to_page_id = ANY(${idArray})
- AND ${from} AND ${to} AND ${origin}
+ AND ${from} AND ${to} AND ${origin} AND ${rankingLinkSql('l')}
GROUP BY l.to_page_id HAVING COUNT(DISTINCT l.from_page_id) >= 1`, params);
return new Map(rows.map(row => [Number(row.to_page_id), { hits: Number(row.hits), cross_source_hits: Number(row.cross_source_hits) }]));
}
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index 8c672fb8a2..7c59a23c11 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -20,7 +20,7 @@
* facts respect visibility for remote callers (world-only).
*/
-import { annotateTemporalRow, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, type TemporalAnnotation } from '../link-validity.ts';
+import { annotateTemporalRow, LIVENESS_EXEMPT_LINK_TYPES, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, type TemporalAnnotation } from '../link-validity.ts';
import type { BrainEngine, FactRow } from '../engine.ts';
import type { TrustTier } from '../trust/tier.ts';
import type { ReadEligibility } from '../eligibility/policy.ts';
@@ -463,7 +463,8 @@ async function assembleCard(
]);
// Live relationships first so ended ones never push a current edge past the cap.
- const rank = (status?: string) => (status === 'live' || status === 'disputed' ? 0 : status === 'event' || status === 'reference' || !status ? 1 : 2);
+ const rank = ({ status, type }: EntityCardEdge) => (status === 'live' || status === 'disputed' ? 0
+ : status === 'event' || status === 'reference' || !status || LIVENESS_EXEMPT_LINK_TYPES.includes(type) ? 1 : 2);
const edgeOf = (l: { link_type: string; context?: string | null } & Partial<TemporalAnnotation>, direction: 'out' | 'in', slug: string): EntityCardEdge => {
const last = l.stints?.[l.stints.length - 1];
return {
@@ -477,8 +478,8 @@ async function assembleCard(
.map(l => edgeOf(l, 'out', l.to_slug));
const inCandidates = inEdges.map(l => edgeOf(l as typeof l & Partial<TemporalAnnotation>, 'in', l.from_slug));
const edges: EntityCardEdge[] = [
- ...[...outCandidates].sort((a, b) => rank(a.status) - rank(b.status)),
- ...[...inCandidates].sort((a, b) => rank(a.status) - rank(b.status)),
+ ...[...outCandidates].sort((a, b) => rank(a) - rank(b)),
+ ...[...inCandidates].sort((a, b) => rank(a) - rank(b)),
].slice(0, EDGE_CAP);
const summary = safeSynopsis(row, { keepVisibility: remote ? ['world'] : ['private', 'world'] });
const relationshipNote = await loadRelationshipNotes(engine, [{ slug: pageSlug, source_id: sourceId, summary }], { excludePrivate })
diff --git a/test/amends-link.test.ts b/test/amends-link.test.ts
new file mode 100644
index 0000000000..2d75a6690d
--- /dev/null
+++ b/test/amends-link.test.ts
@@ -0,0 +1,65 @@
+/**
+ * The non-ranking `amends` link on PGLite (Postgres twin:
+ * test/e2e/amends-link-postgres.test.ts): one final-output invariance row per
+ * link-counting ranking consumer, amendments versus genuine replacement in
+ * final search scores and labels, the example pack's frontmatter mapping and
+ * `since`, and the frozen-clock liveness exemption.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, setSystemTime, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { setPackRelationSemantics } from '../src/core/link-validity.ts';
+import { linkTypeRanks, NON_RANKING_LINK_TYPES, rankingLinkSql } from '../src/core/link-ranking-policy.ts';
+import { loadPackFromFile } from '../src/core/schema-pack/loader.ts';
+import { INVARIANCE_ROWS, amendmentsVersusReplacement, databaseToday, frontmatterRecordsSince, futureAmendsStayVisible,
+ runInvarianceRow, useExamplePack } from './helpers/amends-ranking-scenarios.ts';
+
+setDefaultTimeout(60_000);
+let engine: PGLiteEngine;
+let restorePacks: () => void;
+
+beforeAll(async () => {
+ restorePacks = useExamplePack();
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); resetGateway(); setPackRelationSemantics(new Map()); restorePacks(); });
+beforeEach(async () => { await resetPgliteState(engine); configureGateway({ env: {} } as never); setPackRelationSemantics(new Map()); });
+
+describe('ranking participation policy', () => {
+ test('amends is the non-ranking link type; the SQL predicate inlines it', () => {
+ expect(NON_RANKING_LINK_TYPES).toEqual(['amends']);
+ expect(linkTypeRanks('amends')).toBe(false);
+ expect(linkTypeRanks('supersedes')).toBe(true);
+ expect(linkTypeRanks('mentions')).toBe(true);
+ expect(rankingLinkSql('l')).toBe(`l.link_type <> ALL(ARRAY['amends']::text[])`);
+ });
+
+ test('the bundled example pack is a valid manifest declaring amends as an event mapped from frontmatter', () => {
+ const manifest = loadPackFromFile(new URL('../examples/schema-packs/amends-example/pack.yaml', import.meta.url).pathname);
+ expect(manifest.link_types).toEqual([{ name: 'amends', temporal: 'event' }, { name: 'supersedes' }]);
+ expect(manifest.frontmatter_links).toEqual([
+ { page_type: 'contract', fields: ['amends'], link_type: 'amends' },
+ { page_type: 'contract', fields: ['supersedes'], link_type: 'supersedes' },
+ ]);
+ });
+});
+
+describe('final-output invariance: one row per link-counting ranking consumer', () => {
+ for (const row of INVARIANCE_ROWS) {
+ test(`${row.consumer} — threshold: ${row.threshold}`, () => runInvarianceRow(engine, row));
+ }
+});
+
+describe('amendments versus replacement', () => {
+ test('current and future amendments leave scores and labels unchanged; supersedes halves and labels', () => amendmentsVersusReplacement(engine));
+ test('frontmatter amends objects record since as first_start in both scopes, each on its exact target', () => frontmatterRecordsSince(engine));
+});
+
+describe('liveness exemption (frozen clock)', () => {
+ test('a future-since amends edge stays visible in get_backlinks, traverse_graph and card edges', async () => {
+ const today = await databaseToday(engine);
+ setSystemTime(new Date(`${today}T12:00:00Z`));
+ try { await futureAmendsStayVisible(engine, today); } finally { setSystemTime(); }
+ });
+});
diff --git a/test/e2e/amends-link-postgres.test.ts b/test/e2e/amends-link-postgres.test.ts
new file mode 100644
index 0000000000..647ff1db9f
--- /dev/null
+++ b/test/e2e/amends-link-postgres.test.ts
@@ -0,0 +1,38 @@
+/**
+ * Postgres twin of test/amends-link.test.ts: the per-consumer final-output
+ * invariance table for the non-ranking `amends` link, amendments versus
+ * replacement in final search scores and labels, frontmatter `since`, and the
+ * frozen-clock liveness exemption. One cloned database per scenario.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, setSystemTime, test } from 'bun:test';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { hasDatabase } from './helpers.ts';
+import { persistencePostgresTemplate } from '../helpers/persistence-postgres.ts';
+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
+import { setPackRelationSemantics } from '../../src/core/link-validity.ts';
+import { INVARIANCE_ROWS, amendmentsVersusReplacement, databaseToday, frontmatterRecordsSince, futureAmendsStayVisible,
+ runInvarianceRow, useExamplePack } from '../helpers/amends-ranking-scenarios.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+let template: Awaited<ReturnType<typeof persistencePostgresTemplate>>;
+let engine: PostgresEngine;
+let close: () => Promise<void>;
+let restorePacks: () => void;
+
+d('non-ranking amends link (Postgres)', () => {
+ beforeAll(async () => { restorePacks = useExamplePack(); template = await persistencePostgresTemplate(process.env.DATABASE_URL!); }, 120_000);
+ afterAll(async () => { await template.dispose(); restorePacks(); });
+ beforeEach(async () => { ({ engine, close } = await template.clone()); configureGateway({ env: {} } as never); setPackRelationSemantics(new Map()); }, 60_000);
+ afterEach(async () => { resetGateway(); setPackRelationSemantics(new Map()); await close(); });
+
+ for (const row of INVARIANCE_ROWS) {
+ test(`invariance: ${row.consumer} — threshold: ${row.threshold}`, () => runInvarianceRow(engine, row), 60_000);
+ }
+ test('current and future amendments leave scores and labels unchanged; supersedes halves and labels', () => amendmentsVersusReplacement(engine), 60_000);
+ test('frontmatter amends objects record since as first_start in both scopes, each on its exact target', () => frontmatterRecordsSince(engine), 60_000);
+ test('frozen clock: a future-since amends edge stays visible in get_backlinks, traverse_graph and card edges', async () => {
+ const today = await databaseToday(engine);
+ setSystemTime(new Date(`${today}T12:00:00Z`));
+ try { await futureAmendsStayVisible(engine, today); } finally { setSystemTime(); }
+ }, 60_000);
+});
diff --git a/test/fixtures/goldens/sql-text/salience.json b/test/fixtures/goldens/sql-text/salience.json
index aad17489c7..346c3d1604 100644
--- a/test/fixtures/goldens/sql-text/salience.json
+++ b/test/fixtures/goldens/sql-text/salience.json
@@ -222,8 +222,8 @@
"number",
"number"
],
- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $3",
- "textSha256": "3338bd2f96f229be17a9f3405af5556f88263be691c24990ac2ae0db4c358661"
+ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $3",
+ "textSha256": "1a1f91975382b6f97f2ba8119b0a344c48a2383f19a21040b553657652875f01"
}
],
"sourceId": [
@@ -235,8 +235,8 @@
"string",
"number"
],
- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = $3 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $4",
- "textSha256": "d66d07de0d8a4b29e1a7f730e8bfae4ca1f52e8afc12cf356552eb151d4ddfdb"
+ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = $3 AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $4",
+ "textSha256": "ac911efc9ff41921e9ebdde94bd01d861d022f72ccedac6417eea9de315b2dfc"
}
],
"sourceIds+reenrich": [
@@ -249,8 +249,8 @@
"string",
"number"
],
- "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = ANY($3::text[]) AND NOT ( p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $4 ) AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $5",
- "textSha256": "99c6dc60239a138d17df8f52076ceb9020c9404507aa45fa608be039f3b90d4d"
+ "sql": "SELECT p.slug, p.source_id, p.title, p.type, (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) AS body_len, COALESCE(( SELECT COUNT(*) FROM links l WHERE l.to_page_id = p.id AND l.link_source IS DISTINCT FROM 'mentions' AND l.link_type <> ALL(ARRAY['amends']::text[]) ), 0)::int AS inbound_count FROM pages p WHERE p.deleted_at IS NULL AND p.type = ANY($1::text[]) AND (char_length(p.compiled_truth) + char_length(COALESCE(p.timeline, ''))) < $2 AND p.source_id = ANY($3::text[]) AND NOT ( p.frontmatter ->> 'enriched_at' IS NOT NULL AND p.frontmatter ->> 'enriched_at' > $4 ) AND (p.frontmatter ->> 'dream_generated') IS DISTINCT FROM 'true' ORDER BY inbound_count DESC, p.source_id ASC, p.slug ASC LIMIT $5",
+ "textSha256": "01b82217b92b0982f9570e78247e7c39ab1925fde627edf063923526b895d9e6"
}
]
},
diff --git a/test/helpers/amends-ranking-scenarios.ts b/test/helpers/amends-ranking-scenarios.ts
new file mode 100644
index 0000000000..a9246d34ba
--- /dev/null
+++ b/test/helpers/amends-ranking-scenarios.ts
@@ -0,0 +1,392 @@
+/**
+ * Engine-parametrized scenarios for the non-ranking `amends` link
+ * (src/core/link-ranking-policy.ts) and its liveness exemption
+ * (src/core/link-validity.ts LIVENESS_EXEMPT_LINK_TYPES):
+ * test/amends-link.test.ts on PGLite, test/e2e/amends-link-postgres.test.ts on
+ * Postgres. Each scenario expects a fresh brain. Zero model calls (keyword-only
+ * search: the gateway has no provider key).
+ *
+ * The invariance table has one row per link-counting ranking consumer. Each
+ * row seeds a brain, reads the consumer's final output, adds ONLY amends
+ * edges and reads it again (must be identical), then adds the same edges with
+ * a ranking type and reads it a third time (must cross the consumer's
+ * threshold), so a row that cannot see links fails instead of passing.
+ */
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { SearchResult } from '../../src/core/types.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { hybridSearch, _resetSupersedeProbeForTests, SUPERSEDE_PENALTY } from '../../src/core/search/hybrid.ts';
+import { buildRelationalArm } from '../../src/core/search/relational-recall.ts';
+import { CHAIN_LINK_TYPES, runRelationalChain } from '../../src/core/search/relational-chain.ts';
+import { applyGeneratedDemotion } from '../../src/core/search/provenance-demotion.ts';
+import { applyEntityAnchoring } from '../../src/core/search/entity-anchor.ts';
+import { findPrefixCandidates } from '../../src/core/entities/resolve.ts';
+import { operations, type OperationContext } from '../../src/core/operations.ts';
+import { buildEntityCard } from '../../src/core/verbs/entity-card.ts';
+import { utcToday } from '../../src/core/link-validity.ts';
+import { __setPackLocatorForTests, _resetPackLocatorForTests, _resetPackCacheForTests } from '../../src/core/schema-pack/index.ts';
+import { bundledPackPath } from '../../src/core/schema-pack/bundled-assets.ts';
+
+export const EXAMPLE_PACK = 'amends-example';
+const EXAMPLE_PACK_PATH = new URL('../../examples/schema-packs/amends-example/pack.yaml', import.meta.url).pathname;
+
+/** Resolve the bundled example pack by name for the duration of a test file. */
+export function useExamplePack(): () => void {
+ __setPackLocatorForTests(name => name === EXAMPLE_PACK ? EXAMPLE_PACK_PATH : bundledPackPath(name));
+ _resetPackCacheForTests();
+ return () => { _resetPackLocatorForTests(); _resetPackCacheForTests(); };
+}
+
+type Page = { slug: string; title: string; type: string; body: string; source?: string; frontmatter?: string };
+
+async function seed(engine: BrainEngine, pages: Page[]): Promise<void> {
+ for (const source of new Set(pages.map(p => p.source ?? 'default'))) {
+ if (source !== 'default') await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT (id) DO NOTHING`, [source]);
+ }
+ for (const p of pages) {
+ const md = `---\ntype: ${p.type}\ntitle: ${p.title}\n${p.frontmatter ?? ''}---\n\n${p.body}\n`;
+ await importFromContent(engine, p.slug, md, { noEmbed: true, ...(p.source ? { sourceId: p.source } : {}) });
+ }
+}
+
+type Edge = [from: string, to: string] | [from: string, to: string, fromSource: string, toSource: string];
+
+/** Insert link rows the way a frontmatter mapping stores them (origin = the stating page). */
+async function link(engine: BrainEngine, edges: Edge[], linkType: string): Promise<void> {
+ for (const [from, to, fromSource = 'default', toSource = 'default'] of edges) {
+ const inserted = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO links (from_page_id, to_page_id, link_type, link_source, origin_page_id, origin_field, context)
+ SELECT f.id, t.id, $3, 'frontmatter', f.id, $3, '' FROM pages f, pages t
+ WHERE f.slug = $1 AND f.source_id = $4 AND t.slug = $2 AND t.source_id = $5 RETURNING id`,
+ [from, to, linkType, fromSource, toSource]);
+ if (inserted.length !== 1) throw new Error(`fixture link ${from} -> ${to} not inserted`);
+ }
+}
+
+const pageId = async (engine: BrainEngine, slug: string, source = 'default') =>
+ Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2', [slug, source]))[0]!.id);
+
+/** Final search output: every result's score and every ranking stamp. */
+async function searchOutput(engine: BrainEngine, query: string, extra: Record<string, unknown> = {}) {
+ _resetSupersedeProbeForTests();
+ const results = await hybridSearch(engine, query, { limit: 20, ...extra });
+ return results.map(r => ({
+ slug: r.slug, source_id: r.source_id, score: r.score,
+ backlink_boost: r.backlink_boost, backlink_count: r.backlink_count,
+ graph_adjacency_boost: r.graph_adjacency_boost, graph_cross_source_boost: r.graph_cross_source_boost,
+ superseded: r.superseded, superseded_by: r.superseded_by,
+ })).sort((a, b) => `${a.source_id}:${a.slug}`.localeCompare(`${b.source_id}:${b.slug}`));
+}
+type SearchOut = Awaited<ReturnType<typeof searchOutput>>;
+const row = (out: SearchOut, slug: string) => out.find(r => r.slug === slug)!;
+
+const MSA_TEXT = 'Master services agreement. Payment terms are net 30 and support runs on business days.';
+const AMENDMENT_TEXT = 'Amendment to the master services agreement. Payment terms change to net 45.';
+const contract = (slug: string, title: string, body: string, source?: string): Page => ({ slug, title, type: 'contract', body, source });
+
+export interface InvarianceRow {
+ consumer: string;
+ threshold: string;
+ setup: (engine: BrainEngine) => Promise<void>;
+ observe: (engine: BrainEngine) => Promise<unknown>;
+ /** Edges added once as `amends` (no change allowed), then as a ranking type (must cross the threshold). */
+ edges: Edge[];
+ crossed: (before: any, after: any) => boolean;
+}
+
+export const INVARIANCE_ROWS: InvarianceRow[] = [
+ {
+ consumer: 'backlink boost (hybrid search, getBacklinkCounts)',
+ threshold: 'boost applies from 1 linking page',
+ setup: e => seed(e, [contract('contracts/msa-example', 'MSA Example', MSA_TEXT), contract('contracts/msa-example-amendment-1', 'MSA Example Amendment 1', AMENDMENT_TEXT)]),
+ observe: e => searchOutput(e, 'payment terms master services agreement'),
+ edges: [['contracts/msa-example-amendment-1', 'contracts/msa-example']],
+ crossed: (b: SearchOut, a: SearchOut) => row(b, 'contracts/msa-example').backlink_boost === undefined
+ && row(a, 'contracts/msa-example').backlink_boost! > 1 && row(a, 'contracts/msa-example').score > row(b, 'contracts/msa-example').score,
+ },
+ {
+ consumer: 'in-set adjacency boost (graph signals, getAdjacencyBoosts hits)',
+ threshold: 'ADJACENCY_MIN_HITS = 2 linking top-K pages',
+ setup: async e => {
+ await seed(e, [contract('contracts/msa-example', 'MSA Example', MSA_TEXT),
+ contract('contracts/msa-example-amendment-1', 'MSA Example Amendment 1', AMENDMENT_TEXT),
+ contract('contracts/msa-example-amendment-2', 'MSA Example Amendment 2', `${AMENDMENT_TEXT} Support adds weekends.`)]);
+ await link(e, [['contracts/msa-example-amendment-1', 'contracts/msa-example']], 'related_to');
+ },
+ observe: e => searchOutput(e, 'payment terms master services agreement', { graph_signals: true }),
+ edges: [['contracts/msa-example-amendment-2', 'contracts/msa-example']],
+ crossed: (b: SearchOut, a: SearchOut) => row(b, 'contracts/msa-example').graph_adjacency_boost === undefined
+ && row(a, 'contracts/msa-example').graph_adjacency_boost! > 1,
+ },
+ {
+ consumer: 'cross-source adjacency boost (graph signals, getAdjacencyBoosts cross_source_hits)',
+ threshold: 'CROSS_SOURCE_MIN_HITS = 2 other sources',
+ setup: async e => {
+ await seed(e, [contract('contracts/msa-example', 'MSA Example', MSA_TEXT),
+ contract('contracts/msa-example-amendment-1', 'MSA Example Amendment 1', AMENDMENT_TEXT, 'east-example'),
+ contract('contracts/msa-example-amendment-2', 'MSA Example Amendment 2', `${AMENDMENT_TEXT} Support adds weekends.`, 'west-example')]);
+ await link(e, [['contracts/msa-example-amendment-1', 'contracts/msa-example', 'east-example', 'default']], 'related_to');
+ },
+ observe: e => searchOutput(e, 'payment terms master services agreement', { graph_signals: true }),
+ edges: [['contracts/msa-example-amendment-2', 'contracts/msa-example', 'west-example', 'default']],
+ crossed: (b: SearchOut, a: SearchOut) => row(b, 'contracts/msa-example').graph_cross_source_boost === undefined
+ && row(a, 'contracts/msa-example').graph_cross_source_boost! > 1,
+ },
+ {
+ consumer: 'relational fanout hops (relational search arm, type-agnostic connects)',
+ threshold: 'a shared midpoint is reachable from both seeds',
+ setup: async e => {
+ await seed(e, [{ slug: 'companies/acme-example', title: 'Acme Example', type: 'company', body: 'A customer.' },
+ { slug: 'companies/widget-example', title: 'Widget Example', type: 'company', body: 'A supplier.' },
+ contract('contracts/msa-example', 'MSA Example', MSA_TEXT)]);
+ await link(e, [['contracts/msa-example', 'companies/acme-example']], 'related_to');
+ },
+ observe: async e => (await buildRelationalArm(e, 'what connects Acme Example and Widget Example', { sourceId: 'default' }))
+ .map(r => ({ slug: r.slug, score: r.score })),
+ edges: [['contracts/msa-example', 'companies/widget-example']],
+ crossed: (b: Array<{ slug: string }>, a: Array<{ slug: string }>) => !b.some(r => r.slug === 'contracts/msa-example') && a.some(r => r.slug === 'contracts/msa-example'),
+ },
+ {
+ consumer: 'relational chain hops (relationalChainHop link scan)',
+ threshold: 'an edge of an asked-for type is walked',
+ setup: e => seed(e, [contract('contracts/msa-example', 'MSA Example', MSA_TEXT), contract('contracts/msa-example-amendment-1', 'MSA Example Amendment 1', AMENDMENT_TEXT)]),
+ observe: async e => e.relationalChainHop([await pageId(e, 'contracts/msa-example-amendment-1')], {
+ linkTypes: ['amends', 'related_to'], toward: 'object', subjectTypes: ['contract'], objectTypes: ['contract'],
+ degreeLinkTypes: ['amends', 'related_to'], neighborCap: 100,
+ }),
+ edges: [['contracts/msa-example-amendment-1', 'contracts/msa-example']],
+ crossed: (b: unknown[], a: Array<{ to_slug: string }>) => b.length === 0 && a.length === 1 && a[0]!.to_slug === 'contracts/msa-example',
+ },
+ {
+ consumer: 'typed degree / hub degree (relationalChainHop from_degree; chain path weights)',
+ threshold: 'hub weight falls once an intermediate gains a typed neighbor',
+ setup: async e => {
+ await seed(e, [{ slug: 'people/alice-example', title: 'Alice Example', type: 'person', body: 'An engineer.' },
+ { slug: 'people/bob-example', title: 'Bob Example', type: 'person', body: 'A designer.' },
+ { slug: 'people/carol-example', title: 'Carol Example', type: 'person', body: 'A manager.' },
+ { slug: 'companies/acme-example', title: 'Acme Example', type: 'company', body: 'A customer.' },
+ contract('contracts/msa-example', 'MSA Example', MSA_TEXT)]);
+ await link(e, [['people/alice-example', 'companies/acme-example'], ['people/bob-example', 'companies/acme-example']], 'works_at');
+ },
+ observe: async e => {
+ const alice = await pageId(e, 'people/alice-example');
+ const chain = await runRelationalChain(e, [{ page_id: alice, slug: 'people/alice-example', source_id: 'default' }], {
+ hops: [{ linkTypes: ['works_at'], toward: 'object' }, { linkTypes: ['works_at'], toward: 'subject' }], excludeAnchor: true,
+ }, { sourceId: 'default' });
+ const hop = await e.relationalChainHop([await pageId(e, 'companies/acme-example')], {
+ linkTypes: ['works_at'], toward: 'subject', subjectTypes: ['person'], objectTypes: ['company'],
+ degreeLinkTypes: [...CHAIN_LINK_TYPES, 'amends', 'related_to'], neighborCap: 100,
+ });
+ return { answers: chain.rows.filter(r => r.role === 'answer').map(r => ({ slug: r.slug, score: r.score })), degree: hop.map(h => h.from_degree) };
+ },
+ edges: [['contracts/msa-example', 'companies/acme-example'], ['people/carol-example', 'companies/acme-example']],
+ crossed: (b: { degree: number[] }, a: { degree: number[] }) => b.degree.every(d => d === 2) && a.degree.every(d => d === 4),
+ },
+ {
+ consumer: 'salience inbound counts (listEnrichCandidates order inbound-links)',
+ threshold: 'order flips when one candidate gains inbound links',
+ setup: e => seed(e, [{ slug: 'companies/acme-example', title: 'Acme Example', type: 'company', body: 'A customer.' },
+ { slug: 'companies/widget-example', title: 'Widget Example', type: 'company', body: 'A supplier.' },
+ contract('contracts/msa-example', 'MSA Example', MSA_TEXT)]),
+ observe: e => e.listEnrichCandidates({ types: ['company'], thinThreshold: 10_000, order: 'inbound-links', limit: 10 })
+ .then(rows => rows.map(r => ({ slug: r.slug, inbound_count: r.inbound_count }))),
+ edges: [['contracts/msa-example', 'companies/widget-example']],
+ crossed: (b: Array<{ slug: string }>, a: Array<{ slug: string; inbound_count: number }>) =>
+ b[0]!.slug === 'companies/acme-example' && a[0]!.slug === 'companies/widget-example' && a[0]!.inbound_count === 1,
+ },
+ {
+ consumer: 'canonical entity pick (entity resolution connection count)',
+ threshold: 'the most connected prefix candidate wins',
+ setup: e => seed(e, [{ slug: 'companies/acme-example', title: 'Acme Example', type: 'company', body: 'A customer.' },
+ { slug: 'companies/acme-labs', title: 'Acme Labs', type: 'company', body: 'A lab.' },
+ contract('contracts/msa-example', 'MSA Example', MSA_TEXT)]),
+ observe: e => findPrefixCandidates(e, 'default', 'acme'),
+ edges: [['contracts/msa-example', 'companies/acme-labs']],
+ crossed: (b: Array<{ slug: string }>, a: Array<{ slug: string }>) => b[0]!.slug === 'companies/acme-example' && a[0]!.slug === 'companies/acme-labs',
+ },
+ {
+ consumer: 'generated-page demotion (provenance demotion link test)',
+ threshold: 'a generated page that links to the query entity is demoted',
+ setup: e => seed(e, [{ slug: 'companies/acme-example', title: 'Acme Example', type: 'company', body: 'Acme Example is a customer.' },
+ { slug: 'notes/acme-example-digest', title: 'Weekly digest', type: 'note', body: 'Digest of the week.', frontmatter: 'dream_generated: true\n' }]),
+ observe: async e => {
+ const list = [
+ { page_id: await pageId(e, 'companies/acme-example'), slug: 'companies/acme-example', source_id: 'default', score: 1 },
+ { page_id: await pageId(e, 'notes/acme-example-digest'), slug: 'notes/acme-example-digest', source_id: 'default', score: 1 },
+ ] as SearchResult[];
+ await applyGeneratedDemotion(e, list, 'Acme Example', { sourceId: 'default' });
+ return list.map(r => ({ slug: r.slug, score: r.score, generated_demotion: r.generated_demotion }));
+ },
+ edges: [['notes/acme-example-digest', 'companies/acme-example']],
+ crossed: (b: Array<{ score: number }>, a: Array<{ slug: string; score: number }>) =>
+ b.every(r => r.score === 1) && a.find(r => r.slug === 'notes/acme-example-digest')!.score < 1,
+ },
+ {
+ consumer: 'entity anchoring (pages linking to the named entity)',
+ threshold: 'a page that links to the entity is anchored',
+ setup: e => seed(e, [{ slug: 'companies/acme-example', title: 'Acme Example', type: 'company', body: 'A customer.' },
+ contract('contracts/msa-example', 'MSA Example', MSA_TEXT)]),
+ observe: async e => (await applyEntityAnchoring(e, 'what is the latest on Acme Example', [], { sourceId: 'default' }))
+ .results.map(r => ({ slug: r.slug, score: r.score, entity_anchored: r.entity_anchored })),
+ edges: [['contracts/msa-example', 'companies/acme-example']],
+ crossed: (b: Array<{ slug: string }>, a: Array<{ slug: string }>) => !b.some(r => r.slug === 'contracts/msa-example') && a.some(r => r.slug === 'contracts/msa-example'),
+ },
+];
+
+/** One invariance row: amends edges leave the final output unchanged; the same edges with a ranking type cross the threshold. */
+export async function runInvarianceRow(engine: BrainEngine, r: InvarianceRow): Promise<void> {
+ await r.setup(engine);
+ const before = await r.observe(engine);
+ await link(engine, r.edges, 'amends');
+ expect(await r.observe(engine)).toEqual(before);
+ await link(engine, r.edges, 'related_to');
+ const control = await r.observe(engine);
+ expect(r.crossed(before, control)).toBe(true);
+}
+
+// ─── Search scores and labels: unchanged terms, future amendments, replacement ───
+
+const ctx = (engine: BrainEngine, remote = false): OperationContext => ({
+ engine, config: { engine: 'pglite' as const }, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote, sourceId: 'default', ...(remote ? { takesHoldersAllowList: ['world'] } : {}),
+} as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+async function put(engine: BrainEngine, slug: string, fm: string, body: string): Promise<void> {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await op('put_page').handler(ctx(engine), { slug, content: `---\n${fm}\n---\n\n${body}\n`, ...(snapshot ? { expected_revision: snapshot.revision } : {}) });
+}
+
+const addDays = (day: string, n: number) => new Date(Date.parse(`${day}T00:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10);
+
+/** The brain's current UTC date, as the default liveness filter reads it (the database clock). */
+export async function databaseToday(engine: BrainEngine): Promise<string> {
+ const [r] = await engine.executeRaw<{ d: string }>(`SELECT ((now() AT TIME ZONE 'UTC')::date)::text AS d`);
+ return r!.d;
+}
+
+/**
+ * Write the original contract, an amendment of it that takes effect in the
+ * future (through the example pack's frontmatter mapping) and a prefix-sharing
+ * sibling contract with its own amendment date. Requires the example pack active.
+ */
+export async function seedAmendedContracts(engine: BrainEngine, today: string): Promise<{ since: string; renewalSince: string }> {
+ const since = addDays(today, 400);
+ const renewalSince = addDays(today, 800);
+ await engine.setConfig('schema_pack', EXAMPLE_PACK);
+ await put(engine, 'contracts/msa-example', 'type: contract\ntitle: MSA Example', MSA_TEXT);
+ await put(engine, 'contracts/msa-example-renewal', 'type: contract\ntitle: MSA Example Renewal', 'Renewal of the services agreement for a second term.');
+ await put(engine, 'contracts/msa-example-amendment-2', [
+ 'type: contract', 'title: MSA Example Amendment 2', 'amends:',
+ ' - name: MSA Example', ` since: ${since}`,
+ ' - name: MSA Example Renewal', ` since: ${renewalSince}`,
+ ].join('\n'), AMENDMENT_TEXT);
+ return { since, renewalSince };
+}
+
+/**
+ * The example pack maps frontmatter `amends` to amends links whose `since` is
+ * link_relationships.first_start in both scopes; a `since` stated only on a
+ * private page is recorded in the `all` scope and absent from `world`.
+ */
+export async function frontmatterRecordsSince(engine: BrainEngine): Promise<void> {
+ const { since, renewalSince } = await seedAmendedContracts(engine, await databaseToday(engine));
+ const links = await engine.executeRaw<{ to: string; link_type: string; link_source: string }>(
+ `SELECT t.slug AS "to", l.link_type, l.link_source FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE f.slug = 'contracts/msa-example-amendment-2' AND l.link_type = 'amends' ORDER BY t.slug`);
+ expect(links).toEqual([
+ { to: 'contracts/msa-example', link_type: 'amends', link_source: 'frontmatter' },
+ { to: 'contracts/msa-example-renewal', link_type: 'amends', link_source: 'frontmatter' },
+ ]);
+ const state = await engine.executeRaw<{ to: string; scope: string; semantics: string; first_start: string; status_now: string }>(
+ `SELECT t.slug AS "to", lr.scope, lr.semantics, lr.first_start::text AS first_start, lr.status_now FROM link_relationships lr
+ JOIN pages t ON t.id = lr.to_page_id WHERE lr.link_type = 'amends' ORDER BY t.slug, lr.scope`);
+ expect(state).toEqual([
+ { to: 'contracts/msa-example', scope: 'all', semantics: 'event', first_start: since, status_now: 'not_started' },
+ { to: 'contracts/msa-example', scope: 'world', semantics: 'event', first_start: since, status_now: 'not_started' },
+ { to: 'contracts/msa-example-renewal', scope: 'all', semantics: 'event', first_start: renewalSince, status_now: 'not_started' },
+ { to: 'contracts/msa-example-renewal', scope: 'world', semantics: 'event', first_start: renewalSince, status_now: 'not_started' },
+ ]);
+
+ await put(engine, 'contracts/msa-example-amendment-3', [
+ 'type: contract', 'title: MSA Example Amendment 3', 'visibility: private', 'amends:', ' - name: MSA Example Renewal', ` since: ${since}`,
+ ].join('\n'), 'A private side letter.');
+ const scopes = await engine.executeRaw<{ scope: string; first_start: string }>(
+ `SELECT lr.scope, lr.first_start::text AS first_start FROM link_relationships lr JOIN pages f ON f.id = lr.from_page_id
+ WHERE f.slug = 'contracts/msa-example-amendment-3' AND lr.link_type = 'amends' ORDER BY lr.scope`);
+ expect(scopes).toEqual([{ scope: 'all', first_start: since }]);
+}
+
+/**
+ * Frozen clock: the process clock is pinned to the brain's date, and a future
+ * `since` amends edge stays visible in get_backlinks, traverse_graph and the
+ * entity card's edges, while a future-dated event of another type is hidden.
+ * The caller pins the clock (bun:test setSystemTime) to `today`.
+ */
+export async function futureAmendsStayVisible(engine: BrainEngine, today: string): Promise<void> {
+ expect(utcToday()).toBe(today);
+ const { since } = await seedAmendedContracts(engine, today);
+ await op('add_link').handler(ctx(engine), { from: 'contracts/msa-example-renewal', to: 'contracts/msa-example', link_type: 'discussed_in', valid_from: since });
+
+ const notices: string[] = [];
+ const meta: Record<string, unknown> = {};
+ const reader = { ...ctx(engine), emitNotice: (n: { code: string }) => { notices.push(n.code); }, emitResponseMeta: (k: string, v: unknown) => { meta[k] = v; } } as OperationContext;
+ const backlinks = await op('get_backlinks').handler(reader, { slug: 'contracts/msa-example' }) as Array<{ from_slug: string; link_type: string }>;
+ expect(backlinks.map(b => `${b.from_slug}:${b.link_type}`)).toEqual(['contracts/msa-example-amendment-2:amends']);
+ expect((meta['gbrain.temporal'] as { hidden: number }).hidden).toBe(1);
+ expect(notices).toContain('former_relationships_hidden');
+
+ for (const params of [{ as_of: today }, { as_of: addDays(today, -30) }]) {
+ const rows = await op('get_backlinks').handler(reader, { slug: 'contracts/msa-example', ...params }) as Array<{ from_slug: string; link_type: string; status: string; stints: unknown }>;
+ expect(rows.map(r => [r.link_type, r.status, r.stints])).toEqual([['amends', 'not_started', [{ from: since, until: null }]]]);
+ }
+ const history = await op('get_backlinks').handler(reader, { slug: 'contracts/msa-example', status: 'all' }) as Array<{ link_type: string; status: string }>;
+ expect(history.map(r => `${r.link_type}:${r.status}`).sort()).toEqual(['amends:not_started', 'discussed_in:not_started']);
+
+ const walked = await op('traverse_graph').handler(reader, { slug: 'contracts/msa-example-amendment-2', depth: 1 }) as unknown;
+ expect(JSON.stringify(walked)).toContain('contracts/msa-example"');
+ const remoteBacklinks = await op('get_backlinks').handler({ ...ctx(engine, true), emitNotice() {}, emitResponseMeta() {} } as OperationContext, { slug: 'contracts/msa-example' }) as Array<{ link_type: string }>;
+ expect(remoteBacklinks.map(b => b.link_type)).toEqual(['amends']);
+
+ for (let i = 0; i < 10; i++) {
+ await put(engine, `people/former-${i}-example`, `type: person\ntitle: Former ${i}`, 'A former contact.');
+ await op('add_link').handler(ctx(engine), { from: `people/former-${i}-example`, to: 'contracts/msa-example', link_type: 'works_at', valid_from: '2020-01-01', valid_until: '2021-01-01' });
+ }
+ await put(engine, 'contracts/msa-example-amendment-2', [
+ 'type: contract', 'title: MSA Example Amendment 2', 'amends:', ' - name: MSA Example', ` since: ${since}`,
+ ].join('\n'), `${AMENDMENT_TEXT} Restated.`);
+ const card = await buildEntityCard(engine, 'default', 'contracts/msa-example', { remote: false });
+ const edge = card.card!.edges.find(e => e.type === 'amends' && e.direction === 'in');
+ expect(edge).toEqual(expect.objectContaining({ slug: 'contracts/msa-example-amendment-2', status: 'not_started', since }));
+}
+
+/**
+ * Final search scores and labels: an amendment (current or future-effective)
+ * leaves the original's score unchanged and unlabeled, so its unchanged terms
+ * still rank; a genuine replacement (`supersedes`) halves it and labels it.
+ */
+export async function amendmentsVersusReplacement(engine: BrainEngine): Promise<void> {
+ await seed(engine, [contract('contracts/msa-example', 'MSA Example', MSA_TEXT),
+ contract('contracts/msa-example-amendment-1', 'MSA Example Amendment 1', AMENDMENT_TEXT),
+ contract('contracts/msa-example-amendment-2', 'MSA Example Amendment 2', `${AMENDMENT_TEXT} Support adds weekends.`),
+ contract('contracts/msa-example-v2', 'MSA Example v2', 'Replacement master services agreement. Payment terms are net 60.')]);
+ await engine.setConfig('schema_pack', EXAMPLE_PACK);
+ const query = 'payment terms support business days master services agreement';
+ const before = await searchOutput(engine, query);
+ const msaBefore = row(before, 'contracts/msa-example');
+
+ const future = addDays(await databaseToday(engine), 400);
+ await op('add_link').handler(ctx(engine), { from: 'contracts/msa-example-amendment-1', to: 'contracts/msa-example', link_type: 'amends' });
+ await op('add_link').handler(ctx(engine), { from: 'contracts/msa-example-amendment-2', to: 'contracts/msa-example', link_type: 'amends', valid_from: future });
+ const amended = await searchOutput(engine, query);
+ expect(amended).toEqual(before);
+ expect(row(amended, 'contracts/msa-example')).toEqual(expect.objectContaining({ superseded: undefined, superseded_by: undefined }));
+
+ await op('add_link').handler(ctx(engine), { from: 'contracts/msa-example-v2', to: 'contracts/msa-example', link_type: 'supersedes' });
+ const replaced = row(await searchOutput(engine, query), 'contracts/msa-example');
+ expect(replaced.superseded).toBe(true);
+ expect(replaced.superseded_by).toBe('contracts/msa-example-v2');
+ expect(replaced.score).toBeCloseTo(msaBefore.score * (replaced.backlink_boost ?? 1) * SUPERSEDE_PENALTY, 10);
+ expect(replaced.backlink_count).toBe(1);
+}
diff --git a/test/link-temporal-evidence.test.ts b/test/link-temporal-evidence.test.ts
index 2d91b33d95..8081092fa6 100644
--- a/test/link-temporal-evidence.test.ts
+++ b/test/link-temporal-evidence.test.ts
@@ -5,6 +5,7 @@
*/
import { describe, test, expect } from 'bun:test';
import { deriveTemporalEvidence, rowKey, normalizeLinkTarget, type OwnedRow } from '../src/core/link-temporal-evidence.ts';
+import { setPackRelationSemantics } from '../src/core/link-validity.ts';
const alice = 'people/alice-example';
const row = (to: string, link_type: string, extra: Partial<OwnedRow> = {}): OwnedRow => ({ from_slug: alice, to_slug: to, link_type, link_source: 'markdown', ...extra });
@@ -79,6 +80,32 @@ describe('frontmatter since/until', () => {
const ev = derive('', '', [r], { company: [{ name: 'Acme', since: '2021-04', until: '2024-02-15' }] });
expect(ev.transitions.map(t => `${t.kind}:${t.occurred_on}:${t.date_precision}:${t.producer}`)).toEqual(['start:2021-04-01:month:frontmatter', 'end:2024-02-15:day:frontmatter']);
});
+
+ test('targets sharing a slug prefix: each object dates only its exact target when several match', () => {
+ const page = 'contracts/msa-example-amendment-2';
+ const msa = { from_slug: page, to_slug: 'contracts/msa-example', link_type: 'amends', link_source: 'frontmatter', origin_field: 'amends' };
+ const renewal = { ...msa, to_slug: 'contracts/msa-example-renewal' };
+ const fm = { amends: [{ name: 'MSA Example', since: '2026-11-01' }, { name: 'MSA Example Renewal', since: '2027-03-01' }] };
+ setPackRelationSemantics(new Map([['amends', 'event']]));
+ let ev;
+ try { ev = deriveTemporalEvidence({ slug: page, compiled_truth: '', timeline: '', frontmatter: fm }, [msa, renewal]); }
+ finally { setPackRelationSemantics(new Map()); }
+ expect(ev.transitions.map(t => `${t.to_slug}:${t.kind}:${t.occurred_on}`).sort()).toEqual([
+ 'contracts/msa-example-renewal:start:2027-03-01',
+ 'contracts/msa-example:start:2026-11-01',
+ ]);
+ });
+
+ test('a single prefix match still dates its target; two prefix-only matches date nothing', () => {
+ const r = row('companies/acme-example', 'works_at', { link_source: 'frontmatter', origin_field: 'company' });
+ expect(brief(derive('', '', [r], { company: [{ name: 'Acme', since: '2021-04' }, { name: 'Widget', since: '2022-01' }] }).transitions))
+ .toEqual(['acme-example:works_at:start:2021-04-01:frontmatter']);
+ expect(derive('', '', [r], { company: [{ name: 'Acme', since: '2021-04' }, { name: 'Acme Example', since: '2022-01' }] }).transitions
+ .map(t => t.occurred_on)).toEqual(['2022-01-01']);
+ expect(derive('', '', [row('companies/acme-example-labs', 'works_at', { link_source: 'frontmatter', origin_field: 'company' })], {
+ company: [{ name: 'Acme', since: '2021-04' }, { name: 'Acme Example', since: '2022-01' }],
+ }).transitions).toEqual([]);
+ });
});
describe('assertion tense', () => {