Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

F5: read-only precision sample tool; descriptor runs up to three words matched word-wise; labels after a sentence boundary; region/territory descriptors

garrytan16949af9ef38
diff --git a/scripts/owner-phrase-sample.ts b/scripts/owner-phrase-sample.ts
new file mode 100644
index 0000000000..5d4eaa25b3
--- /dev/null
+++ b/scripts/owner-phrase-sample.ts
@@ -0,0 +1,80 @@
+#!/usr/bin/env bun
+/**
+ * Owner-phrase precision sample (docs/guides/owner-phrases.md, "Precision
+ * sample"). Read-only: derives the owner-phrase windows and links the pass
+ * would store for one source of the configured brain (or a PGLite copy given
+ * with --pglite), inside a READ ONLY transaction, with no model or network
+ * 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 --score <labeled.tsv>
+ *
+ * Exit codes: 0 written (or scored), 1 usage or runtime error, 3 refused
+ * (fewer than 22 derivable links, or --out exists without --force).
+ */
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+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,
+} 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'
+ + ' 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; };
+const fail = (code: number, message: string): never => { console.error(message); process.exit(code); };
+
+if (flag('--score')) {
+ console.log(JSON.stringify({ rule: SAMPLE_RULE, ...scoreLabels(readFileSync(flag('--score')!, 'utf8')) }));
+ process.exit(0);
+}
+const out = flag('--out');
+const seed = flag('--seed');
+if (!out || !seed) fail(1, USAGE);
+const n = Number(flag('--n') ?? SAMPLE_DEFAULT_SIZE);
+if (!Number.isInteger(n) || n < 1) fail(1, `--n must be a positive integer\n${USAGE}`);
+if (existsSync(out!) && !args.includes('--force')) fail(3, 'refused: --out already exists; pass --force to replace it');
+const sourceId = flag('--source') ?? 'default';
+
+let engineConfig: EngineConfig;
+if (flag('--pglite')) engineConfig = { engine: 'pglite', database_path: flag('--pglite') } as EngineConfig;
+else {
+ const config = loadConfig();
+ if (!config) fail(1, 'No GBrain config found. Pass --pglite <brain directory copy>, or run from a machine with a configured brain.');
+ engineConfig = toEngineConfig(config!);
+}
+const engine = await createEngine(engineConfig);
+await engine.connect(engineConfig);
+let code = 0;
+try {
+ const result = await engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION READ ONLY');
+ const derived = await deriveOwnerPhraseLinks(tx, sourceId);
+ 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 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,
+ unresolved: result.derived.unresolved, ambiguous: result.derived.ambiguous };
+ if (result.refused) {
+ console.log(JSON.stringify({ ...counts, refused: `fewer than ${SAMPLE_MIN_POPULATION} owner-phrase links derivable; no sample written` }));
+ code = 3;
+ } else {
+ writeFileSync(out!, toTsv(result.rows), { mode: 0o600 });
+ console.log(JSON.stringify({ ...counts, sample: result.rows.length, out }));
+ }
+} catch (error) {
+ console.error(`owner-phrase sample failed: ${error instanceof Error ? error.message : String(error)}`);
+ code = 1;
+} finally {
+ await engine.disconnect();
+}
+process.exit(code);
diff --git a/src/core/mentions/owner-phrase/pass.ts b/src/core/mentions/owner-phrase/pass.ts
index f71cb3a702..aad8ea1ea3 100644
--- a/src/core/mentions/owner-phrase/pass.ts
+++ b/src/core/mentions/owner-phrase/pass.ts
@@ -162,12 +162,16 @@ function groupAccounts(accounts: EntityRow[], pack: PackTypes | null, policy: Me
export interface OwnerPhraseModel {
windows: OwnerWindow[];
descriptors: Map<string, Set<string>>;
- links: Array<{ from_id: number; from_slug: string; to_slug: string; context: string; evidence: number[] }>;
+ links: Array<{ from_id: number; from_slug: string; to_slug: string; context: string; evidence: number[]; line: number; windows: OwnerWindow[] }>;
counters: Omit<OwnerPhraseCounters, 'links' | 'documents' | 'windows'>;
}
-/** Statements, windows and resolved links of one source from its stored scans (no writes). */
-export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<OwnerPhrasePassOpts, 'sourceId' | 'gazetteer' | 'types' | 'pack' | 'policy'>): Promise<OwnerPhraseModel> {
+/** One page's scan as the model reads it (`owner_phrase_page_state`, or computed in memory by a dry run). */
+export type OwnerPhraseState = StateRow;
+
+/** Statements, windows and resolved links of one source from its stored scans, or from `states` when given (no writes). */
+export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<OwnerPhrasePassOpts, 'sourceId' | 'gazetteer' | 'types' | 'pack' | 'policy'>,
+ states?: OwnerPhraseState[]): Promise<OwnerPhraseModel> {
const { sourceId } = opts;
const entities = await engine.executeRaw<EntityRow>(
`SELECT id, slug, type, title, frontmatter->>'identity' AS identity FROM pages
@@ -195,7 +199,7 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Owne
const accountIndex = buildNameIndex(accountEntries);
const personIndex = buildNameIndex(personEntries);
- const states = await engine.executeRaw<StateRow>(
+ states ??= await engine.executeRaw<StateRow>(
`SELECT s.page_id, p.slug, s.page_date::text AS page_date, s.readings, s.agent, s.cues, s.descriptors, s.hits
FROM owner_phrase_page_state s JOIN pages p ON p.id = s.page_id
WHERE s.source_id = $1 AND p.deleted_at IS NULL
@@ -246,7 +250,7 @@ export async function buildOwnerPhraseModel(engine: BrainEngine, opts: Pick<Owne
for (const to of r.accounts) {
if (to === s.slug || seen.has(to)) continue;
seen.add(to);
- links.push({ from_id: Number(s.page_id), from_slug: s.slug, to_slug: to, context: hit.surface, evidence });
+ links.push({ from_id: Number(s.page_id), from_slug: s.slug, to_slug: to, context: hit.surface, evidence, line: hit.line, windows: r.windows });
}
}
}
diff --git a/src/core/mentions/owner-phrase/sample.ts b/src/core/mentions/owner-phrase/sample.ts
new file mode 100644
index 0000000000..abddb291b4
--- /dev/null
+++ b/src/core/mentions/owner-phrase/sample.ts
@@ -0,0 +1,142 @@
+/**
+ * Owner phrases, read-only: derive the windows and links the pass would store
+ * for one source without writing anything, and draw a reproducible labeling
+ * sample of those links for the precision check (docs/guides/owner-phrases.md,
+ * "Precision sample").
+ *
+ * `deriveOwnerPhraseLinks` scans every live page in memory with the same
+ * scanner, statement grammar, window assembly and resolution as the pass, then
+ * drops the pairs the pass would not store (a pair another link already
+ * covers) and keeps one link per page pair, exactly as the pass does. It reads
+ * pages, links, aliases and config only. Callers that need a guarantee run it
+ * inside a read-only transaction (scripts/owner-phrase-sample.ts does).
+ *
+ * Sampling rule v1, fixed before any sample is drawn: the population is every
+ * derived link, one per (document, account page); each is ranked by
+ * sha256("owner-phrase-sample-v1", seed, document slug, account slug) and the
+ * first n are taken (all of them when fewer than n exist). The same brain and
+ * seed always give the same sample. Fewer than SAMPLE_MIN_POPULATION links is a
+ * refusal: the precision bar cannot be met or missed on so few.
+ */
+
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from '../../engine.ts';
+import { buildGazetteer } from '../../by-mention.ts';
+import { linkableTypesFor, loadSourcePack, readMentionPolicy } from '../policy.ts';
+import { scanPage } from './scan.ts';
+import { buildOwnerPhraseModel, type OwnerPhraseState } from './pass.ts';
+
+export const SAMPLE_RULE = 'owner-phrase-sample-v1';
+export const SAMPLE_MIN_POPULATION = 22;
+export const SAMPLE_DEFAULT_SIZE = 100;
+const SCAN_BATCH = 1000;
+const EXCERPT_MAX = 300;
+
+export interface DerivedLink {
+ doc: string;
+ account: string;
+ phrase: string;
+ line: number;
+ /** Owner and inclusive bounds of each window the phrase resolved through. */
+ windows: Array<{ owner: string; from: string | null; to: string | null }>;
+ /** Evidence pages of those windows with their lines. */
+ evidence: Array<{ slug: string; line: number }>;
+}
+
+export interface Derivation { links: DerivedLink[]; windows: number; pages: number; unresolved: number; ambiguous: number }
+
+/** The links the owner-phrase pass would store for `sourceId`, derived without writes. */
+export async function deriveOwnerPhraseLinks(engine: BrainEngine, sourceId: string): Promise<Derivation> {
+ const policy = await readMentionPolicy(engine);
+ const pack = await loadSourcePack(engine, sourceId, { strict: true });
+ const gazetteer = await buildGazetteer(engine, { policy, strict: true });
+ const states: OwnerPhraseState[] = [];
+ let after = 0;
+ let pages = 0;
+ for (;;) {
+ const rows = await engine.executeRaw<{ id: number; slug: string; type: string | null; title: string | null; compiled_truth: string | null;
+ timeline: string | null; frontmatter: unknown; effective_date: unknown; effective_date_source: string | null }>(
+ `SELECT id, slug, type, title, compiled_truth, timeline, frontmatter, effective_date, effective_date_source FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND id > $2 ORDER BY id LIMIT $3`, [sourceId, after, SCAN_BATCH]);
+ if (!rows.length) break;
+ after = Number(rows[rows.length - 1]!.id);
+ pages += rows.length;
+ for (const p of rows) {
+ const frontmatter = (typeof p.frontmatter === 'string' ? JSON.parse(p.frontmatter) : p.frontmatter) as Record<string, unknown> | null;
+ const scan = scanPage({ ...p, frontmatter });
+ if (!scan.cues.length && !scan.hits.length && !scan.descriptors.length) continue;
+ states.push({ page_id: Number(p.id), slug: p.slug, page_date: scan.date, readings: scan.readings, agent: scan.agent,
+ cues: scan.cues, descriptors: scan.descriptors, hits: scan.hits });
+ }
+ }
+ const model = await buildOwnerPhraseModel(engine, { sourceId, gazetteer, types: linkableTypesFor(pack, policy), pack, policy }, states);
+ const fromIds = [...new Set(model.links.map(l => l.from_id))];
+ const covered = new Set(fromIds.length ? (await engine.executeRaw<{ f: number; t: string }>(
+ `SELECT l.from_page_id AS f, t.slug AS t FROM links l JOIN pages t ON t.id = l.to_page_id
+ WHERE l.from_page_id = ANY($1::int[]) AND t.source_id = $2 AND l.link_kind IS DISTINCT FROM 'owner_phrase'`, [fromIds, sourceId]))
+ .map(r => `${r.f}\0${r.t}`) : []);
+ const slugById = new Map(states.map(s => [s.page_id, s.slug]));
+ const seen = new Set<string>();
+ const links: DerivedLink[] = [];
+ for (const l of model.links) {
+ const key = `${l.from_id}\0${l.to_slug}`;
+ if (covered.has(key) || seen.has(key)) continue;
+ seen.add(key);
+ const windows = l.windows.filter(w => w.accounts.includes(l.to_slug) || w.group === l.to_slug);
+ const shown = windows.length ? windows : l.windows;
+ links.push({
+ doc: l.from_slug, account: l.to_slug, phrase: l.context, line: l.line,
+ windows: shown.map(w => ({ owner: w.ownerName, from: w.from, to: w.to })),
+ evidence: [...new Map(shown.flatMap(w => w.evidence).map(e => [`${e.page_id}:${e.line}`, { slug: slugById.get(e.page_id) ?? e.slug, line: e.line }])).values()],
+ });
+ }
+ links.sort((a, b) => a.doc.localeCompare(b.doc) || a.account.localeCompare(b.account));
+ return { links, windows: model.windows.length, pages, unresolved: model.counters.unresolved, ambiguous: model.counters.ambiguous };
+}
+
+/** Rule v1: rank by sha256(rule, seed, doc, account), take the first n. */
+export function sampleLinks(links: DerivedLink[], seed: string, n: number): DerivedLink[] {
+ const rank = (l: DerivedLink) => createHash('sha256').update([SAMPLE_RULE, seed, l.doc, l.account].join('\0')).digest('hex');
+ return links.map(l => ({ l, r: rank(l) })).sort((a, b) => (a.r < b.r ? -1 : a.r > b.r ? 1 : 0)).slice(0, n).map(x => x.l);
+}
+
+/** The line a phrase sits on (line 0 is the title), cut to EXCERPT_MAX characters. */
+export function lineExcerpt(page: { title: string | null; compiled_truth: string | null; timeline: string | null }, line: number): string {
+ if (line === 0) return (page.title ?? '').slice(0, EXCERPT_MAX);
+ const lines = `${page.compiled_truth ?? ''}${page.timeline ? `\n${page.timeline}` : ''}`.split('\n');
+ return (lines[line - 1] ?? '').trim().slice(0, EXCERPT_MAX);
+}
+
+export const TSV_COLUMNS = ['id', 'doc_slug', 'phrase', 'line_excerpt', 'account', 'window', 'evidence_page', 'label'] as const;
+const cell = (v: string) => v.replace(/[\t\r\n]+/g, ' ');
+
+export function toTsv(rows: Array<DerivedLink & { excerpt: string }>): string {
+ const body = rows.map((r, i) => [String(i + 1), r.doc, r.phrase, r.excerpt, r.account,
+ r.windows.map(w => `${w.owner} ${w.from ?? '?'}..${w.to ?? 'open'}`).join('; '),
+ r.evidence.map(e => `${e.slug}#L${e.line}`).join('; '), ''].map(cell).join('\t'));
+ return [TSV_COLUMNS.join('\t'), ...body].join('\n') + '\n';
+}
+
+/** Wilson score interval lower bound at 95% (z = 1.96). */
+export function wilsonLower(correct: number, n: number): number {
+ if (n === 0) return 0;
+ const z = 1.96;
+ const p = correct / n;
+ return (p + z * z / (2 * n) - z * Math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))) / (1 + z * z / n);
+}
+
+/** Counts of a labeled TSV (`label` column: y / n; anything else is unlabeled). */
+export function scoreLabels(tsv: string): { labeled: number; correct: number; wrong: number; unlabeled: number; wilson_lower_95: number } {
+ const [head, ...rows] = tsv.split('\n').filter(l => l.trim());
+ const at = head!.split('\t').indexOf('label');
+ if (at < 0) throw new Error('the TSV has no label column');
+ let correct = 0; let wrong = 0; let unlabeled = 0;
+ for (const r of rows) {
+ const v = (r.split('\t')[at] ?? '').trim().toLowerCase();
+ if (v === 'y' || v === 'yes' || v === '1') correct++;
+ else if (v === 'n' || v === 'no' || v === '0') wrong++;
+ else unlabeled++;
+ }
+ const labeled = correct + wrong;
+ return { labeled, correct, wrong, unlabeled, wilson_lower_95: Number(wilsonLower(correct, labeled).toFixed(4)) };
+}
diff --git a/src/core/mentions/owner-phrase/scan.ts b/src/core/mentions/owner-phrase/scan.ts
index 4bb28cdc23..127def4f82 100644
--- a/src/core/mentions/owner-phrase/scan.ts
+++ b/src/core/mentions/owner-phrase/scan.ts
@@ -20,7 +20,7 @@
import { findDates, dayOf } from './dates.ts';
/** Bump to rescan every page's owner-phrase state once (scanner behavior change). */
-export const OWNER_PHRASE_SCAN_VERSION = 1;
+export const OWNER_PHRASE_SCAN_VERSION = 2;
export interface CueLine { line: number; text: string }
export interface PhraseHit { owner: string; descriptor: string; noun: string; line: number; surface: string }
@@ -56,7 +56,7 @@ export const PERSONAL_ACCOUNT_RE = /\b(?:benefits?|hsa|fsa|401\(?k\)?|payroll|pe
const NAME = String.raw`[A-Z][a-zA-Z]+(?:[-'][A-Z][a-zA-Z]+)?`;
const NAME_RUN = String.raw`${NAME}(?: ${NAME}){0,2}`;
-const DESC = String.raw`[A-Za-z][A-Za-z0-9&-]*(?: [A-Za-z][A-Za-z0-9&-]*)?`;
+const DESC = String.raw`[A-Za-z][A-Za-z0-9&-]*(?: [A-Za-z][A-Za-z0-9&-]*){0,2}`;
const NOUN = '(?:book of business|account|book|client|customer|relationship|portfolio)';
const POSSESSIVE_RE = new RegExp(String.raw`(?<![\w'’])(${NAME_RUN})['’]s (${DESC}) (${NOUN})(?![\w-])`, 'g');
const RUNS_RE = new RegExp(String.raw`\b[Tt]he (${DESC}) (account|book|client|customer|relationship) (?:that |which )?(${NAME_RUN}) (?:runs|handles|owns|manages|covers|leads|looks after|is running|is handling|is managing|is covering|is leading|has been running|runs point on)\b`, 'g');
@@ -90,7 +90,7 @@ function isAgentAuthored(type: string | null, fm: Record<string, unknown>): bool
return false;
}
-const DESCRIPTOR_LABEL_RE = /^\s*(?:[-*]\s*)?(?:\*\*)?(?:segment|industry|vertical|sector|category|line of business|business line|descriptor)(?:\*\*)?\s*:\s*(?:\*\*)?([^|;,.()]+)/i;
+const DESCRIPTOR_LABEL_RE = /(?:^|[.;]\s+)\s*(?:[-*]\s*)?(?:\*\*)?(?:segment|industry|vertical|sector|category|line of business|business line|descriptor|region|territory)(?:\*\*)?\s*:\s*(?:\*\*)?([^|;,.()]+)/gi;
const DESCRIPTOR_DECL_RES = [
/\b(?:is|as) (?:our|the|a|an) ((?:[a-z][a-z0-9&-]*)(?: [a-z][a-z0-9&-]*)?) (?:account|client|customer)\b/gi,
/\bknown (?:internally )?as the ((?:[a-z][a-z0-9&-]*)(?: [a-z][a-z0-9&-]*)?) (?:account|client|customer|book)\b/gi,
@@ -108,7 +108,7 @@ function cleanDescriptor(raw: string): string | null {
function frontmatterDescriptors(fm: Record<string, unknown>): string[] {
const out: string[] = [];
- for (const key of ['segment', 'industry', 'vertical', 'sector', 'category', 'descriptor', 'line_of_business']) {
+ for (const key of ['segment', 'industry', 'vertical', 'sector', 'category', 'descriptor', 'line_of_business', 'region', 'territory']) {
const v = fm[key];
for (const item of Array.isArray(v) ? v : [v]) {
if (typeof item !== 'string') continue;
@@ -205,8 +205,7 @@ export function scanPage(page: ScanInput): PageScan {
}
const descriptors = new Set(frontmatterDescriptors(fm));
for (const raw of lines) {
- const label = DESCRIPTOR_LABEL_RE.exec(raw);
- if (label) { const d = cleanDescriptor(label[1]!); if (d) descriptors.add(d); }
+ for (const label of raw.matchAll(DESCRIPTOR_LABEL_RE)) { const d = cleanDescriptor(label[1]!); if (d) descriptors.add(d); }
for (const re of DESCRIPTOR_DECL_RES) for (const m of raw.matchAll(re)) { const d = cleanDescriptor(m[1]!); if (d) descriptors.add(d); }
}
const titleHits = page.title ? phraseHits([page.title]).map(h => ({ ...h, line: 0 })) : [];
diff --git a/src/core/mentions/owner-phrase/windows.ts b/src/core/mentions/owner-phrase/windows.ts
index 0d6649fa2c..9f27f6f96b 100644
--- a/src/core/mentions/owner-phrase/windows.ts
+++ b/src/core/mentions/owner-phrase/windows.ts
@@ -184,11 +184,20 @@ export function ownerMatches(surface: string, window: Pick<OwnerWindow, 'owner'>
return s.join(' ') === w.join(' ');
}
+/** A descriptor run matches an account when the whole run is one of its descriptors, or every word of the run is a word of its descriptors ("EMEA software" with region EMEA and industry software). */
+export function descriptorMatches(descriptors: ReadonlySet<string>, run: string): boolean {
+ if (descriptors.has(run)) return true;
+ const words = run.split(' ');
+ if (words.length < 2) return false;
+ const known = new Set([...descriptors].flatMap(d => d.split(' ')));
+ return words.every(w => known.has(w));
+}
+
/** Resolve one owner phrase on a document dated `date` (plus its other readings) against the windows (contract lines 9-10). */
export function resolvePhrase(hit: Pick<PhraseHit, 'owner' | 'descriptor'>, date: string | null, readings: string[],
windows: OwnerWindow[], descriptorsOf: (group: string) => ReadonlySet<string>): Resolution {
if (!date) return { linked: false, reason: 'no_page_date' };
- const owned = windows.filter(w => ownerMatches(hit.owner, w) && descriptorsOf(w.group).has(hit.descriptor));
+ const owned = windows.filter(w => ownerMatches(hit.owner, w) && descriptorMatches(descriptorsOf(w.group), hit.descriptor));
if (!owned.length) return { linked: false, reason: 'no_owner' };
let chosen: string | null = null;
let chosenWindows: OwnerWindow[] = [];
diff --git a/test/owner-phrase-sample.test.ts b/test/owner-phrase-sample.test.ts
new file mode 100644
index 0000000000..aa0a02855f
--- /dev/null
+++ b/test/owner-phrase-sample.test.ts
@@ -0,0 +1,126 @@
+/**
+ * Owner-phrase precision sample (scripts/owner-phrase-sample.ts,
+ * mentions/owner-phrase/sample.ts): the read-only derivation, sampling rule
+ * v1, the labeling TSV and the Wilson bound.
+ *
+ * Protects: the dry run deriving exactly the links the stored pass would
+ * write, without writing (it runs inside a READ ONLY transaction and leaves
+ * every table unchanged, with `mentions.owner_phrases` off); a sample
+ * reproducible from the operator's seed; the refusal below 22 links; stdout
+ * carrying counts only. Regression: a sampler that differs from the pass, a
+ * sample that changes between runs, or a log line naming a page.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { deriveOwnerPhraseLinks, sampleLinks, scoreLabels, toTsv, wilsonLower, SAMPLE_MIN_POPULATION, TSV_COLUMNS } from '../src/core/mentions/owner-phrase/sample.ts';
+import { doc, ownerPhraseLinks, seedOwnerPhraseBrain, sweepOwnerPhrases } from './helpers/owner-phrase-brain.ts';
+
+const dir = mkdtempSync(join(tmpdir(), 'owner-phrase-sample-'));
+const brainPath = join(dir, 'brain.pglite');
+let engine: PGLiteEngine;
+
+async function counts(e: PGLiteEngine) {
+ const [r] = await e.executeRaw<Record<string, number>>(`SELECT (SELECT count(*) FROM links)::int AS links, (SELECT count(*) FROM owner_phrase_windows)::int AS windows,
+ (SELECT count(*) FROM owner_phrase_page_state)::int AS states, (SELECT count(*) FROM owner_phrase_status)::int AS status, (SELECT count(*) FROM config)::int AS config`);
+ return r;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({ database_path: brainPath } as never);
+ await engine.initSchema();
+ await seedOwnerPhraseBrain(engine, { enabled: false });
+ for (let i = 1; i <= 24; i++) {
+ await doc(engine, `notes/call-${String(i).padStart(2, '0')}`, `Call recap: Quill's freight account asked about lane ${i}.`, { date: `2025-05-${String(i + 1).padStart(2, '0')}` });
+ }
+ await sweepOwnerPhrases(engine);
+}, 180_000);
+afterAll(async () => { await engine.disconnect().catch(() => {}); rmSync(dir, { recursive: true, force: true }); });
+
+describe('read-only derivation', () => {
+ let derivedPairs: string[];
+ test('derives inside a READ ONLY transaction with the key off and writes nothing', async () => {
+ const before = await counts(engine);
+ const derived = await engine.transaction(async tx => {
+ await tx.executeRaw('SET TRANSACTION READ ONLY');
+ return deriveOwnerPhraseLinks(tx, 'default');
+ });
+ expect(await counts(engine)).toEqual(before);
+ expect(before).toMatchObject({ windows: 0, states: 0, status: 0 });
+ expect(derived.links.length).toBe(28);
+ expect(derived.windows).toBe(6);
+ derivedPairs = derived.links.map(l => `${l.doc} -> ${l.account}`);
+ const renewal = derived.links.find(l => l.doc === 'notes/renewal')!;
+ expect(renewal).toMatchObject({ phrase: "Quill's freight account", line: 1, windows: [{ owner: 'Quill Example', from: '2025-05-01', to: null }],
+ evidence: [{ slug: 'updates/acme-handoff', line: 1 }] });
+ });
+
+ test('the derived links are exactly the links the stored pass writes once the key is on', async () => {
+ await engine.setConfig('mentions.owner_phrases', 'true');
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).toEqual([...derivedPairs].sort());
+ await engine.setConfig('mentions.owner_phrases', 'false');
+ await sweepOwnerPhrases(engine);
+ expect(await ownerPhraseLinks(engine)).toEqual([]);
+ });
+});
+
+describe('sampling rule v1, TSV and scoring', () => {
+ test('a seed reproduces the sample; another seed reorders it; n caps it', async () => {
+ const { links } = await deriveOwnerPhraseLinks(engine, 'default');
+ const a = sampleLinks(links, 'seed-a', 10).map(l => l.doc);
+ expect(sampleLinks(links, 'seed-a', 10).map(l => l.doc)).toEqual(a);
+ expect(sampleLinks(links, 'seed-b', 10).map(l => l.doc)).not.toEqual(a);
+ expect(sampleLinks(links, 'seed-a', 100)).toHaveLength(links.length);
+ expect(sampleLinks([...links].reverse(), 'seed-a', 10).map(l => l.doc)).toEqual(a);
+ });
+
+ test('the TSV has the labeling columns and one row per sampled link; labels score with a Wilson 95% lower bound', async () => {
+ const { links } = await deriveOwnerPhraseLinks(engine, 'default');
+ const tsv = toTsv(sampleLinks(links, 's', 3).map(l => ({ ...l, excerpt: 'line\twith tab' })));
+ const rows = tsv.split('\n').filter(Boolean).map(r => r.split('\t'));
+ expect(rows[0]).toEqual([...TSV_COLUMNS]);
+ expect(rows.slice(1).every(r => r.length === TSV_COLUMNS.length && r[3] === 'line with tab')).toBe(true);
+ const labeled = [rows[0]!.join('\t'), ...rows.slice(1).map((r, i) => [...r.slice(0, 7), i === 2 ? 'n' : 'y'].join('\t'))].join('\n');
+ expect(scoreLabels(labeled)).toMatchObject({ labeled: 3, correct: 2, wrong: 1, unlabeled: 0 });
+ expect(wilsonLower(57, 60)).toBeGreaterThanOrEqual(0.85);
+ expect(wilsonLower(56, 60)).toBeLessThan(0.85);
+ expect(wilsonLower(92, 100)).toBeGreaterThanOrEqual(0.85);
+ expect(wilsonLower(91, 100)).toBeLessThan(0.85);
+ });
+});
+
+describe('scripts/owner-phrase-sample.ts', () => {
+ const run = (args: string[]) => Bun.spawnSync(['bun', 'scripts/owner-phrase-sample.ts', '--pglite', brainPath, ...args], { cwd: join(import.meta.dir, '..'), env: { ...process.env, GBRAIN_HOME: dir } });
+
+ test('writes the sample to the named path; stdout names no page; a repeat with the same seed is byte-identical', async () => {
+ await engine.disconnect();
+ const out = join(dir, 'sample.tsv');
+ const first = run(['--out', out, '--seed', 'operator-seed', '--n', '25']);
+ expect(first.exitCode).toBe(0);
+ const stdout = first.stdout.toString() + first.stderr.toString();
+ const summary = JSON.parse(first.stdout.toString().trim().split('\n').at(-1)!);
+ expect(summary).toMatchObject({ rule: 'owner-phrase-sample-v1', population: 28, sample: 25, windows: 6 });
+ expect(stdout).not.toMatch(/notes\/|companies\/|Quill|Rowan|Juniper|freight/);
+ const tsv = readFileSync(out, 'utf8');
+ expect(tsv.trim().split('\n')).toHaveLength(26);
+ 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);
+ }, 120_000);
+
+ test(`refuses below ${SAMPLE_MIN_POPULATION} links and writes nothing`, async () => {
+ const small = new PGLiteEngine();
+ await small.connect({ database_path: brainPath } as never);
+ await small.executeRaw(`DELETE FROM pages WHERE slug LIKE 'notes/call-%'`);
+ await small.disconnect();
+ const out = join(dir, 'small.tsv');
+ const r = run(['--out', out, '--seed', 'x']);
+ expect(r.exitCode).toBe(3);
+ expect(JSON.parse(r.stdout.toString().trim().split('\n').at(-1)!)).toMatchObject({ population: 4 });
+ expect(() => readFileSync(out)).toThrow();
+ }, 120_000);
+});