Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(orphan-policy): orphanExclusionSql, the SQL renderer of the shared orphan policy
garrytan5976a6f05838
diff --git a/src/core/orphan-policy.ts b/src/core/orphan-policy.tsindex 48197e0e74..0c9e6a3647 100644--- a/src/core/orphan-policy.ts+++ b/src/core/orphan-policy.ts@@ -11,8 +11,15 @@** gbrain config set orphans.exclude_prefixes "my-private-folder/,archive/"* gbrain config set orphans.exclude_slugs "some-one-off-page"+ *+ * One policy, two renderers: `shouldExcludeFromOrphanReporting` (TypeScript,+ * one slug at a time) and `orphanExclusionSql` (a SQL predicate for set-wise+ * aggregates such as get_health). Both read the constants below;+ * `test/orphan-policy-sql-parity.test.ts` keeps them equal on generated slugs.*/+import { joinFragments, sqlFragment, trustedSql, type SqlFragment } from './engine-sql/fragment.ts';+// '/readme' — a README is a folder descriptor, not a knowledge node;// nothing is expected to wikilink to it.const AUTO_SUFFIX_PATTERNS = ['/_index', '/log', '/readme'];@@ -56,11 +63,22 @@ const FIRST_SEGMENT_EXCLUSIONS = new Set([]);const ROOT_DATE_SLUG = /^\d{4}-\d{2}-\d{2}(?:-.+)?$/;+// SQL (ARE) twin of ROOT_DATE_SLUG: JS `\d` is ASCII-only and `.` stops at+// line terminators, so both are spelled out explicitly.+const ROOT_DATE_SLUG_SQL = '^[0123456789]{4}-[0123456789]{2}-[0123456789]{2}(-[^\\n\\r\\u2028\\u2029]+)?$';++const DAILY_SEGMENT = '/daily/';+const BRAIN_PREFIX = '_brain-';+const AGENTS_PREFIX = 'agents/';+const AGENT_DREAMING_SEGMENT = '/memory/dreaming/';+const AGENT_WORKSPACE_FILES = ['agents', 'identity', 'soul', 'tools', 'user', 'heartbeat', 'dreams', 'dormant'];+const AGENT_WORKSPACE_FILE = new RegExp(`^agents/[^/]+/(?:${AGENT_WORKSPACE_FILES.join('|')})$`);+const AGENT_WORKSPACE_FILE_SQL = `^agents/[^/]+/(${AGENT_WORKSPACE_FILES.join('|')})$`;function isAgentWorkspaceConvention(slug: string): boolean {- if (!slug.startsWith('agents/')) return false;- if (slug.includes('/memory/dreaming/')) return true;- return /^agents\/[^/]+\/(?:agents|identity|soul|tools|user|heartbeat|dreams|dormant)$/.test(slug);+ if (!slug.startsWith(AGENTS_PREFIX)) return false;+ if (slug.includes(AGENT_DREAMING_SEGMENT)) return true;+ return AGENT_WORKSPACE_FILE.test(slug);}/** Per-brain additions to the convention defaults (from config). */@@ -120,7 +138,7 @@ export function shouldExcludeFromOrphanReporting(}if (slug.includes(RAW_SEGMENT)) return true;- if (slug.includes('/daily/')) return true;+ if (slug.includes(DAILY_SEGMENT)) return true;for (const prefix of DENY_PREFIXES) {if (slug.startsWith(prefix)) return true;@@ -131,7 +149,7 @@ export function shouldExcludeFromOrphanReporting(if (ROOT_DATE_SLUG.test(slug)) return true;- if (slug.startsWith('_brain-')) return true;+ if (slug.startsWith(BRAIN_PREFIX)) return true;if (isAgentWorkspaceConvention(slug)) return true;@@ -145,5 +163,42 @@ export function shouldExcludeFromOrphanReporting(return false;}+const SQL_ALIAS = /^[a-z_][a-z0-9_]*$/;++/**+ * SQL renderer of `shouldExcludeFromOrphanReporting(slug, overrides, { type })`+ * over the pages row aliased `alias`: a boolean expression that is TRUE when+ * the row is excluded and never NULL. Every list (the convention constants and+ * the per-brain overrides) binds as a text[] parameter; only the alias, checked+ * against a plain-identifier pattern, is spliced. Quarantine is not part of+ * the predicate: SQL callers filter it with the quarantine fragment.+ */+export function orphanExclusionSql(alias: string, overrides?: OrphanPolicyOverrides): SqlFragment {+ if (!SQL_ALIAS.test(alias)) throw new Error(`orphanExclusionSql: alias must be a plain identifier, got ${JSON.stringify(alias)}`);+ const slug = trustedSql(`${alias}.slug`);+ const type = trustedSql(`${alias}.type`);+ // One comparison per list entry (OR-chained, each value a parameter): a+ // per-row unnest() subquery costs more than the whole remaining predicate.+ const anyOf = (values: readonly string[], test: (value: string) => SqlFragment) =>+ values.length === 0 ? sqlFragment`FALSE` : joinFragments(values.map(test), ' OR ');+ const suffix = (v: string) => sqlFragment`right(${slug}, ${v.length}::int) = ${v}::text`;+ const prefix = (v: string) => sqlFragment`starts_with(${slug}, ${v}::text)`;+ return sqlFragment`COALESCE((+ ${type} = ANY(${[...NON_LINKABLE_PAGE_TYPES]}::text[])+ OR ${slug} = ANY(${[...PSEUDO_SLUGS]}::text[])+ OR ${anyOf(AUTO_SUFFIX_PATTERNS, suffix)}+ OR strpos(${slug}, ${RAW_SEGMENT}::text) > 0+ OR strpos(${slug}, ${DAILY_SEGMENT}::text) > 0+ OR ${anyOf(DENY_PREFIXES, prefix)}+ OR split_part(${slug}, '/', 1) = ANY(${[...FIRST_SEGMENT_EXCLUSIONS]}::text[])+ OR ${slug} ~ ${ROOT_DATE_SLUG_SQL}::text+ OR starts_with(${slug}, ${BRAIN_PREFIX}::text)+ OR (starts_with(${slug}, ${AGENTS_PREFIX}::text)+ AND (strpos(${slug}, ${AGENT_DREAMING_SEGMENT}::text) > 0 OR ${slug} ~ ${AGENT_WORKSPACE_FILE_SQL}::text))+ OR ${slug} = ANY(${overrides?.excludeSlugs ?? []}::text[])+ OR ${anyOf(overrides?.excludePrefixes ?? [], prefix)}+ ), false)`;+}+/** #5828: the brain_score timeline component's graded subset of the linkable scope. */export { gradeTimelinePages } from './timeline-grading.ts';diff --git a/test/helpers/orphan-policy-parity.ts b/test/helpers/orphan-policy-parity.tsnew file mode 100644index 0000000000..c7cc03e803--- /dev/null+++ b/test/helpers/orphan-policy-parity.ts@@ -0,0 +1,72 @@+/**+ * Generated slug/type corpus for the orphan-policy TS/SQL parity check+ * (`orphanExclusionSql` vs `shouldExcludeFromOrphanReporting`). Shared by the+ * PGLite unit test and its Postgres twin so both engines judge the same rows.+ */+import { expect } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { orphanExclusionSql, shouldExcludeFromOrphanReporting, type OrphanPolicyOverrides } from '../../src/core/orphan-policy.ts';+import { renderFragment, sqlFragment } from '../../src/core/engine-sql/fragment.ts';++const STEMS = [+ '', 'a', 'notes/x', 'people/alice-example', 'readme', 'README', 'index', 'schema', 'log', '_atlas', '_stats', 'claude',+ 'x/_index', 'x/log', 'x/readme', 'x/logs', 'x/_indexes', 'x/Readme', '/log', '_index',+ 'w/raw/y', 'raw', 'raw/y', 'w/raw', 'w/daily/y', 'daily', 'daily/x', 'w/daily', 'dailyx/y',+ 'output/x', 'outputs/x', 'output', 'dashboards/x', 'scripts/x', 'templates/x', '_templates/x', 'openclaw/config/x', 'openclaw/x',+ 'extracts/x', 'life/events/2026-01-01-ab', 'life/diary/x', 'life/eventsx/y',+ 'scratch', 'scratch/x', 'thoughts/x', 'catalog/x', 'entities/x', 'atoms/x', 'skills/x', 'dreaming/x', 'inbox/x', 'inboxes/x',+ '2026-01-02', '2026-01-02-standup', '2026-01-02-', '2026-01-02-\n', '2026-01-02-a\nb', '2026-01-02\n', '2026-1-02', '12026-01-02',+ '٢٠٢٦-٠١-٠٢', '٢٠٢٦-01-02', '2026-٠١-02', '2026-01-٠٢', 'x/aindex', 'x/%index', '2026-01-02', '2026-01-02-\u2028', '2026-01-02-x\u2029', '2026-01-02-\r', '2026-01-02-\t', '2026-01-02/x',+ '_brain-x', '_brain', '_brainx', 'agents/a/soul', 'agents/a/souls', 'agents/a/b/soul', 'agents//soul', 'agents/a\n/soul',+ 'agents/a/identity', 'agents/a/tools', 'agents/a/user', 'agents/a/heartbeat', 'agents/a/dreams', 'agents/a/dormant', 'agents/a/agents',+ 'agents/a/memory/dreaming/x', 'agents/memory/dreaming/', 'x/agents/a/soul', 'agentsx/a/soul',+ 'private/x', 'private', 'Ünï/x', 'one-off', 'one-off/x', 'x', '%/_index', 'a_b/log', 'a%b', "o'brien", 'emoji/🧠/log',+];++const SUFFIXES = ['', '/', '/x', '\n', ' ', '/readme', '/log'];+const TYPES: Array<string | null> = [null, '', 'note', 'person', 'atom', 'conversation', 'source', 'Atom', 'atoms', 'media'];++export const PARITY_OVERRIDES: Array<OrphanPolicyOverrides | undefined> = [+ undefined,+ { excludePrefixes: [], excludeSlugs: [] },+ { excludePrefixes: ['private/', 'Ünï/', 'a%', 'x'], excludeSlugs: ['one-off', 'x', "o'brien", '2026-1-02'] },+];++export function parityCorpus(seed = 3): Array<{ slug: string; type: string | null }> {+ let a = seed >>> 0;+ const rand = () => {+ a = (a * 1664525 + 1013904223) >>> 0;+ return a / 4294967296;+ };+ const rows: Array<{ slug: string; type: string | null }> = [];+ for (const stem of STEMS) {+ for (const suffix of SUFFIXES) rows.push({ slug: stem + suffix, type: TYPES[Math.floor(rand() * TYPES.length)] });+ }+ for (const type of TYPES) rows.push({ slug: 'notes/plain', type });+ for (let i = 0; i < 400; i++) {+ const a1 = STEMS[Math.floor(rand() * STEMS.length)];+ const a2 = STEMS[Math.floor(rand() * STEMS.length)];+ rows.push({ slug: `${a1}/${a2}`.replace(/^\//, ''), type: TYPES[Math.floor(rand() * TYPES.length)] });+ }+ return rows;+}++/** Evaluate `orphanExclusionSql` on the engine and compare with the TS renderer row by row. */+export async function expectOrphanPolicyParity(engine: BrainEngine): Promise<number> {+ const rows = parityCorpus();+ let checked = 0;+ for (const overrides of PARITY_OVERRIDES) {+ const { text, params } = renderFragment(sqlFragment`+ SELECT p.ord::int AS ord, ${orphanExclusionSql('p', overrides)} AS excluded+ FROM unnest(${rows.map(r => r.slug)}::text[], ${rows.map(r => r.type)}::text[]) WITH ORDINALITY AS p(slug, type, ord)+ ORDER BY p.ord`);+ const result = await engine.executeRaw<{ ord: number; excluded: boolean }>(text, params);+ expect(result.length).toBe(rows.length);+ const mismatches = result+ .map(r => ({ ...rows[r.ord - 1], sql: r.excluded, ts: shouldExcludeFromOrphanReporting(rows[r.ord - 1].slug, overrides, { type: rows[r.ord - 1].type }) }))+ .filter(r => r.sql !== r.ts);+ expect({ overrides, mismatches }).toEqual({ overrides, mismatches: [] });+ checked += rows.length;+ }+ return checked;+}diff --git a/test/orphan-policy-sql-parity.test.ts b/test/orphan-policy-sql-parity.test.tsnew file mode 100644index 0000000000..aa6b63bca5--- /dev/null+++ b/test/orphan-policy-sql-parity.test.ts@@ -0,0 +1,41 @@+/**+ * F4a: one orphan policy, two renderers. `orphanExclusionSql` (the predicate+ * get_health's aggregate statement uses) must agree with+ * `shouldExcludeFromOrphanReporting` (what `gbrain orphans` and the per-slug+ * callers use) on every generated slug and page type, with and without+ * per-brain overrides; otherwise doctor reports two contradictory orphan+ * numbers. Covers the regex edges where JS and Postgres differ (Unicode+ * digits, line terminators), LIKE metacharacters in slugs and overrides, and+ * NULL types. The Postgres twin is `test/e2e/engine-sql-health-parity.test.ts`.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { orphanExclusionSql } from '../src/core/orphan-policy.ts';+import { renderFragment } from '../src/core/engine-sql/fragment.ts';+import { expectOrphanPolicyParity } from './helpers/orphan-policy-parity.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});++afterAll(async () => {+ await engine.disconnect();+});++describe('orphan policy TS/SQL parity (PGLite)', () => {+ test('SQL and TS renderers agree on the generated corpus', async () => {+ expect(await expectOrphanPolicyParity(engine)).toBeGreaterThan(2000);+ });++ test('overrides bind as parameters and the alias is the only spliced text', () => {+ const { text, params } = renderFragment(orphanExclusionSql('pg', { excludePrefixes: ["evil'); DROP TABLE pages; --"], excludeSlugs: ['x'] }));+ expect(text).not.toContain('DROP TABLE');+ expect(params).toContain("evil'); DROP TABLE pages; --");+ expect(text).toContain('pg.slug');+ expect(() => orphanExclusionSql('p; DROP TABLE pages')).toThrow(/plain identifier/);+ });+});