Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

F5 known_as continuation: card next through get_backlinks group:"known_as"

garrytan88d1a8e3d08c
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.md
index 22d6aa489a..435ac9ae86 100644
--- a/docs/architecture/key-files/entity-recall.md
+++ b/docs/architecture/key-files/entity-recall.md
@@ -11,7 +11,7 @@ card and `get_backlinks`. Guide: [entity recall](../../guides/entity-recall.md).
- `src/core/mentions/aliases.ts` — derived names of an entity page, implementing `docs/designs/ALIAS_CONVENTIONS.md`. Stored aliases and card identity lines read declarations with `anchored: true` (a cue must attach to the page itself; search's per-result `aliasDeclarations` scan reads them all). `titleSubject` (text after the last `: `), `declarationsIn` (each declaration with its line: prose cues, label and value lines and table rows whose label names an alias field (also a label opening a later sentence of a line, alias noun within its first two words, at most 7 words), the quoted-only "calls it" cue, a quoted defined term right after the page's own name; a capture is a quoted name or a run of up to 4 capitalized or code tokens ending at punctuation, a lowercase word or the line end, rejected on a possessive, a run of only common words or a cue after a relational noun; linear in the line length), `declaredNames` (its post-filtered names, shared with search's `aliasDeclarations`), `deriveEntityAliases(page, {multiword, deny})` (subject `origin='subject'`, declarations `origin='declared'` with their lines, read from `publicBody`: private takes and facts fences stripped; a single-token declaration is `case_sensitive`; `mentions.alias_deny` and frontmatter `alias_deny` reject as `denied`). `aliasRejection`: under 4 characters (unless a short code the page declares for itself: a declaration marked `selfCode`), a generic word, or the first word of the page's own multi-word name. Rejections are returned with their line for explain. Tests: `test/mentions-policy-aliases.test.ts`.
- `src/core/mentions/short-codes.ts` — `isShortCode` (2-3 letters or digits with a capital, not in `SHORT_CODE_STOPLIST` of common capitals and business acronyms, compared upper-cased). `declarationsIn` marks a short code `selfCode` when an alias label or an `also called` / `a.k.a.` / `known as` / `short for` cue declares it in a sentence naming nothing before the cue but the page (empty, a pronoun or an own name); `aliasRejection` lets it through and `by-mention.ts` keeps a `declared`, `case_sensitive` short code in the gazetteer, matched only as written. Leaf module (aliases.ts imports by-mention.ts). Tests: `test/mentions-policy-aliases.test.ts`, `test/mentions-pass.test.ts`.
- `src/core/mentions/pass.ts` — `runMentionPass(engine, {sourceId?, deadline?, signal?, beforePublish?})`, run by `extractStaleFromDB` (unmanaged) and `extractManagedStaleLinks` (managed, unless `mentions: false`). Per source: policy off → `disableSource` deletes plain mention links (`link_kind` null or `plain`; `typed_ner` stays), derived alias rows, saved entries and page state once and records `disabled`; a changed policy fingerprint (types, cross-source flag, ignore list, `mentions.alias_deny`, `mentions.multiword_aliases`, `mentions.sibling_merge`) marks every page due and recounts `pending`; the status row's `policy_fingerprint` carries the extractor versions its count reflects after the hash (`<hash>;v<mention>.<alias>`, `INDEX_VERSION_STAMP`), and a stamp that differs from the binary's recounts `pending` once (version-behind pages are already due, so nothing is invalidated); `refreshAliases` rewrites derived rows of entity pages whose `page_mention_state.alias_revision`/`alias_version` differ (revision-checked, coordinated write when managed) and removes them from pages that stopped being entities; `buildGazetteer({strict: true})` failing writes nothing and records `failed`; `saveEntries` diffs `mention_gazetteer_entries` under `pg_advisory_xact_lock`, bumps the source generation and marks due only pages linking to a removed target plus pages a mini-gazetteer of added names matches (ASCII names prefiltered with `LIKE` on lower-cased text, others scanned in JS; a first save marks the source due); `reconcileSource` scans due pages (no state row, or `mention_revision`/`mention_version` differ) in batches of 200 and publishes only when the source generations (`FOR SHARE`) and each page's `knowledge_revision` (`FOR SHARE`) are unchanged, writing link diffs (`addLinksBatch`, audit site `extract.mentions`) and page state in one transaction; then the status row gets state, `pending` (`countIndexDuePages`: mention-due pages plus linkable entity pages whose derived aliases are behind their content or `ALIAS_DERIVATION_VERSION`, counted when the source finishes or the deadline stops it) and `last_pass_at`. `writeDerivedAliases` / `writePageAliases` are import's and `reindex --aliases`' alias projection. `MENTION_EXTRACTOR_VERSION` and `ALIAS_DERIVATION_VERSION` are independent of `LINK_EXTRACTOR_VERSION_TS`. The scanned text is title, compiled truth and timeline; frontmatter `mention_ignore` names are skipped per page. Tests: `test/mentions-pass.test.ts`, `test/mentions-coverage-version.test.ts`, `test/mentions-managed.test.ts`, `test/e2e/mentions-parity.test.ts`.
-- `src/core/mentions/owner-phrase/` — owner-phrase resolution with validity windows behind `mentions.owner_phrases` (default off; contract: [owner phrases](../../guides/owner-phrases.md)). `scan.ts` stores per page (`owner_phrase_page_state`, keyed by `knowledge_revision` and `OWNER_PHRASE_SCAN_VERSION`) the cue lines, owner phrases, declared descriptors, the non-fallback page date and the belated-note readings; `dates.ts` parses written dates; `statements.ts` turns cue lines into dated takeover/join/ongoing/end/stint/correction statements (agent-written pages set none); `windows.ts` applies corrections, assembles per-identity-group windows with inclusive bounds and resolves a phrase (temporal candidates first, then ambiguity refusal, readings must agree). `pass.ts` `runOwnerPhrasePass`, called per source from `runMentionPass` after the plain reconcile, rebuilds windows into `owner_phrase_windows` (generation bumps only when the window hash changes; a window whose evidence includes a private page records `private_page_id`) and diffs `link_source='mentions'`, `link_kind='owner_phrase'` links under `pg_advisory_xact_lock`, storing a private evidence page as `origin_page_id`; a page pair another link covers gets none, and a plain mention displaces the row (`mentions/pass.ts`). Key off removes rows, windows, scans and status once. `known-as.ts` is the card's bounded `known_as` read (10 rows plus total, private windows hidden from untrusted readers); `ranking.ts` `rankingLinkSql` keeps owner-phrase links out of the readers that count every link (adjacency boosts, entity anchoring, generated-page demotion). Tests: `test/owner-phrase-rules.test.ts`, `test/owner-phrase-pass.test.ts`, `test/e2e/owner-phrase-parity.test.ts`.
+- `src/core/mentions/owner-phrase/` — owner-phrase resolution with validity windows behind `mentions.owner_phrases` (default off; contract: [owner phrases](../../guides/owner-phrases.md)). `scan.ts` stores per page (`owner_phrase_page_state`, keyed by `knowledge_revision` and `OWNER_PHRASE_SCAN_VERSION`) the cue lines, owner phrases, declared descriptors, the non-fallback page date and the belated-note readings; `dates.ts` parses written dates; `statements.ts` turns cue lines into dated takeover/join/ongoing/end/stint/correction statements (agent-written pages set none); `windows.ts` applies corrections, assembles per-identity-group windows with inclusive bounds and resolves a phrase (temporal candidates first, then ambiguity refusal, readings must agree). `pass.ts` `runOwnerPhrasePass`, called per source from `runMentionPass` after the plain reconcile, rebuilds windows into `owner_phrase_windows` (generation bumps only when the window hash changes; a window whose evidence includes a private page records `private_page_id`) and diffs `link_source='mentions'`, `link_kind='owner_phrase'` links under `pg_advisory_xact_lock`, storing a private evidence page as `origin_page_id`; a page pair another link covers gets none, and a plain mention displaces the row (`mentions/pass.ts`). Key off removes rows, windows, scans and status once. `known-as.ts` is the card's bounded `known_as` read (10 rows plus total, private windows hidden from untrusted readers) and its keyset continuation, served as `get_backlinks` `group: "known_as"` (`ops/backlinks-paged.ts`); `ranking.ts` `rankingLinkSql` keeps owner-phrase links out of the readers that count every link (adjacency boosts, entity anchoring, generated-page demotion). Tests: `test/owner-phrase-rules.test.ts`, `test/owner-phrase-pass.test.ts`, `test/e2e/owner-phrase-parity.test.ts`.
- `src/core/mentions/stale.ts` — the pass as a sweep phase: `previewMentionPass` (index-due pages per source, as `countIndexDuePages` counts them, and newest `last_pass_at`, for `--dry-run`, doctor `links_extraction_lag` and post-upgrade), `linkPhaseDeadline` (a budgeted sweep gives link work half its budget while mention-due pages exist), `formatMentionSummary`, `mentionJsonFields`.
- `src/core/mentions/coverage.ts` — `readMentionCoverage(engine, sourceIds)`: `{state, pending_pages, last_pass_at, degraded?}` from `mention_index_status` plus due pages written at or after the row's `counted_at` (states `complete`, `pending`, `disabled`, `failed`; the card adds `type_not_linkable`). A row whose version stamp differs from the binary's (counted by another release) is recounted once with `countIndexDuePages` and the count and stamp saved on the row (compare-and-set on the stored fingerprint; a failed write still returns the count), so after a version bump every page behind `MENTION_EXTRACTOR_VERSION` or `ALIAS_DERIVATION_VERSION` reads as pending whatever its `updated_at`, and later reads stay one status read plus the recent-pages query. Policy settings changes are detected by the pass, not here. `mentionCoverageNotice` builds the `mention_index` notice (kind `degraded`, a per-call code): the free catch-up sweep for pending/failed, the user's setting for disabled/type-not-linkable, each with a read-only verify.
- `src/core/mentions/referrers.ts` — the shared referrer query behind `referenced_by` and `get_backlinks {group:"page"}`: one row per referring page (every link source), semi-join over links to the target (plus identity co-members under `entity_identity.union`), canonical type via bound alias arrays, date `COALESCE(effective_date, updated_at)` with `date_source`, previews (160 characters after an optional `# ` heading, fences stripped, `redactFindings`). `readReferrerGroups`: per-type totals and a bounded top-10 per type, water-filled to 50 rows per card. `readReferrerPage`: keyset paging on `(date DESC, source_id, slug)` with an opaque cursor (microsecond UTC text). Untrusted scopes apply `privatePagesFilterFragment` to referrer and target and `privateLinkOriginFilterFragment` to the link, in rows and counts. #5575: quarantined referrers are left out (rows and counts) unless `includeQuarantined`, the scope's `eligibility` (`pageEligibleSql`) applies before LIMIT, and each row carries `trust_tier`, `origin` and `unconfirmed` from `trustFields`. Tests: `test/mentions-card-backlinks.test.ts`, `test/context-pack-newer-mentions.test.ts`, `test/entity-card-perf.slow.test.ts` (10,000-link hub gate).
diff --git a/docs/guides/owner-phrases.md b/docs/guides/owner-phrases.md
index 1e51c7d5a3..2eea3bbd0c 100644
--- a/docs/guides/owner-phrases.md
+++ b/docs/guides/owner-phrases.md
@@ -144,7 +144,9 @@ The rules below are general to any brain. Each line is covered by a test row in
that page as `origin_page_id`. Remote and world-scope readers apply the
link-origin privacy check and do not see the link. Trusted local reads do.
`known_as` rows on the card follow the same rule. The card shows at most
- 10 `known_as` rows, newest window first, with the `total`.
+ 10 `known_as` rows, newest window first, with the `total`. When rows <
+ total, `known_as.next` is an executable `get_backlinks` call with
+ `group: "known_as"` and a cursor that returns the rest in the same order.
13. **Invalidation.** A page is rescanned when its content revision or the
owner-phrase version changes. Windows are rebuilt from every page's stored
statements on each pass, and links are diffed against them. So a window
diff --git a/src/core/mentions/owner-phrase/known-as.ts b/src/core/mentions/owner-phrase/known-as.ts
index 049ec1452e..693675c40b 100644
--- a/src/core/mentions/owner-phrase/known-as.ts
+++ b/src/core/mentions/owner-phrase/known-as.ts
@@ -1,14 +1,18 @@
/**
* The entity card's `known_as` rows: each owner of an account with the
* validity window of its owner phrase ("<owner>'s <descriptor> account"),
- * read from `owner_phrase_windows`. Bounded at KNOWN_AS_MAX rows with the
- * total. Untrusted readers never see a window whose evidence includes a
- * private page. Owner phrases are never aliases: they stay out of `aka`,
- * `page_aliases` and search alias fan-out. Fail-soft: a read error returns
- * nothing.
+ * read from `owner_phrase_windows`. The card shows KNOWN_AS_MAX rows with the
+ * total; when rows < total it carries a `next` continuation through the
+ * card's existing mechanism: `get_backlinks` with `group: "known_as"` and a
+ * keyset cursor, ordered newest window first by (start, owner, account group,
+ * end), so the continuation reproduces the card's order exactly. Untrusted
+ * readers never see a window whose evidence includes a private page. Owner
+ * phrases are never aliases: they stay out of `aka`, `page_aliases` and search
+ * alias fan-out. The card read is fail-soft (a read error returns nothing).
*/
import type { BrainEngine } from '../../engine.ts';
+import { PAGE_DEFAULT_LIMIT } from '../referrers.ts';
export const KNOWN_AS_MAX = 10;
@@ -24,26 +28,66 @@ export interface KnownAsRow {
evidence: Array<{ slug: string; line: number; kind: string }>;
}
-export interface KnownAs { rows: KnownAsRow[]; total: number }
+export interface KnownAsNext { tool: 'get_backlinks'; arguments: Record<string, unknown>; requires_surface?: 'starter' }
+export interface KnownAs { rows: KnownAsRow[]; total: number; next?: KnownAsNext }
-export async function readKnownAs(engine: BrainEngine, sourceId: string, slug: string, opts: { excludePrivate: boolean }): Promise<{ known_as?: KnownAs }> {
+type Key = [string, string, string, string];
+const NO_START = '0001-01-01';
+const NO_END = '9999-12-31';
+
+export function encodeKnownAsCursor(key: Key): string {
+ return Buffer.from(JSON.stringify(['known_as', ...key])).toString('base64url');
+}
+
+export function decodeKnownAsCursor(cursor: string): Key | null {
+ try {
+ const v = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
+ if (Array.isArray(v) && v.length === 5 && v[0] === 'known_as' && v.slice(1).every(x => typeof x === 'string')) return v.slice(1) as Key;
+ } catch { /* invalid */ }
+ return null;
+}
+
+/** One page of an account's windows, newest first; `cursor` continues after the last row. */
+export async function readKnownAsPage(engine: BrainEngine, sourceId: string, slug: string,
+ opts: { excludePrivate: boolean; limit: number; after?: Key | null }): Promise<{ rows: KnownAsRow[]; total: number; cursor: string | null }> {
+ const params: unknown[] = [sourceId, slug, opts.limit];
+ const scope = `source_id = $1 AND (group_key = $2 OR $2 = ANY(account_slugs))${opts.excludePrivate ? ' AND private_page_id IS NULL' : ''}`;
+ let keyset = '';
+ if (opts.after) {
+ params.push(...opts.after);
+ keyset = `AND (d < $4 OR (d = $4 AND (owner_key COLLATE "C", group_key COLLATE "C", e) > ($5, $6, $7)))`;
+ }
+ const rows = await engine.executeRaw<{ owner_name: string; owner_key: string; group_key: string; descriptors: string[]; f: string | null; t: string | null;
+ d: string; e: string; start_known: boolean; evidence: unknown; total: number; remaining: number }>(
+ `SELECT w.*, count(*) OVER ()::int AS remaining FROM (
+ SELECT owner_name, owner_key, group_key, descriptors, valid_from::text AS f, valid_to::text AS t,
+ COALESCE(valid_from::text, '${NO_START}') AS d, COALESCE(valid_to::text, '${NO_END}') AS e, start_known, evidence,
+ count(*) OVER ()::int AS total
+ FROM owner_phrase_windows WHERE ${scope}) w
+ WHERE TRUE ${keyset}
+ ORDER BY d DESC, owner_key COLLATE "C", group_key COLLATE "C", e LIMIT $3`, params);
+ const total = rows.length ? Number(rows[0]!.total)
+ : Number((await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM owner_phrase_windows WHERE ${scope}`, [sourceId, slug]))[0]?.n ?? 0);
+ const out = rows.map(r => {
+ const evidence = (typeof r.evidence === 'string' ? JSON.parse(r.evidence) : r.evidence) as Array<{ slug: string; line: number; kind: string }>;
+ return { owner: r.owner_name, descriptors: r.descriptors ?? [], from: r.f, to: r.t, start_known: r.start_known,
+ evidence: evidence.map(e => ({ slug: e.slug, line: e.line, kind: e.kind })) };
+ });
+ const last = rows[rows.length - 1];
+ const more = last != null && Number(last.remaining) > rows.length;
+ return { rows: out, total, cursor: more ? encodeKnownAsCursor([last.d, last.owner_key, last.group_key, last.e]) : null };
+}
+
+export async function readKnownAs(engine: BrainEngine, sourceId: string, slug: string,
+ opts: { excludePrivate: boolean; surfaceCeiling?: string }): Promise<{ known_as?: KnownAs }> {
try {
- const rows = await engine.executeRaw<{ owner_name: string; descriptors: string[]; f: string | null; t: string | null; start_known: boolean; evidence: unknown; total: number }>(
- `SELECT owner_name, descriptors, valid_from::text AS f, valid_to::text AS t, start_known, evidence, count(*) OVER ()::int AS total
- FROM owner_phrase_windows
- WHERE source_id = $1 AND (group_key = $2 OR $2 = ANY(account_slugs))${opts.excludePrivate ? ' AND private_page_id IS NULL' : ''}
- ORDER BY valid_from DESC NULLS LAST, owner_name LIMIT $3`, [sourceId, slug, KNOWN_AS_MAX]);
- if (!rows.length) return {};
- return {
- known_as: {
- total: Number(rows[0]!.total),
- rows: rows.map(r => {
- const evidence = (typeof r.evidence === 'string' ? JSON.parse(r.evidence) : r.evidence) as Array<{ slug: string; line: number; kind: string }>;
- return { owner: r.owner_name, descriptors: r.descriptors ?? [], from: r.f, to: r.t, start_known: r.start_known,
- evidence: evidence.map(e => ({ slug: e.slug, line: e.line, kind: e.kind })) };
- }),
- },
- };
+ const page = await readKnownAsPage(engine, sourceId, slug, { excludePrivate: opts.excludePrivate, limit: KNOWN_AS_MAX });
+ if (!page.rows.length) return {};
+ const next: KnownAsNext | undefined = page.rows.length < page.total && page.cursor ? {
+ tool: 'get_backlinks', arguments: { slug, source_id: sourceId, group: 'known_as', limit: PAGE_DEFAULT_LIMIT, cursor: page.cursor },
+ ...(opts.surfaceCeiling === 'verbs' ? { requires_surface: 'starter' as const } : {}),
+ } : undefined;
+ return { known_as: { rows: page.rows, total: page.total, ...(next ? { next } : {}) } };
} catch {
return {};
}
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 4ffff38307..6c4f8af838 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -1621,10 +1621,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"group": {
"type": "string",
- "enum": [
- "page"
- ],
- "description": "Per page."
+ "description": "page or known_as."
},
"limit": {
"type": "number",
diff --git a/src/core/ops/backlinks-paged.ts b/src/core/ops/backlinks-paged.ts
index 94b7b436fa..453b3170b5 100644
--- a/src/core/ops/backlinks-paged.ts
+++ b/src/core/ops/backlinks-paged.ts
@@ -7,7 +7,8 @@
* `{rows, total, truncated, cursor, coverage}`: one row per referring page,
* newest first by `(date DESC, source_id, slug)`, read through the same
* helper as the entity card's `referenced_by`, so a card group's `next` call
- * continues it exactly.
+ * continues it exactly. `group: "known_as"` pages the card's owner windows
+ * (`known_as.next`) with the same `{rows, total, truncated, cursor}` shape.
*/
import { opError, type OperationContext } from './contract.ts';
@@ -18,6 +19,7 @@ import {
decodeCursor, readReferrerPage, referrerTypes, PAGE_DEFAULT_LIMIT, PAGE_MAX_LIMIT, type ReferenceRow, type ReferrerScope,
} from '../mentions/referrers.ts';
import { mentionCoverageNotice, readMentionCoverage, type MentionCoverage } from '../mentions/coverage.ts';
+import { decodeKnownAsCursor, readKnownAsPage, type KnownAsRow } from '../mentions/owner-phrase/known-as.ts';
export interface BacklinkPage {
rows: ReferenceRow[];
@@ -81,9 +83,10 @@ async function assertKnownType(ctx: OperationContext, scope: ReferrerScope, type
* `group: "page"`: one page of referring pages. A slug with no live page in
* scope answers like an empty read (no rows, total 0).
*/
-export async function readBacklinkPage(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<BacklinkPage> {
+export async function readBacklinkPage(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<BacklinkPage | KnownAsPage> {
+ if (p.group === 'known_as') return readKnownAsGroup(ctx, p, policy);
if (p.group !== 'page') {
- throw opError('invalid_params', `get_backlinks: group must be "page".`, 'Pass group: "page" for one row per referring page, or omit group for link rows.');
+ throw opError('invalid_params', `get_backlinks: group must be "page" or "known_as".`, 'Pass group: "page" for one row per referring page, group: "known_as" for the card\'s owner windows, or omit group for link rows.');
}
const limit = parseLimit(p, PAGE_DEFAULT_LIMIT)!;
const cursor = p.cursor === undefined ? null : decodeCursor(String(p.cursor));
@@ -100,6 +103,28 @@ export async function readBacklinkPage(ctx: OperationContext, p: Record<string,
return { ...await readReferrerPage(ctx.engine, resolved.scope, { type, limit, cursor }), coverage };
}
+export interface KnownAsPage { rows: KnownAsRow[]; total: number; truncated: boolean; cursor: string | null }
+
+/**
+ * `group: "known_as"`: one page of the entity card's owner windows
+ * (mentions/owner-phrase/known-as.ts), continuing a card's `known_as.next`.
+ * A slug with no live page in scope answers like an empty read.
+ */
+async function readKnownAsGroup(ctx: OperationContext, p: Record<string, unknown>, policy: PageReadPolicy): Promise<KnownAsPage> {
+ if (p.type !== undefined) {
+ throw opError('invalid_params', 'get_backlinks: type does not apply to group: "known_as".', 'Omit type with group: "known_as".');
+ }
+ const limit = parseLimit(p, PAGE_DEFAULT_LIMIT)!;
+ const after = p.cursor === undefined ? null : decodeKnownAsCursor(String(p.cursor));
+ if (p.cursor !== undefined && !after) {
+ throw opError('invalid_params', 'get_backlinks: cursor is not one this tool returned.', 'Pass the cursor from the previous known_as response unchanged, or omit it to start from the newest window.');
+ }
+ const sourceId = await targetSource(ctx, String(p.slug), await scopeSources(ctx, policy));
+ if (!sourceId) return { rows: [], total: 0, truncated: false, cursor: null };
+ const page = await readKnownAsPage(ctx.engine, sourceId, String(p.slug), { excludePrivate: policy.excludePrivate === true, limit, after });
+ return { rows: page.rows, total: page.total, truncated: page.cursor !== null, cursor: page.cursor };
+}
+
/**
* Array mode with `type` and/or `limit`: today's link rows, filtered by the
* referring page's type and cut at `limit` (a cut is reported with a
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index f496558410..b0562e5b54 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -405,7 +405,7 @@ const get_backlinks: Operation = {
source_id: LINK_SOURCE_ID_PARAM,
all_sources: LINK_ALL_SOURCES_PARAM,
type: { type: 'string', description: 'Referrer type.' },
- group: { type: 'string', enum: ['page'], description: 'Per page.' },
+ group: { type: 'string', description: 'page or known_as.' },
limit: { type: 'number', description: 'Max 500.' },
cursor: { type: 'string', description: 'Paging.' },
},
diff --git a/src/core/verbs/entity-card.ts b/src/core/verbs/entity-card.ts
index e4f3e8db93..97ed7108c0 100644
--- a/src/core/verbs/entity-card.ts
+++ b/src/core/verbs/entity-card.ts
@@ -329,7 +329,7 @@ export async function buildEntityCard(
if (opts.includeReferences) {
Object.assign(card, await cardReferences(engine, sourceId, best.row, opts, excludePrivate, entityTypes),
await readCardIdentity(engine, sourceId, best.row, { excludePrivate, excludeQuarantined: opts.omitQuarantined === true, surfaceCeiling: opts.surfaceCeiling, aka: card.aka }),
- await readKnownAs(engine, sourceId, best.row.slug, { excludePrivate }));
+ await readKnownAs(engine, sourceId, best.row.slug, { excludePrivate, surfaceCeiling: opts.surfaceCeiling }));
}
return {
found: true,
diff --git a/test/e2e/owner-phrase-parity.test.ts b/test/e2e/owner-phrase-parity.test.ts
index f20a9add40..668c20af9b 100644
--- a/test/e2e/owner-phrase-parity.test.ts
+++ b/test/e2e/owner-phrase-parity.test.ts
@@ -3,7 +3,8 @@
*
* Protects: the v240 migration (link_kind CHECK accepting 'owner_phrase',
* the windowed tables) and the owner-phrase pass producing the same windows,
- * links, counters, visibility and `known_as` rows on both engines, plus a
+ * links, counters, visibility, `known_as` rows and their get_backlinks
+ * continuation on both engines, plus a
* correction, a deletion, disable, and two passes racing over a real
* connection pool on Postgres (the advisory lock serializes publication).
* Regression: an engine-specific SQL difference in the jsonb batch writes,
@@ -17,7 +18,7 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { buildGazetteer } from '../../src/core/by-mention.ts';
import { linkableTypesFor, loadSourcePack, readMentionPolicy } from '../../src/core/mentions/policy.ts';
import { runOwnerPhrasePass } from '../../src/core/mentions/owner-phrase/pass.ts';
-import { ACME, NIMBUS, doc, ownerPhraseLinks, ownerPhraseSnapshot, seedOwnerPhraseBrain, sweepOwnerPhrases, windowRows } from '../helpers/owner-phrase-brain.ts';
+import { ACME, NIMBUS, doc, knownAsContinuation, ownerPhraseLinks, ownerPhraseSnapshot, seedOwnerPhraseBrain, sweepOwnerPhrases, windowRows } from '../helpers/owner-phrase-brain.ts';
import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
const SKIP_PG = !hasDatabase();
@@ -53,12 +54,14 @@ async function checkConstraint(engine: BrainEngine) {
let pglite: PGLiteEngine;
let pgliteSnap: Awaited<ReturnType<typeof ownerPhraseSnapshot>>;
let pgliteLife: Awaited<ReturnType<typeof lifecycle>>;
+let pgliteKnownAs: Awaited<ReturnType<typeof knownAsContinuation>>;
beforeAll(async () => {
pglite = new PGLiteEngine();
await pglite.connect({});
await pglite.initSchema();
await seedOwnerPhraseBrain(pglite);
pgliteSnap = await ownerPhraseSnapshot(pglite);
+ pgliteKnownAs = await knownAsContinuation(pglite);
pgliteLife = await lifecycle(pglite);
}, 180_000);
afterAll(async () => { await pglite.disconnect(); });
@@ -71,6 +74,8 @@ describe('owner phrases (PGLite half)', () => {
expect(pgliteLife.afterRace).toContain(`notes/new-call -> ${NIMBUS}`);
expect(pgliteLife.deleted.filter(l => l.endsWith(ACME))).toEqual([]);
expect(pgliteLife.disabled).toEqual({ state: 'off', links: [], windows: [] });
+ expect(pgliteKnownAs.trusted.followed).toEqual(pgliteKnownAs.trusted.all);
+ expect(pgliteKnownAs.trusted).toMatchObject({ total: 14, shown: 10 });
});
});
@@ -88,6 +93,10 @@ describeBoth('owner phrases (Postgres parity)', () => {
expect(await ownerPhraseSnapshot(pg)).toEqual(pgliteSnap);
});
+ test('the known_as continuation (card next followed through get_backlinks) matches PGLite', async () => {
+ expect(await knownAsContinuation(pg)).toEqual(pgliteKnownAs);
+ });
+
test('correction, a pooled race, deletion and disable match PGLite', async () => {
expect(await lifecycle(pg)).toEqual(pgliteLife);
});
diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.json
index c516012960..a54e49edb0 100644
--- a/test/fixtures/goldens/cli/tools-json.json
+++ b/test/fixtures/goldens/cli/tools-json.json
@@ -2,8 +2,8 @@
"golden": {
"exitCode": 0,
"stderr": "",
- "stdoutBytes": 231140,
- "stdoutSha256": "bb979a78c5e89bb88016cc8af97c2215136976a11b8fdba6de37d572d83dc54d",
+ "stdoutBytes": 231096,
+ "stdoutSha256": "435c54d9550675983ba1320461cc5ee8937930ac316fdb44b2e86d65f6b56f9f",
"toolNames": [
"remember",
"entity",
@@ -1975,10 +1975,7 @@
"type": "string"
},
"group": {
- "description": "Per page.",
- "enum": [
- "page"
- ],
+ "description": "page or known_as.",
"type": "string"
},
"limit": {
diff --git a/test/helpers/owner-phrase-brain.ts b/test/helpers/owner-phrase-brain.ts
index 18e6d7b52c..9f5d64d87c 100644
--- a/test/helpers/owner-phrase-brain.ts
+++ b/test/helpers/owner-phrase-brain.ts
@@ -90,3 +90,44 @@ export async function ownerPhraseSnapshot(engine: BrainEngine) {
knownAsRemote: (await card(true))?.rows.map(r => `${r.owner} ${r.from ?? '?'}..${r.to ?? 'open'}`) ?? [],
};
}
+
+/**
+ * Twelve dated stints on one account (more than the card's 10 `known_as` rows),
+ * then the card and its `known_as.next` continuation followed to the end
+ * through `get_backlinks`. Returns owners in served order per reader.
+ */
+export async function knownAsContinuation(engine: BrainEngine) {
+ const { dispatchToolCall } = await import('../../src/mcp/dispatch.ts');
+ const names = ['Alder', 'Birch', 'Cedar', 'Dogwood', 'Elm', 'Fir', 'Ginkgo', 'Hazel', 'Ivy', 'Kauri', 'Linden', 'Maple'];
+ await doc(engine, 'companies/orbit-example-labs', 'Segment: research', { type: 'company', title: 'Orbit Example Labs' });
+ await doc(engine, 'meetings/orbit-history', ['| Account | Owner | Start | End |', '|---|---|---|---|',
+ ...names.map((n, i) => `| Orbit Example Labs | ${n} Example | ${2010 + i}-01-01 | ${2010 + i}-12-31 |`)].join('\n'), { date: '2024-01-05' });
+ await doc(engine, 'notes/orbit-private', 'Orbit Example Labs moves from Maple Example to Quill Example, effective 2023-02-01.', { date: '2023-01-20', private: true });
+ await sweepOwnerPhrases(engine);
+ const config = { engine: 'pglite' };
+ const local = { remote: false, sourceId: 'default', config };
+ const remote = { remote: true, transport: 'stdio', sourceId: 'default', takesHoldersAllowList: ['world'], config };
+ const call = async (op: string, args: Record<string, unknown>, ctx: Record<string, unknown>) => {
+ const r = await dispatchToolCall(engine, op, args, ctx as never);
+ return r.isError ? { error: r.content[0]!.text } : JSON.parse(r.content[0]!.text);
+ };
+ const follow = async (ctx: Record<string, unknown>) => {
+ const card = (await call('entity', { name: 'Orbit Example Labs' }, ctx)).card.known_as;
+ const owners: string[] = card.rows.map((r: { owner: string }) => r.owner);
+ const pages: number[] = [];
+ let next = card.next?.arguments ? { ...card.next.arguments, limit: 1 } : null;
+ while (next) {
+ const page = await call('get_backlinks', next, ctx);
+ pages.push(page.rows.length);
+ owners.push(...page.rows.map((r: { owner: string }) => r.owner));
+ next = page.cursor ? { ...next, cursor: page.cursor } : null;
+ }
+ const all = await call('get_backlinks', { slug: 'companies/orbit-example-labs', group: 'known_as', limit: 500 }, ctx);
+ return { total: card.total, shown: card.rows.length, next: card.next ? { tool: card.next.tool, group: card.next.arguments.group, requires_surface: card.next.requires_surface ?? null } : null,
+ followed: owners, pages, all: all.rows.map((r: { owner: string }) => r.owner), allTotal: all.total, truncated: all.truncated };
+ };
+ const verbs = (await call('entity', { name: 'Orbit Example Labs' }, { ...remote, surfaceCeiling: 'verbs' })).card.known_as.next?.requires_surface ?? null;
+ const badCursor = await call('get_backlinks', { slug: 'companies/orbit-example-labs', group: 'known_as', cursor: 'nope' }, local);
+ const withType = await call('get_backlinks', { slug: 'companies/orbit-example-labs', group: 'known_as', type: 'note' }, local);
+ return { trusted: await follow(local), remote: await follow(remote), verbs, badCursor: 'error' in badCursor, withType: 'error' in withType };
+}
diff --git a/test/owner-phrase-pass.test.ts b/test/owner-phrase-pass.test.ts
index 76ab6e712f..40b10c4b65 100644
--- a/test/owner-phrase-pass.test.ts
+++ b/test/owner-phrase-pass.test.ts
@@ -24,7 +24,7 @@ import { buildEntityCard } from '../src/core/verbs/entity-card.ts';
import { entityAnchoredPages } from '../src/core/search/entity-anchor.ts';
import { applyGeneratedDemotion } from '../src/core/search/provenance-demotion.ts';
import type { SearchResult } from '../src/core/types.ts';
-import { ACME, NIMBUS, WIDGET, doc, ownerPhraseLinks, ownerPhraseSnapshot, seedOwnerPhraseBrain, sweepOwnerPhrases, windowRows } from './helpers/owner-phrase-brain.ts';
+import { ACME, NIMBUS, WIDGET, doc, knownAsContinuation, ownerPhraseLinks, ownerPhraseSnapshot, seedOwnerPhraseBrain, sweepOwnerPhrases, windowRows } from './helpers/owner-phrase-brain.ts';
let engine: PGLiteEngine;
let snap: Awaited<ReturnType<typeof ownerPhraseSnapshot>>;
@@ -157,6 +157,25 @@ describe('final-score invariance', () => {
});
});
+describe('known_as continuation', () => {
+ test('rows < total carries a get_backlinks group:"known_as" next that continues the card in order to the end; private windows stay hidden from untrusted reads', async () => {
+ const r = await knownAsContinuation(engine);
+ const owners = ['Quill Example', 'Maple Example', 'Linden Example', 'Kauri Example', 'Ivy Example', 'Hazel Example', 'Ginkgo Example', 'Fir Example',
+ 'Dogwood Example', 'Elm Example', 'Cedar Example', 'Birch Example', 'Alder Example'];
+ // 12 table stints, Quill's private takeover and Maple's private predecessor window ending the day before it.
+ expect(r.trusted).toMatchObject({ total: 14, shown: 10, next: { tool: 'get_backlinks', group: 'known_as', requires_surface: null }, allTotal: 14, truncated: false });
+ expect(r.trusted.all.slice(0, 3)).toEqual(['Quill Example', 'Maple Example', 'Maple Example']);
+ expect(r.trusted.followed).toEqual(r.trusted.all);
+ expect(r.trusted.pages).toEqual([1, 1, 1, 1]);
+ expect(r.remote).toMatchObject({ total: 12, shown: 10, allTotal: 12 });
+ expect(r.remote.followed).toEqual(r.remote.all);
+ expect(r.remote.all).not.toContain('Quill Example');
+ expect(new Set(r.trusted.all)).toEqual(new Set(owners));
+ expect(r.verbs).toBe('starter');
+ expect([r.badCursor, r.withType]).toEqual([true, true]);
+ });
+});
+
describe('invalidation', () => {
test('a correction ends the wrong stint and relinks documents that were not edited; the generation advances', async () => {
const before = Number((await engine.executeRaw<{ g: string }>('SELECT generation::text AS g FROM owner_phrase_status'))[0]!.g);