Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(scale): fixture facts/takes fences, injected vectors, grant and writer probes, cached corpus writer (F4c)
garrytan05c39c21a799
diff --git a/scripts/scale/fixture.ts b/scripts/scale/fixture.tsindex ef323ac62d..05de4e1da9 100644--- a/scripts/scale/fixture.ts+++ b/scripts/scale/fixture.ts@@ -1,16 +1,35 @@/**- * Deterministic synthetic brain for the report-only scale harness- * (`bun run test:scale`, docs/TESTING.md "Scale tier"). Same seed and page- * count always produce the same pages, links and known answers, so a report- * can be reproduced from its printed seed. No embeddings, no provider calls.+ * Deterministic synthetic brain for the scale harness (`bun run test:scale`,+ * docs/TESTING.md "Scale tier"). Same seed and page count always produce the+ * same pages, links, fences, vectors and known answers, so a report can be+ * reproduced from its printed seed. No provider calls.** Two sources: `default` and `scale-b`. About a third of `scale-b` bodies copy* a `default` body (partly overlapping corpora). Each page links to three* pages of its own source, carries two dated timeline bullets and a unique* search token. A few island pages have no links in or out (known orphans).+ * Every tenth page (a person) carries a `## Facts` and a `## Takes` fence with+ * two rows each. Each page has a deterministic two-hot query vector+ * (`scaleVector`) that the harness writes onto its chunks and injects through+ * `queryEmbedFn`, so the vector arm runs keylessly.*/+import { renderFactsTable, type ParsedFact } from '../../src/core/facts-fence.ts';+import { renderTakesFence, type ParsedTake } from '../../src/core/takes-fence.ts';+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';-export interface ScalePage { sourceId: string; slug: string; content: string; token: string; links: string[] }+export interface ScalePage {+ sourceId: string;+ slug: string;+ content: string;+ token: string;+ links: string[];+ /** Global position; drives `scaleVector`. */+ index: number;+ facts: number;+ takes: number;+}+export interface ScaleWriter { slug: string; requestId: string; content: string }export interface ScaleFixture {seed: number;pages: ScalePage[];@@ -18,6 +37,13 @@ export interface ScaleFixture {islands: string[];/** A `default` page with outbound links, for traversal and backlink queries. */hub: string;+ /** Vector-arm probe: a query text no keyword matches, embedded as the target page's vector. */+ vectorProbe: { query: string; sourceId: string; slug: string; index: number };+ /** Source-scoped grant probe: a caller allowed only `allowed` must see `visible` and never `hidden`. */+ grant: { allowed: string; visible: { sourceId: string; slug: string; token: string }; hidden: { sourceId: string; slug: string; token: string } };+ /** Two receipt-bearing put_page writers with distinct request ids. */+ writers: [ScaleWriter, ScaleWriter];+ expected: { facts: number; takes: number };}export const SCALE_SOURCES = ['default', 'scale-b'] as const;@@ -40,6 +66,41 @@ function kindFor(i: number): 'people' | 'companies' | 'notes' {return r < 2 ? 'people' : r < 3 ? 'companies' : 'notes';}+/**+ * The two dimensions set in page `index`'s vector. Distinct for every index+ * below dim * (dim - 1), so the target page is the only chunk at cosine 1.+ */+export function scaleVectorDims(index: number, dim: number): [number, number] {+ const a = index % dim;+ const b = (a + 1 + (Math.floor(index / dim) % (dim - 1))) % dim;+ return [a, b];+}++export function scaleVector(index: number, dim: number): Float32Array {+ const v = new Float32Array(dim);+ for (const d of scaleVectorDims(index, dim)) v[d] = Math.SQRT1_2;+ return v;+}++function uuidFrom(rand: () => number): string {+ const hex = Array.from({ length: 32 }, () => Math.floor(rand() * 16).toString(16));+ hex[12] = '4';+ hex[16] = (8 + Math.floor(rand() * 4)).toString(16);+ const h = hex.join('');+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;+}++function fences(s: number, i: number): string[] {+ const facts = renderFactsTable([1, 2].map(rowNum => ({+ rowNum, claim: `Scale fact ${rowNum} for page ${s}-${i}`, kind: 'fact', confidence: 1, visibility: 'world', notability: 'medium',+ validFrom: '2025-01-01', source: 'scale-fixture', active: true,+ } satisfies ParsedFact)));+ const takes = renderTakesFence([1, 2].map(rowNum => ({+ rowNum, claim: `Scale take ${rowNum} for page ${s}-${i}`, kind: 'take', holder: 'brain', weight: 0.5, sinceDate: '2025-01', source: 'scale-fixture', active: true,+ } satisfies ParsedTake)));+ return ['## Facts', '', facts, '', '## Takes', '', takes, ''];+}+export function generateScaleFixture(opts: { pages: number; seed: number }): ScaleFixture {if (!Number.isInteger(opts.pages) || opts.pages < 20) throw new Error('scale fixture needs at least 20 pages');const rand = mulberry32(opts.seed);@@ -62,17 +123,63 @@ export function generateScaleFixture(opts: { pages: number; seed: number }): Scaif (s === 0) defaultBodies.push(prose);const month = String(1 + Math.floor(rand() * 12)).padStart(2, '0');const day = String(1 + Math.floor(rand() * 28)).padStart(2, '0');+ const fenced = i % 10 === 0;const content = ['---', `title: Scale ${s} ${i}`, `type: ${kindFor(i) === 'people' ? 'person' : kindFor(i) === 'companies' ? 'company' : 'note'}`, '---',`# Scale ${s} ${i}`, '', `${prose} Marker ${token}.`, '',...links.map(target => `See [[${target}]].`), '',+ ...(fenced ? fences(s, i) : []),'## Timeline', '', `- **2025-${month}-${day}** | Scale event ${i} recorded`, `- **2026-${month}-${day}** | Scale follow-up ${i}`, '',].join('\n');- pages.push({ sourceId, slug, content, token, links });+ pages.push({ sourceId, slug, content, token, links, index: pages.length, facts: fenced ? 2 : 0, takes: fenced ? 2 : 0 });}}const islands = pages.filter(p => p.sourceId === 'default' && p.links.length === 0&& !pages.some(other => other.sourceId === 'default' && other.links.includes(p.slug))).map(p => p.slug);const hub = pages.find(p => p.sourceId === 'default' && p.links.length === 3)!.slug;- return { seed: opts.seed, pages, islands, hub };+ const target = pages[Math.floor(pages.length * 2 / 3)]!;+ const visible = pages.find(p => p.sourceId === 'scale-b' && p.index % 3 !== 0)!;+ const hidden = pages.find(p => p.sourceId === 'default' && p.index > 0)!;+ const writer = (n: number): ScaleWriter => ({+ slug: `notes/scale-writer-${n}`,+ requestId: uuidFrom(rand),+ content: ['---', `title: Scale writer ${n}`, 'type: note', '---', '', `Concurrent receipt-bearing write ${n} for seed ${opts.seed}.`, ''].join('\n'),+ });+ return {+ seed: opts.seed, pages, islands, hub,+ vectorProbe: { query: `zzvectorprobe${opts.seed}`, sourceId: target.sourceId, slug: target.slug, index: target.index },+ grant: { allowed: 'scale-b', visible: { sourceId: visible.sourceId, slug: visible.slug, token: visible.token },+ hidden: { sourceId: hidden.sourceId, slug: hidden.slug, token: hidden.token } },+ writers: [writer(0), writer(1)],+ expected: { facts: pages.reduce((n, p) => n + p.facts, 0), takes: pages.reduce((n, p) => n + p.takes, 0) },+ };+}++/** Bump when the on-disk corpus layout changes, so a cached corpus is rewritten. */+const CORPUS_LAYOUT = 1;++/**+ * Write the fixture as Markdown under `<dir>/<source>/<slug>.md` for the real+ * `gbrain import` path, once: a corpus whose manifest matches seed, page+ * count and content digest is reused (CI caches only this directory).+ * Returns whether the corpus was (re)written.+ */+export function writeScaleCorpus(fixture: ScaleFixture, dir: string): boolean {+ const hasher = new Bun.CryptoHasher('sha256');+ for (const p of fixture.pages) hasher.update(`${p.sourceId}\0${p.slug}\0${p.content}\0`);+ const manifest = { layout: CORPUS_LAYOUT, seed: fixture.seed, pages: fixture.pages.length, sha256: hasher.digest('hex') };+ const manifestPath = join(dir, 'manifest.json');+ if (existsSync(manifestPath)) {+ try {+ if (JSON.stringify(JSON.parse(readFileSync(manifestPath, 'utf8'))) === JSON.stringify(manifest)) return false;+ } catch { /* unreadable manifest: rewrite the corpus */ }+ }+ for (const sourceId of SCALE_SOURCES) rmSync(join(dir, sourceId), { recursive: true, force: true });+ for (const p of fixture.pages) {+ const file = join(dir, p.sourceId, `${p.slug}.md`);+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, p.content);+ }+ writeFileSync(manifestPath, JSON.stringify(manifest) + '\n');+ return true;}diff --git a/test/scripts/scale-fixture.test.ts b/test/scripts/scale-fixture.test.tsindex e69c460349..40c1e811ac 100644--- a/test/scripts/scale-fixture.test.ts+++ b/test/scripts/scale-fixture.test.ts@@ -1,10 +1,17 @@/**- * The report-only scale harness (`bun run test:scale`) is reproducible only if- * its fixture is: the same seed and page count must give byte-identical pages,- * and the known answers the harness asserts must hold in the fixture itself.+ * The scale harness (`bun run test:scale`) is reproducible only if its fixture+ * is: the same seed and page count must give byte-identical pages, and the+ * known answers the harness asserts (search tokens, islands, the hub, facts and+ * takes counts, the vector probe, the grant probe, the two writers) must hold+ * in the fixture itself.*/import { expect, test } from 'bun:test';-import { generateScaleFixture } from '../../scripts/scale/fixture.ts';+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { generateScaleFixture, scaleVector, scaleVectorDims, writeScaleCorpus } from '../../scripts/scale/fixture.ts';+import { parseFactsFence } from '../../src/core/facts-fence.ts';+import { parseTakesFence } from '../../src/core/takes-fence.ts';test('same seed and size give an identical fixture; another seed differs', () => {const a = generateScaleFixture({ pages: 300, seed: 7 });@@ -30,3 +37,55 @@ test('fixture shape: page count, two sources, unique tokens, links stay in theirexpect(f.pages.find(p => p.slug === f.hub && p.sourceId === 'default')!.links.length).toBe(3);expect(() => generateScaleFixture({ pages: 5, seed: 1 })).toThrow();});++test('fixture additions: facts/takes fences parse, vectors single out their page, grant and writer probes hold', () => {+ const f = generateScaleFixture({ pages: 400, seed: 3 });+ let facts = 0;+ let takes = 0;+ for (const p of f.pages) {+ const parsedFacts = parseFactsFence(p.content);+ const parsedTakes = parseTakesFence(p.content);+ expect(parsedFacts.warnings).toEqual([]);+ expect(parsedTakes.warnings).toEqual([]);+ expect(parsedFacts.facts.length).toBe(p.facts);+ expect(parsedTakes.takes.length).toBe(p.takes);+ facts += parsedFacts.facts.length;+ takes += parsedTakes.takes.length;+ }+ expect(facts).toBeGreaterThan(0);+ expect(f.expected).toEqual({ facts, takes });++ // Two-hot vectors: the probe page is the only page at cosine 1 to its own vector.+ const dim = 64;+ const keys = f.pages.map(p => scaleVectorDims(p.index, dim).join(','));+ expect(new Set(keys).size).toBe(f.pages.length);+ const probe = scaleVector(f.vectorProbe.index, dim);+ const cosines = f.pages.map(p => scaleVector(p.index, dim).reduce((s, x, i) => s + x * probe[i]!, 0));+ expect(cosines.filter(c => c > 0.999)).toHaveLength(1);+ expect(f.pages[f.vectorProbe.index]).toMatchObject({ sourceId: f.vectorProbe.sourceId, slug: f.vectorProbe.slug });+ expect(f.pages.some(p => p.content.includes(f.vectorProbe.query))).toBe(false);++ expect(f.grant.visible.sourceId).toBe(f.grant.allowed);+ expect(f.grant.hidden.sourceId).not.toBe(f.grant.allowed);+ expect(f.pages.filter(p => new RegExp(`\\b${f.grant.hidden.token}\\b`).test(p.content)).map(p => p.sourceId)).toEqual([f.grant.hidden.sourceId]);++ const [a, b] = f.writers;+ expect(a.requestId).not.toBe(b.requestId);+ expect(a.slug).not.toBe(b.slug);+ for (const w of f.writers) expect(w.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);+});++test('writeScaleCorpus writes one Markdown file per page once, reuses a matching corpus and rewrites a stale one', () => {+ const dir = mkdtempSync(join(tmpdir(), 'scale-corpus-'));+ try {+ const f = generateScaleFixture({ pages: 40, seed: 2 });+ expect(writeScaleCorpus(f, dir)).toBe(true);+ for (const p of f.pages) expect(readFileSync(join(dir, p.sourceId, `${p.slug}.md`), 'utf8')).toBe(p.content);+ expect(writeScaleCorpus(f, dir)).toBe(false);+ const other = generateScaleFixture({ pages: 40, seed: 9 });+ expect(writeScaleCorpus(other, dir)).toBe(true);+ for (const p of other.pages) expect(readFileSync(join(dir, p.sourceId, `${p.slug}.md`), 'utf8')).toBe(p.content);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});