Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: SQL twins of trimmed TypeScript checks trim the same whitespace
garrytan732df8eab374
diff --git a/src/core/access/caller.ts b/src/core/access/caller.tsindex 5a2bb720a5..61dceda3a2 100644--- a/src/core/access/caller.ts+++ b/src/core/access/caller.ts@@ -18,6 +18,7 @@ import { ACCESS_ID_RE, identityFor, normalizePrincipal } from './principals.ts';import { catalogueError } from '../error-catalogue.ts';import { hostOnlyError } from '../ops/op-fix.ts';import { currentCallerAccess } from '../search/private-visibility.ts';+import { edgeTrimSql } from '../edge-whitespace.ts';import { GUEST, STDIO_MAY_ACT_FOR_KEY, mayActForCovers, singleMemberAudience, type AudiencePrincipal } from './audience.ts';import { parseMayActFor } from './members.ts';@@ -50,7 +51,7 @@ async function liveIdentity(engine: Pick<BrainEngine, 'executeRaw'>, memberSql:export async function memberIdentityFor(engine: Pick<BrainEngine, 'executeRaw'>, auth: Pick<AuthInfo, 'member'> & { principal?: { kind: string; id: string } } | undefined): Promise<string[]> {if (auth?.member !== undefined) return auth.member ? identityFor(auth.member.id, auth.member.groups) : [];const principal = auth?.principal;- if (principal?.kind === 'local_stdio') return liveIdentity(engine, 'SELECT btrim(value) FROM config WHERE key = $1', STDIO_MEMBER_KEY);+ if (principal?.kind === 'local_stdio') return liveIdentity(engine, `SELECT ${edgeTrimSql('value')} FROM config WHERE key = $1`, STDIO_MEMBER_KEY);if (!principal || (principal.kind !== 'legacy_token' && principal.kind !== 'oauth_client')) return [];return liveIdentity(engine, principal.kind === 'legacy_token'? 'SELECT member_id FROM access_tokens WHERE id::text = $1 AND revoked_at IS NULL'diff --git a/src/core/edge-whitespace.ts b/src/core/edge-whitespace.tsnew file mode 100644index 0000000000..678cfef2fd--- /dev/null+++ b/src/core/edge-whitespace.ts@@ -0,0 +1,22 @@+/**+ * The whitespace JavaScript's `String.prototype.trim` strips (WhiteSpace and LineTerminator), for SQL twins of+ * TypeScript predicates. Postgres `btrim(x)` with no set strips spaces only, so a twin that trims there disagrees with+ * its TypeScript side on a tab, newline, NBSP or other edge whitespace. Twins trim with edgeTrimSql instead;+ * test/edge-whitespace.test.ts holds the set equal to what `trim` strips.+ */+export const EDGE_WHITESPACE = ' \t\n\v\f\r\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';++const EDGE_WHITESPACE_SQL = `E'${[...EDGE_WHITESPACE].map(c => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`).join('')}'`;++/** `btrim` of a code-provided SQL expression over EDGE_WHITESPACE: the SQL twin of `.trim()`. */+export function edgeTrimSql(expr: string): string {+ return `btrim(${expr}, ${EDGE_WHITESPACE_SQL})`;+}++/** ASCII-only lowercase in SQL, independent of the database collation: the twin of `.replace(/[A-Z]/g, …)`. */+export function asciiLowerSql(expr: string): string {+ return `translate(${expr}, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`;+}++/** ASCII-only lowercase, the TypeScript side of asciiLowerSql. */+export const asciiLower = (value: string) => value.replace(/[A-Z]/g, c => c.toLowerCase());diff --git a/src/core/persistence/local-edit-adoption.ts b/src/core/persistence/local-edit-adoption.tsindex 552b5ae154..92a5663fd2 100644--- a/src/core/persistence/local-edit-adoption.ts+++ b/src/core/persistence/local-edit-adoption.ts@@ -60,6 +60,7 @@ import { ledgerLocation, messageDigest, readLedger } from '../git/commit-ledger.import { adoptedBy, localEditAdoptionCommit, type GitCommitNote } from './effect-model.ts';import { claimOwner } from './claim-phase.ts';import type { PreparedMutation } from './coordinator.ts';+import { EDGE_WHITESPACE } from '../edge-whitespace.ts';export const ADOPTED_CHANGE_REASON = 'adopted_local_edit';export const ADOPT_QUIET_KEY = 'persistence.adopt_quiet_ms';@@ -118,8 +119,6 @@ async function settled(path: string, quiet: number): Promise<boolean> {}}-/** The whitespace JS `trim` strips; the SQL side trims the same set, so an earlier revision matches whatever its edges hold. */-const EDGE_WHITESPACE = ' \t\n\v\f\r\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';const edgeTrim = (text: string | null | undefined) => (text ?? '').trim();/** Body lines that are Facts or timeline fence rows (list items and table rows, not a table's separator line). */function fenceRows(...texts: Array<string | null | undefined>): Set<string> {diff --git a/src/core/persistence/unbound-pages.ts b/src/core/persistence/unbound-pages.tsindex 554548eaa0..e2a10b343d 100644--- a/src/core/persistence/unbound-pages.ts+++ b/src/core/persistence/unbound-pages.ts@@ -17,6 +17,7 @@ import { resolveSourceLocalFilePath } from '../markdown.ts';import { opError } from '../ops/contract.ts';import { scannerSourcePath } from '../write-through.ts';import { resolveSlugForPath } from '../sync.ts';+import { edgeTrimSql } from '../edge-whitespace.ts';export function isDatabaseOnlyPage(page: { source_path?: string | null; source_uri?: string | null; database_only_reason?: string | null }): boolean {return page.database_only_reason === 'unbound_source' && !page.source_path?.trim() && !page.source_uri?.trim();@@ -24,7 +25,7 @@ export function isDatabaseOnlyPage(page: { source_path?: string | null; source_u/** `isDatabaseOnlyPage` as a SQL predicate over the `pages` row aliased `alias` (#6536: doctor counts with it). */export function databaseOnlyPageSql(alias: string): string {- const blank = (column: string) => `COALESCE(btrim(${alias}.${column}, E' \\t\\n\\r\\f\\v'), '')=''`;+ const blank = (column: string) => `COALESCE(${edgeTrimSql(`${alias}.${column}`)}, '')=''`;return `${alias}.database_only_reason IS NOT DISTINCT FROM 'unbound_source' AND ${blank('source_path')} AND ${blank('source_uri')}`;}diff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex 65ee019c4d..1ad125597b 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -25,6 +25,7 @@ import type { BrainEngine } from '../engine.ts';import { embeddedKey, embeddedKeyInScope, unscopedWithOpenEmbeddedEngines } from '../engine-scope-store.ts';import { requestConfigRows } from '../config-snapshot.ts';import { isValidSourceId } from '../source-id.ts';+import { asciiLower, asciiLowerSql, edgeTrimSql } from '../edge-whitespace.ts';import { ACCESS_ID_RE, hasReaders, MEMBER_PAGE_PREFIX, normalizePrincipal, readersAllow, validIdentity } from '../access/principals.ts';import { validPrefix, validQualifiedRuleId } from '../access/folder-rules.ts';@@ -484,7 +485,8 @@ export type Visibility = 'private' | 'world';/*** Privacy aliases: keys a page may carry instead of `visibility` (the* bulk-ingestion template's `access`, a `confidentiality` field), with the- * values that mean private. Matching is case-insensitive on the trimmed value.+ * values that mean private. Matching is ASCII case-insensitive on the value trimmed of+ * edge whitespace, the same on the TypeScript and SQL sides.* Everything derived from an aliased page (facts, chronicle events, timeline* rows, remember saves into it) is private. Remote page reads honor the aliases* too unless the operator sets `visibility.honor_aliases false`.@@ -498,14 +500,14 @@ export const HONOR_ALIASES_KEY = 'visibility.honor_aliases';function hasPrivacyAlias(frontmatter: Record<string, unknown>): boolean {return Object.entries(PRIVACY_ALIASES).some(([key, values]) => {const value = frontmatter[key];- return typeof value === 'string' && values.includes(value.trim().toLowerCase());+ return typeof value === 'string' && values.includes(asciiLower(value.trim()));});}/** SQL twin of hasPrivacyAlias on a page alias (a code-provided literal). */export function privacyAliasSql(alias: string): string {return `(${Object.entries(PRIVACY_ALIASES).map(([key, values]) =>- `COALESCE(lower(btrim(${alias}.frontmatter->>'${key}')) IN (${values.map(v => `'${v}'`).join(',')}), false)`).join(' OR ')})`;+ `COALESCE(${asciiLowerSql(edgeTrimSql(`${alias}.frontmatter->>'${key}'`))} IN (${values.map(v => `'${v}'`).join(',')}), false)`).join(' OR ')})`;}/**diff --git a/src/core/trust/backfill.ts b/src/core/trust/backfill.tsindex 3a21824b6d..36809622ce 100644--- a/src/core/trust/backfill.ts+++ b/src/core/trust/backfill.ts@@ -46,6 +46,7 @@ import { appendBulkRetier } from '../belief/retier.ts';import { markBeliefCommits } from '../belief/append.ts';import { maintenanceAttribution } from '../persistence/attribution.ts';import { readManagedMode } from '../persistence/managed-mode.ts';+import { edgeTrimSql } from '../edge-whitespace.ts';import { EXTRACT_ATOMS_EXTRACTOR_PREFIX, frontmatterTrustCapsSql } from './channel.ts';import { claimedSourceSql, legacyRowSql, notConnectorSourceSql, readLegacyCeilings, type LegacyCeilings } from './claim-state.ts';import { TRUST_BACKFILL_COMPLETED_KEY, type TrustTable } from './schema.ts';@@ -168,7 +169,7 @@ function classifier(cols: Columns, assumeClaimed: readonly string[] = [], ceilinsignals.add('frontmatter_provenance');terms.push(`CASE WHEN ${p}.frontmatter ? 'transcript_import' OR ${p}.frontmatter->>'provenance' = 'auto-extracted'OR ${p}.frontmatter->>'dream_generated' = 'true'- OR (CASE WHEN jsonb_typeof(${p}.frontmatter->'extracted_by') = 'string' THEN btrim(${p}.frontmatter->>'extracted_by', E' \\t\\n\\r') END)+ OR (CASE WHEN jsonb_typeof(${p}.frontmatter->'extracted_by') = 'string' THEN ${edgeTrimSql(`${p}.frontmatter->>'extracted_by'`)} END)LIKE '${EXTRACT_ATOMS_EXTRACTOR_PREFIX.replace(/_/g, '\\_')}%' THEN ${rank('agent_written')} END`);}if (cols.has('pages', 'revision_write_request_id')) { const q = request(r); if (q) terms.push(q); }diff --git a/src/core/trust/channel.ts b/src/core/trust/channel.tsindex cd923cff5c..fc2ff36979 100644--- a/src/core/trust/channel.ts+++ b/src/core/trust/channel.ts@@ -24,6 +24,7 @@import type { BrainEngine } from '../engine.ts';import type { WriteRequest } from '../persistence/model.ts';import { CONNECTOR_SOURCE_KINDS } from '../persistence/connector-identity.ts';+import { edgeTrimSql } from '../edge-whitespace.ts';import {CONTENT_ORIGINS, OWNER_TIER_FLOOR, TRUST_TIER_RANK, compareTrust, contentOriginTier, effectiveWriteTrust, isTrustTier, minTrust, trustRankSql,type ContentOrigin, type TrustTier, type WriteTrust,@@ -155,7 +156,7 @@ export function frontmatterTrustCaps(frontmatter: Record<string, unknown> | null*/export function frontmatterTrustCapsSql(fm: string): string[] {const list = (values: readonly string[]) => values.map(v => `'${v.replace(/'/g, "''")}'`).join(',');- const text = (key: string, base = fm) => `(CASE WHEN jsonb_typeof(${base}->'${key}') = 'string' THEN NULLIF(btrim(${base}->>'${key}', E' \\t\\n\\r'), '') END)`;+ const text = (key: string, base = fm) => `(CASE WHEN jsonb_typeof(${base}->'${key}') = 'string' THEN NULLIF(${edgeTrimSql(`${base}->>'${key}'`)}, '') END)`;const stamp = (key: string) => `CASE WHEN ${text(key)} IN (${list(EXTERNAL_CAPTURE_KINDS)}) THEN ${TRUST_TIER_RANK.external_untrusted}WHEN ${text(key)} LIKE 'mcp:%' OR ${text(key)} IN (${list(AGENT_CAPTURE_KINDS)}) THEN ${TRUST_TIER_RANK.agent_written}WHEN ${text(key)} LIKE 'connector:%' OR ${text(key)} IN (${list(CONNECTOR_SOURCE_KINDS)}) THEN ${TRUST_TIER_RANK.external_untrusted} END`;diff --git a/test/edge-whitespace-twins.test.ts b/test/edge-whitespace-twins.test.tsnew file mode 100644index 0000000000..b20a75989a--- /dev/null+++ b/test/edge-whitespace-twins.test.ts@@ -0,0 +1,136 @@+/**+ * SQL twins of TypeScript predicates normalize a value the same way the TypeScript side does. JavaScript's `trim`+ * strips every WhiteSpace and LineTerminator character; Postgres `btrim(x)` strips spaces only, and `lower()` follows+ * the database collation. Each twin here trims with edgeTrimSql (and the privacy aliases lowercase ASCII only), so:+ *+ * - the privacy aliases (`access`, `confidentiality`) give the same answer row-side and in SQL for every edge+ * whitespace character, and remote list and search reads hide an aliased page whatever whitespace its value carries+ * (a YAML block scalar keeps a trailing newline);+ * - the frontmatter trust caps, the local stdio member binding and the database-only page predicate agree with their+ * TypeScript sides on the same inputs.+ *+ * PGLite and Postgres (DATABASE_URL); synthetic names.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { EDGE_WHITESPACE, edgeTrimSql } from '../src/core/edge-whitespace.ts';+import { operationsByName } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { databaseOnlyPageSql, isDatabaseOnlyPage } from '../src/core/persistence/unbound-pages.ts';+import { memberIdentityFor, stdioMemberId, STDIO_MEMBER_KEY } from '../src/core/access/caller.ts';+import { addMember } from '../src/core/access/members.ts';+import { PRIVACY_ALIASES, __resetPrivateVisibilityCacheForTests, isPrivacyPrivatePage, privacyAliasSql } from '../src/core/search/private-visibility.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';++const EDGES = [...EDGE_WHITESPACE];+const engines: Array<{ name: string; engine: BrainEngine }> = [];+let closePostgres: (() => Promise<void>) | undefined;++beforeAll(async () => {+ for (const backend of testBackends()) {+ if (backend === 'pglite') {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ engines.push({ name: backend, engine });+ } else {+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push({ name: backend, engine: isolated.engine });+ closePostgres = isolated.close;+ }+ }+}, 120_000);+afterAll(async () => {+ for (const { engine } of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+});++test('EDGE_WHITESPACE is exactly what String.prototype.trim strips', () => {+ const stripped: string[] = [];+ for (let code = 0; code <= 0xffff; code++) {+ const c = String.fromCharCode(code);+ if (`x${c}`.trim() === 'x') stripped.push(c);+ }+ expect(EDGES.sort()).toEqual(stripped.sort());+});++describe.each(testBackends())('%s', (backend) => {+ const engine = () => engines.find(e => e.name === backend)!.engine;++ test('edgeTrimSql matches trim on every edge character', async () => {+ const values = EDGES.flatMap(c => [`${c}a b${c}`, `${c}${c}x`, `y${c}`, c, `${c} ${c}`]);+ const rows = await engine().executeRaw<{ v: string; t: string }>(`SELECT v, ${edgeTrimSql('v')} AS t FROM unnest($1::text[]) AS v`, [values]);+ for (const row of rows) expect({ v: row.v, t: row.t }).toEqual({ v: row.v, t: row.v.trim() });+ });++ test('privacy aliases: the SQL twin agrees with the row-side check on edge whitespace and case', async () => {+ __resetPrivateVisibilityCacheForTests();+ const words = ['private', 'restricted', 'confidential', 'secret', 'public', 'internal', 'privates', ''];+ const shapes = (w: string) => [w, w.toUpperCase(), `${w[0]?.toUpperCase() ?? ''}${w.slice(1)}`, ...EDGES.flatMap(c => [`${c}${w}`, `${w}${c}`, `${c}${w.toUpperCase()}${c}`])];+ const frontmatters = Object.keys(PRIVACY_ALIASES).flatMap(key => words.flatMap(w => shapes(w).map(v => ({ [key]: v }))));+ frontmatters.push({ access: 'PR\u0130VATE' }, { access: 'pri\u200bvate' }, { confidentiality: 'SECRET\u212a' }, { access: ['private'] }, { access: 1 });+ const rows = await engine().executeRaw<{ i: number; private: boolean }>(+ `SELECT i, ${privacyAliasSql('p')} AS private FROM jsonb_array_elements($1::jsonb) WITH ORDINALITY AS t(frontmatter, i), LATERAL (SELECT t.frontmatter) AS p`,+ [JSON.stringify(frontmatters)]);+ expect(rows).toHaveLength(frontmatters.length);+ for (const row of rows) {+ const fm = frontmatters[Number(row.i) - 1]!;+ expect({ fm, private: row.private }).toEqual({ fm, private: isPrivacyPrivatePage({ type: 'note', frontmatter: fm }) });+ }+ expect(isPrivacyPrivatePage({ type: 'note', frontmatter: { access: 'private\n' } })).toBe(true);+ });++ test('remote list and search hide an aliased page whatever edge whitespace its value carries; local reads see it', async () => {+ __resetPrivateVisibilityCacheForTests();+ const sourceId = `ws-${randomUUID().slice(0, 8)}`;+ await engine().executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);+ const ctx = (remote: boolean) => ({ engine: engine(), config: { engine: engine().kind, embedding_disabled: true }, remote, sourceId, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } }) as unknown as OperationContext;+ const pages: Record<string, string> = {+ 'meetings/block-example': 'access: |\n private',+ 'meetings/tab-example': 'access: "restricted\\t"',+ 'meetings/nbsp-example': 'confidentiality: "secret\\u00a0"',+ 'meetings/open-example': 'access: public',+ };+ for (const [slug, field] of Object.entries(pages)) {+ await operationsByName.put_page!.handler(ctx(false), { slug, content: `---\ntype: meeting\ntitle: ${slug}\n${field}\n---\n# ${slug}\n\nQuillmarrow synthetic agenda.\n` });+ }+ const listed = async (c: OperationContext) => {+ const out = await operationsByName.list_pages!.handler(c, { type: 'meeting' }) as unknown;+ return ((Array.isArray(out) ? out : (out as { pages: unknown[] }).pages) as Array<{ slug: string }>).map(r => r.slug).sort();+ };+ const searched = async (c: OperationContext) =>+ [...new Set((await operationsByName.search!.handler(c, { query: 'Quillmarrow' }) as Array<{ slug: string }>).map(r => r.slug))].sort();+ expect(await listed(ctx(true))).toEqual(['meetings/open-example']);+ expect(await searched(ctx(true))).toEqual(['meetings/open-example']);+ expect(await listed(ctx(false))).toEqual(Object.keys(pages).sort());+ expect(await searched(ctx(false))).toEqual(Object.keys(pages).sort());+ }, 120_000);++ test('the stdio member binding trims like stdioMemberId', async () => {+ await addMember(engine(), 'carol-example');+ try {+ for (const c of EDGES) {+ await engine().setConfig(STDIO_MEMBER_KEY, `carol-example${c}`);+ expect({ c, id: await stdioMemberId(engine()) }).toEqual({ c, id: 'carol-example' });+ expect({ c, identity: await memberIdentityFor(engine(), { principal: { kind: 'local_stdio', id: 'stdio' } }) }).toEqual({ c, identity: ['member:carol-example'] });+ }+ } finally {+ await engine().setConfig(STDIO_MEMBER_KEY, '');+ }+ });++ test('databaseOnlyPageSql agrees with isDatabaseOnlyPage on edge-whitespace paths', async () => {+ const rows = await engine().executeRaw<{ source_path: string; matched: boolean }>(+ `SELECT p.source_path, (${databaseOnlyPageSql('p')}) AS matched FROM (SELECT v AS source_path, NULL::text AS source_uri, 'unbound_source'::text AS database_only_reason FROM unnest($1::text[]) AS v) AS p`,+ [EDGES.flatMap(c => [c, `${c}${c}`, `${c}notes/a.md`])]);+ for (const row of rows) {+ expect({ path: row.source_path, matched: row.matched }).toEqual({ path: row.source_path,+ matched: isDatabaseOnlyPage({ source_path: row.source_path, source_uri: null, database_only_reason: 'unbound_source' }) });+ }+ });+});diff --git a/test/trust-backfill.test.ts b/test/trust-backfill.test.tsindex 47aa6a8d85..d1cb68275a 100644--- a/test/trust-backfill.test.ts+++ b/test/trust-backfill.test.ts@@ -65,6 +65,7 @@ async function seed(engine: BrainEngine) {await addPage('transcript', src, null, { transcript_import: { harness: 'codex', session_id: 's1' } });await addPage('extracted', src, null, { provenance: 'auto-extracted' });await addPage('atom', src, null, { type: 'atom', extracted_by: 'extract_atoms-v0.41.2.1', source_slug: 'p/plain' });+ await addPage('atom_padded', src, null, { type: 'atom', extracted_by: '\u00a0extract_atoms-v0.42', source_slug: 'p/plain' });await addPage('plain', src, null);await addPage('connector', connector, null);@@ -99,7 +100,7 @@ async function seed(engine: BrainEngine) {return { src, connector, pages, facts, take: Number(take!.id), entry: Number(entry!.id) };}type Fixture = Awaited<ReturnType<typeof seed>>;-const EXPECTED_PAGES = { webhook: 'external_untrusted', mcp: 'agent_written', dream: 'agent_written', transcript: 'agent_written', extracted: 'agent_written', atom: 'agent_written', plain: 'unknown', connector: 'external_untrusted' };+const EXPECTED_PAGES = { webhook: 'external_untrusted', mcp: 'agent_written', dream: 'agent_written', transcript: 'agent_written', extracted: 'agent_written', atom: 'agent_written', atom_padded: 'agent_written', plain: 'unknown', connector: 'external_untrusted' };const EXPECTED_FACTS = {sync_request: 'operator_curated', put_page_request: 'agent_written', remote_request: 'agent_written', connector_request: 'external_untrusted',other_request: 'unknown', compacted_request: 'unknown', lane: 'agent_written', fenced_external: 'external_untrusted', plain: 'unknown', connector: 'external_untrusted',@@ -217,7 +218,7 @@ describe('trust backfill dry run before the trust migration', () => {expect(Number(after!.n)).toBe(Number(before!.n));expect(report.schema).toBe('pre_trust');expect(report.tables.every(t => t.current === undefined)).toBe(true);- expect(report.projected).toEqual({ user_confirmed: 0, operator_curated: 1, tool_observed: 0, agent_written: 9, unknown: 4, external_untrusted: 6 });+ expect(report.projected).toEqual({ user_confirmed: 0, operator_curated: 1, tool_observed: 0, agent_written: 10, unknown: 4, external_untrusted: 6 });expect(report.rows).toBe(Object.keys(f.pages).length + Object.keys(f.facts).length + 2);expect((await doctor(engine)).details).toEqual({ schema: 'pre_trust' });await expect(runTrustBackfill(engine, { log: quiet })).rejects.toMatchObject({ code: 'migrations_pending' });diff --git a/test/trust-claim.test.ts b/test/trust-claim.test.tsindex f2d3afcdcb..bc36119598 100644--- a/test/trust-claim.test.ts+++ b/test/trust-claim.test.ts@@ -142,6 +142,9 @@ describe('trust claim-sources', () => {{ dream_generated: true }, { dream_generated: 'true' }, { dream_generated: false }, { provenance: 'manual', source_kind: 'inbox-folder', trust_tier: 'tool_observed' },{ extracted_by: 'extract_atoms-v0.41.2.1' }, { extracted_by: ' extract_atoms-v0.42 ' }, { extracted_by: 'extractXatoms-v1' },{ extracted_by: 'gpt-extractor' }, { extracted_by: 5 }, { extracted_by: 'extract_atoms-v0.41.2.1', trust_tier: 'external_untrusted' },+ { source_kind: '\u00a0webhook\u00a0' }, { captured_via: '\u2003connector:gmail\u000b' }, { ingested_via: 'capture-cli\u3000' },+ { transcript_import: { harness: '\ufeffclaude-code\u2028' } }, { source_url: '\u00a0', clipper: 'x' }, { source_url: 'https://x', clipped_at: '\u000c' },+ { provenance: 'auto-extracted\u00a0' }, { extracted_by: '\u2009extract_atoms-v0.42' },];const sql = `SELECT LEAST(${frontmatterTrustCapsSql('v.fm').join(', ')}) AS r FROM (SELECT $1::text::jsonb AS fm) v`;for (const fm of samples) {