Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
F5: docs for descriptor rules and the precision sample; --source all; rule tests
garrytan5756f61558f0
diff --git a/docs/architecture/key-files/entity-recall.md b/docs/architecture/key-files/entity-recall.mdindex 435ac9ae86..562a47bdd9 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) 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/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). `sample.ts` derives the links the pass would store without writes (in-memory scans fed to `buildOwnerPhraseModel`) and implements sampling rule v1, the labeling TSV and the Wilson bound for `scripts/owner-phrase-sample.ts`. Tests: `test/owner-phrase-rules.test.ts`, `test/owner-phrase-pass.test.ts`, `test/owner-phrase-sample.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.mdindex 2eea3bbd0c..9130a03233 100644--- a/docs/guides/owner-phrases.md+++ b/docs/guides/owner-phrases.md@@ -117,11 +117,16 @@ The rules below are general to any brain. Each line is covered by a test row inaliases (without corporate suffixes such as Inc, LLC, Co or Group), plusdeclared descriptors on the account page: "X is our <d> account", "knowninternally as the <d> account", and the `segment`, `industry`, `vertical`,- `sector`, `category` and `descriptor` labels or frontmatter keys.+ `sector`, `category`, `descriptor`, `region` and `territory` labels or+ frontmatter keys. A label counts at the start of a line or after a+ sentence boundary ("Account: X. Industry: food. Region: EMEA.").8. **Owner phrases.** "<Name>'s <d> account" (also book, client, customer,relationship, portfolio, book of business) and "the <d> account (that) <Name>- runs / handles / owns / manages / covers / leads". The descriptor must be- the whole run between the possessive and the noun. A plural noun, a name+ runs / handles / owns / manages / covers / leads". The descriptor is the+ whole run between the possessive and the noun, one to three words. It+ matches an account when the run is one of the account's descriptors, or+ when every word of the run is a word of its descriptors ("EMEA software"+ for an account with region EMEA and industry software). A plural noun, a namethat is itself an account or company, and a sentence about personal orbenefit accounts (benefits, HSA, FSA, 401k, payroll, bank, login, password)are not owner phrases. A one-word name matches an owner by first name, a@@ -155,3 +160,38 @@ The rules below are general to any brain. Each line is covered by a test row inEvery pass reports `links`, `documents`, `unresolved`, `ambiguous` and`windows` under `mentions.owner_phrases` in `gbrain extract --stale --json`.++## Precision sample++Before the key's default can change, a labeled sample of derived links from a+real brain must show precision at a Wilson 95% lower bound of 0.85 or more+(at least 57 of 60 correct, or 92 of 100). `scripts/owner-phrase-sample.ts`+draws that sample without writing anything:++- It derives the windows and links the pass would store, inside a `READ ONLY`+ transaction, with no model or network calls. The key can stay off.+- Sampling rule v1, fixed before any sample is drawn: one population row per+ (document, account page) link; rows are ranked by+ sha256(`owner-phrase-sample-v1`, seed, document slug, account slug) and the+ first `--n` (default 100) are taken. The same brain and seed give the same+ sample.+- Fewer than 22 derivable links is a refusal (exit 3); nothing is written.+- The TSV goes only to the path given with `--out` (mode 0600; an existing file+ needs `--force`). Columns: `id`, `doc_slug`, `phrase`, `line_excerpt`,+ `account`, `window`, `evidence_page`, `label`. stdout carries counts only.++From a checkout of the branch, against a copy of a PGLite brain or a live+Postgres brain:++```bash+cd ~/gbrain-f5 && bun install+cp -a "$(jq -r .database_path ~/.gbrain/config.json)" /tmp/brain-f5-copy # PGLite only; copy while nothing writes+bun scripts/owner-phrase-sample.ts --pglite /tmp/brain-f5-copy --source all --seed "<seed>" --n 100 --out ~/f5-sample.tsv+# Postgres brain: omit --pglite; the script reads ~/.gbrain/config.json+# label each row y (the document means that account) or n in the label column, then:+bun scripts/owner-phrase-sample.ts --score ~/f5-sample.tsv+```++`--score` prints the labeled, correct and wrong counts and the Wilson 95%+lower bound. The TSV stays with the owner; only the counts and the bound are+published.diff --git a/scripts/owner-phrase-sample.ts b/scripts/owner-phrase-sample.tsindex 5d4eaa25b3..6c27c45d7f 100644--- a/scripts/owner-phrase-sample.ts+++ b/scripts/owner-phrase-sample.ts@@ -7,7 +7,10 @@* calls, then writes a labeling TSV of a reproducible sample to the path the* operator names. stdout carries counts only, never page names or text.*- * bun scripts/owner-phrase-sample.ts --out <file.tsv> --seed <seed> [--source <id>] [--n 100] [--pglite <dir>] [--force]+ * bun scripts/owner-phrase-sample.ts --out <file.tsv> --seed <seed> [--source <id>|all] [--n 100] [--pglite <dir>] [--force]+ *+ * `--source all` derives every source and samples the union (slugs are+ * written as <source>:<slug>).* bun scripts/owner-phrase-sample.ts --score <labeled.tsv>** Exit codes: 0 written (or scored), 1 usage or runtime error, 3 refused@@ -19,10 +22,10 @@ import { loadConfig, toEngineConfig } from '../src/core/config.ts';import { createEngine } from '../src/core/engine-factory.ts';import type { EngineConfig } from '../src/core/types.ts';import {- deriveOwnerPhraseLinks, lineExcerpt, sampleLinks, scoreLabels, toTsv, SAMPLE_DEFAULT_SIZE, SAMPLE_MIN_POPULATION, SAMPLE_RULE,+ deriveOwnerPhraseLinks, lineExcerpt, sampleLinks, scoreLabels, toTsv, SAMPLE_DEFAULT_SIZE, SAMPLE_MIN_POPULATION, SAMPLE_RULE, type DerivedLink,} from '../src/core/mentions/owner-phrase/sample.ts';-const USAGE = 'usage: bun scripts/owner-phrase-sample.ts --out <file.tsv> --seed <seed> [--source <id>] [--n 100] [--pglite <dir>] [--force]\n'+const USAGE = 'usage: bun scripts/owner-phrase-sample.ts --out <file.tsv> --seed <seed> [--source <id>|all] [--n 100] [--pglite <dir>] [--force]\n'+ ' bun scripts/owner-phrase-sample.ts --score <labeled.tsv>';const args = process.argv.slice(2);const flag = (name: string) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined; };@@ -53,13 +56,23 @@ let code = 0;try {const result = await engine.transaction(async tx => {await tx.executeRaw('SET TRANSACTION READ ONLY');- const derived = await deriveOwnerPhraseLinks(tx, sourceId);+ const sources = sourceId === 'all' ? (await tx.executeRaw<{ id: string }>('SELECT id FROM sources ORDER BY id')).map(r => r.id) : [sourceId];+ const derived = { links: [] as Array<DerivedLink & { source: string }>, pages: 0, windows: 0, unresolved: 0, ambiguous: 0 };+ for (const source of sources) {+ const d = await deriveOwnerPhraseLinks(tx, source);+ derived.links.push(...d.links.map(l => sources.length > 1 ? { ...l, source, doc: `${source}:${l.doc}`, account: `${source}:${l.account}` } : { ...l, source }));+ derived.pages += d.pages; derived.windows += d.windows; derived.unresolved += d.unresolved; derived.ambiguous += d.ambiguous;+ }if (derived.links.length < SAMPLE_MIN_POPULATION) return { refused: true as const, derived };- const sample = sampleLinks(derived.links, seed!, n);- const pages = new Map((await tx.executeRaw<{ slug: string; title: string | null; compiled_truth: string | null; timeline: string | null }>(- 'SELECT slug, title, compiled_truth, timeline FROM pages WHERE source_id = $1 AND deleted_at IS NULL AND slug = ANY($2::text[])',- [sourceId, [...new Set(sample.map(s => s.doc))]])).map(p => [p.slug, p]));- return { refused: false as const, derived, rows: sample.map(s => ({ ...s, excerpt: pages.has(s.doc) ? lineExcerpt(pages.get(s.doc)!, s.line) : '' })) };+ const sample = sampleLinks(derived.links, seed!, n) as Array<DerivedLink & { source: string }>;+ const rows = [];+ for (const s of sample) {+ const slug = sources.length > 1 ? s.doc.slice(s.source.length + 1) : s.doc;+ const [page] = await tx.executeRaw<{ title: string | null; compiled_truth: string | null; timeline: string | null }>(+ 'SELECT title, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [s.source, slug]);+ rows.push({ ...s, excerpt: page ? lineExcerpt(page, s.line) : '' });+ }+ return { refused: false as const, derived, rows };});const counts = { rule: SAMPLE_RULE, seed_sha256: createHash('sha256').update(seed!).digest('hex').slice(0, 16), source: sourceId,pages: result.derived.pages, windows: result.derived.windows, population: result.derived.links.length,diff --git a/test/owner-phrase-rules.test.ts b/test/owner-phrase-rules.test.tsindex 17ca2d6b67..b5834ce629 100644--- a/test/owner-phrase-rules.test.ts+++ b/test/owner-phrase-rules.test.ts@@ -18,7 +18,7 @@ import { tokenizeTitle } from '../src/core/by-mention.ts';import { findDates } from '../src/core/mentions/owner-phrase/dates.ts';import { scanPage, type ScanInput } from '../src/core/mentions/owner-phrase/scan.ts';import { buildNameIndex, parseStatements, type Statement } from '../src/core/mentions/owner-phrase/statements.ts';-import { accountDescriptors, buildWindows, ownerMatches, resolvePhrase, type OwnerWindow } from '../src/core/mentions/owner-phrase/windows.ts';+import { accountDescriptors, buildWindows, descriptorMatches, ownerMatches, resolvePhrase, type OwnerWindow } from '../src/core/mentions/owner-phrase/windows.ts';const ACCOUNTS = ['Acme Example Freight', 'Widget Example Health', 'Orbit Example Labs', 'Nimbus Example Freight'];const slugOf = (t: string) => `companies/${t.toLowerCase().replace(/ /g, '-')}`;@@ -188,6 +188,18 @@ describe('lines 7-10: resolution', () => {expect([...accountDescriptors(['CRM record: Acme Example Freight Inc'], ['logistics'])].sort()).toEqual(['acme', 'example', 'freight', 'logistics']);});+ test('a descriptor run of up to three words matches when it is one descriptor or every word is a descriptor word; labels count after a sentence boundary', () => {+ const set = new Set(['freight', 'north america', 'emea']);+ expect(descriptorMatches(set, 'freight')).toBe(true);+ expect(descriptorMatches(set, 'emea freight')).toBe(true);+ expect(descriptorMatches(set, 'north america freight')).toBe(true);+ expect(descriptorMatches(set, 'new freight')).toBe(false);+ expect(descriptorMatches(set, 'america')).toBe(false);+ const acct = page(slugOf('Orbit Example Labs'), 'Account: Orbit Example Labs. Industry: robotics. Region: EMEA.', { type: 'company' });+ expect(acct.scan.descriptors).toEqual(['emea', 'robotics']);+ expect(page('notes/n5', "Quill Example's North America robotics account renewed.").scan.hits.map(h => h.descriptor)).toEqual(['north america robotics']);+ });+test('owner matching: one word matches a first name, two words the full name', () => {expect(ownerMatches('Quill', { owner: 'quill example' })).toBe(true);expect(ownerMatches('Quill Example', { owner: 'quill example' })).toBe(true);diff --git a/test/owner-phrase-sample.test.ts b/test/owner-phrase-sample.test.tsindex aa0a02855f..5b15c7eaa2 100644--- a/test/owner-phrase-sample.test.ts+++ b/test/owner-phrase-sample.test.ts@@ -110,6 +110,9 @@ describe('scripts/owner-phrase-sample.ts', () => {expect(run(['--out', out, '--seed', 'operator-seed', '--n', '25']).exitCode).toBe(3);expect(run(['--out', out, '--seed', 'operator-seed', '--n', '25', '--force']).exitCode).toBe(0);expect(readFileSync(out, 'utf8')).toBe(tsv);+ const all = run(['--out', join(dir, 'all.tsv'), '--seed', 'operator-seed', '--n', '25', '--source', 'all']);+ expect(all.exitCode).toBe(0);+ expect(JSON.parse(all.stdout.toString().trim().split('\n').at(-1)!)).toMatchObject({ population: 28, sample: 25 });}, 120_000);test(`refuses below ${SAMPLE_MIN_POPULATION} links and writes nothing`, async () => {