Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(g6): strict-source door measurements per writer (red where a writer misses one commit per group or has no managed branch) (GBRA-60)
garrytandc5e41aceb02
diff --git a/test/e2e/g6-brainstorm-strict-postgres.test.ts b/test/e2e/g6-brainstorm-strict-postgres.test.tsnew file mode 100644index 0000000000..14712c3707--- /dev/null+++ b/test/e2e/g6-brainstorm-strict-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../g6-brainstorm-strict.test.ts'));diff --git a/test/e2e/g6-connectors-strict-postgres.test.ts b/test/e2e/g6-connectors-strict-postgres.test.tsnew file mode 100644index 0000000000..0a66a82518--- /dev/null+++ b/test/e2e/g6-connectors-strict-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../g6-connectors-strict.test.ts'));diff --git a/test/e2e/g6-import-strict-postgres.test.ts b/test/e2e/g6-import-strict-postgres.test.tsnew file mode 100644index 0000000000..d082f0c58d--- /dev/null+++ b/test/e2e/g6-import-strict-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../g6-import-strict.test.ts'));diff --git a/test/e2e/g6-ingestion-strict-postgres.test.ts b/test/e2e/g6-ingestion-strict-postgres.test.tsnew file mode 100644index 0000000000..d34838c038--- /dev/null+++ b/test/e2e/g6-ingestion-strict-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../g6-ingestion-strict.test.ts'));diff --git a/test/e2e/git-door-g6-enrichment-postgres.test.ts b/test/e2e/git-door-g6-enrichment-postgres.test.tsnew file mode 100644index 0000000000..9bb33e6995--- /dev/null+++ b/test/e2e/git-door-g6-enrichment-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../git-door-g6-enrichment.test.ts'));diff --git a/test/e2e/git-door-g6-extract-atoms-postgres.test.ts b/test/e2e/git-door-g6-extract-atoms-postgres.test.tsnew file mode 100644index 0000000000..694e807b4e--- /dev/null+++ b/test/e2e/git-door-g6-extract-atoms-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../git-door-g6-extract-atoms.test.ts'));diff --git a/test/e2e/git-door-g6-patterns-postgres.test.ts b/test/e2e/git-door-g6-patterns-postgres.test.tsnew file mode 100644index 0000000000..14fe8e2d1d--- /dev/null+++ b/test/e2e/git-door-g6-patterns-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../git-door-g6-patterns.test.ts'));diff --git a/test/e2e/git-door-g6-synthesize-postgres.test.ts b/test/e2e/git-door-g6-synthesize-postgres.test.tsnew file mode 100644index 0000000000..4ef191d6b3--- /dev/null+++ b/test/e2e/git-door-g6-synthesize-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../git-door-g6-synthesize.test.ts'));diff --git a/test/g6-brainstorm-strict.test.ts b/test/g6-brainstorm-strict.test.tsnew file mode 100644index 0000000000..75e4302409--- /dev/null+++ b/test/g6-brainstorm-strict.test.ts@@ -0,0 +1,41 @@+/**+ * G6 (git-canonical memory): `gbrain brainstorm --save` and `gbrain lsd --save` on a strict (canonical: git) managed+ * source are door-only.+ *+ * Both save through persistSavedIdea (commands/brainstorm.ts), with the page content the CLI builds after the run+ * (serializeMarkdown of the run's frontmatter and body, so no model call is involved, as in test/brainstorm/save.test.ts).+ * After three saves every idea page is at HEAD with the bytes on disk, the tree is clean, the git-gap census reports no+ * gap, and the saves make at most one commit per publication group.+ * PGLite here; Postgres in test/e2e/g6-brainstorm-strict-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { buildIdeaSlug, persistSavedIdea } from '../src/commands/brainstorm.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { describeMeasure, expectDoorOnly, head, initStrictCheckout, measureBatch, strictSource } from './helpers/strict-door-census.ts';++const runs: Array<{ label: 'brainstorm' | 'lsd'; question: string }> = [+ { label: 'brainstorm', question: 'How could alice-example grow acme-example' },+ { label: 'brainstorm', question: 'What would bob-example build next' },+ { label: 'lsd', question: 'Why does acme-example ship weekly' },+];+const saved = (label: string, question: string) => serializeMarkdown({ mode: label, question, source_kind: label }, `# ${question}\n\nIdea body.`, '',+ { type: 'note', title: `${label === 'lsd' ? 'LSD' : 'Brainstorm'}: ${question}`, tags: [] });++for (const backend of testBackends()) describe(`[${backend}] G6: brainstorm and lsd --save on a strict source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('three saves: every idea page at HEAD, clean tree, no census gap, one commit per group', () => managedBrain(async ({ engine, root }) => {+ await strictSource(engine);+ const base = head(root);+ const slugs = runs.map((run, i) => buildIdeaSlug(run.question, run.label, `g6000${i}`));+ const outcomes = [];+ for (const [i, run] of runs.entries()) outcomes.push(await persistSavedIdea(engine, { slug: slugs[i]!, content: saved(run.label, run.question), provenanceVia: run.label }));+ console.log(`[G6 brainstorm/${backend}] outcomes=${JSON.stringify(outcomes.map(o => ({ dbSaved: o.dbSaved, dbError: o.dbError?.slice(0, 120), held: o.held, written: o.writeThrough.written, skipped: o.writeThrough.skipped })))}`);+ const m = await measureBatch(engine, 'default', root, base, slugs);+ console.log(describeMeasure(`brainstorm/${backend}`, m));+ expect(outcomes.map(o => o.dbSaved)).toEqual(slugs.map(() => true));+ expectDoorOnly(m, expect);+ }, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);+});diff --git a/test/g6-connectors-strict.test.ts b/test/g6-connectors-strict.test.tsnew file mode 100644index 0000000000..a2bcb52d33--- /dev/null+++ b/test/g6-connectors-strict.test.ts@@ -0,0 +1,74 @@+/**+ * G6 (git-canonical memory): the managed connectors on a strict (canonical: git) source are door-only.+ *+ * A managed Google sweep (google/sweep-shared.ts importRendered -> ManagedConnectorSync.importMarkdown) and a managed+ * GitHub sweep (github-source.ts materializePage -> the same importMarkdown) admit one connector_v2_import request per+ * item (persistence/connector-sync.ts submit) and the owner publishes each through publishMutation (PGLite) or+ * publishSingleWrite (Postgres). After a sweep of three items every page is at HEAD with the bytes on disk, the tree+ * is clean, the git-gap census reports no gap, and the sweep makes at most one commit per publication group.+ * PGLite here; Postgres in test/e2e/g6-connectors-strict-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { parseGitHubSourceConfig, runGitHubSync } from '../src/core/github-source.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { completeBaselineSweep, githubConfig, googleConfig, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { describeMeasure, expectDoorOnly, head, initStrictCheckout, measureBatch, strictSource } from './helpers/strict-door-census.ts';++const people = ['alice-example', 'bob-example', 'carol-example'];+const contactsFetch = withGoogleAccount(async (url: string) => json(url.includes('/settings/sendAs') ? { sendAs: [] } : {+ connections: people.map(id => ({ resourceName: `people/${id}`, names: [{ displayName: id.replace('-example', ' Example') }],+ emailAddresses: [{ value: `${id}@example.invalid` }], organizations: [{ name: 'Acme Example' }] })),+ nextSyncToken: 'contacts-g6',+}));++const issues = [1, 2, 3].map(number => ({ number, title: `Example issue ${number}`, state: 'open', body: `Synthetic issue body ${number}.`,+ created_at: '2026-01-01T00:00:00Z', updated_at: `2026-01-0${number + 1}T00:00:00Z`, labels: [], assignees: [], user: { login: 'example-user' },+ html_url: `https://github.com/acme-example/app/issues/${number}` }));+const issuesFetch = async (url: string) => {+ const path = new URL(url).pathname;+ if (path.endsWith('/issues')) return json(issues);+ if (path.endsWith('/pulls') || path.endsWith('/comments')) return json([]);+ const detail = /\/issues\/(\d+)$/.exec(path);+ if (detail) return json(issues.find(issue => issue.number === Number(detail[1])));+ if (path === '/repos/acme-example/app') return json({ full_name: 'acme-example/app', private: true, default_branch: 'main' });+ throw new Error(`Unexpected external fixture route ${path}`);+};++const env = { CONNECTOR_TEST_TOKEN: 'synthetic-local-fixture' };+const connectorSource = (config: Record<string, unknown>) => async ({ engine, root }: { engine: import('../src/core/engine.ts').BrainEngine; root: string }) => {+ initStrictCheckout(root);+ await engine.executeRaw("UPDATE sources SET config=$1::text::jsonb WHERE id='default'", [JSON.stringify(config)]);+};+const connectorSlugs = (engine: import('../src/core/engine.ts').BrainEngine) => engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL ORDER BY slug").then(rows => rows.map(row => row.slug));++for (const backend of testBackends()) describe(`[${backend}] G6: managed connectors on a strict source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('Google contacts sweep of three people: every page at HEAD, clean tree, no census gap, one commit per group', () => withEnv(env, () => managedBrain(async ({ engine, root }) => {+ await strictSource(engine);+ const base = head(root);+ const run = () => runGoogleSync(engine, 'default', parseGoogleSourceConfig(googleConfig, root), options, contactsFetch);+ await completeBaselineSweep(engine, 'default', run);+ const slugs = await connectorSlugs(engine);+ expect(slugs.length).toBeGreaterThanOrEqual(people.length);+ const m = await measureBatch(engine, 'default', root, base, slugs);+ console.log(describeMeasure(`google/${backend}`, m));+ expectDoorOnly(m, expect);+ }, { databaseUrl, setup: connectorSource(googleConfig) })), 120_000);++ test('GitHub sweep of three issues: every page at HEAD, clean tree, no census gap, one commit per group', () => withEnv(env, () => managedBrain(async ({ engine, root }) => {+ await strictSource(engine);+ const base = head(root);+ const run = () => runGitHubSync(engine, 'default', parseGitHubSourceConfig(githubConfig, root), options, issuesFetch);+ await completeBaselineSweep(engine, 'default', run);+ const slugs = await connectorSlugs(engine);+ expect(slugs.length).toBeGreaterThanOrEqual(issues.length);+ const m = await measureBatch(engine, 'default', root, base, slugs);+ console.log(describeMeasure(`github/${backend}`, m));+ expectDoorOnly(m, expect);+ }, { databaseUrl, setup: connectorSource(githubConfig) })), 120_000);+});diff --git a/test/g6-import-strict.test.ts b/test/g6-import-strict.test.tsnew file mode 100644index 0000000000..b353818d2d--- /dev/null+++ b/test/g6-import-strict.test.ts@@ -0,0 +1,57 @@+/**+ * G6 (git-canonical memory): `gbrain import` on a strict (canonical: git) managed source is door-only.+ *+ * GBRA-176 found that a classic import rewrites the files it imports (it normalizes frontmatter order) and leaves the+ * rewrite uncommitted. On a strict source the managed import (import-mutations.ts importManagedFiles, prepared by+ * import-prepare.ts prepareManagedImportMutation) publishes through publishMutation / publishGroup, so the door must+ * commit exactly the bytes it writes: a file whose frontmatter the import normalizes and a file it leaves byte for byte+ * untouched, both already committed and both new to Git. After the batch every page is at HEAD with the bytes on disk,+ * the tree is clean, the git-gap census reports no gap, and the batch makes at most one commit per publication group.+ * PGLite here; Postgres in test/e2e/g6-import-strict-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { runImport } from '../src/commands/import.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';+import { git } from './helpers/git-publication.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { describeMeasure, expectDoorOnly, head, initStrictCheckout, measureBatch, strictSource } from './helpers/strict-door-census.ts';++/** Frontmatter in an order the import rewrites: title before type, an extra key between them. */+const reordered = (title: string) => `---\ntitle: ${title}\nsummary: ${title} summary\ntype: note\n---\n\n${title} body.\n`;+/** The exact bytes the import renders for such a page, so it leaves the file untouched. */+const canonical = (title: string) => serializeMarkdown({}, `${title} body.`, '', { type: 'note', title, tags: [] });++const files: Record<string, string> = {+ 'notes/alice-example-tracked-reordered.md': reordered('Alice example tracked'),+ 'notes/acme-example-tracked-canonical.md': canonical('Acme example tracked'),+ 'notes/alice-example-new-reordered.md': reordered('Alice example new'),+ 'notes/acme-example-new-canonical.md': canonical('Acme example new'),+};+const slugs = Object.keys(files).map(path => path.replace(/\.md$/, ''));++for (const backend of testBackends()) describe(`[${backend}] G6: gbrain import on a strict source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('normalized and untouched files, committed and new: every page at HEAD, clean tree, no census gap, one commit per group', () => managedBrain(async ({ engine, root }) => {+ mkdirSync(join(root, 'notes'));+ for (const [path, bytes] of Object.entries(files)) writeFileSync(join(root, path), bytes);+ git(root, 'add', ...Object.keys(files).filter(path => path.includes('-tracked-')));+ git(root, 'commit', '-qm', 'user-authored notes');+ await strictSource(engine);+ const base = head(root);+ const result = await runImport(engine, [root, '--no-embed'], { sourceId: 'default' });+ expect(result).toMatchObject({ imported: slugs.length, errors: 0, failures: [] });+ const m = await measureBatch(engine, 'default', root, base, slugs);+ console.log(describeMeasure(`import/${backend}`, m));+ for (const [path, bytes] of Object.entries(files)) {+ const disk = readFileSync(join(root, path), 'utf8');+ console.log(`[G6 import/${backend}] ${path} rewritten=${disk !== bytes}`);+ }+ expect(readFileSync(join(root, 'notes/acme-example-new-canonical.md'), 'utf8')).toBe(files['notes/acme-example-new-canonical.md']);+ expect(readFileSync(join(root, 'notes/alice-example-new-reordered.md'), 'utf8')).not.toBe(files['notes/alice-example-new-reordered.md']);+ expectDoorOnly(m, expect);+ }, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);+});diff --git a/test/g6-ingestion-strict.test.ts b/test/g6-ingestion-strict.test.tsnew file mode 100644index 0000000000..91950ed4db--- /dev/null+++ b/test/g6-ingestion-strict.test.ts@@ -0,0 +1,70 @@+/**+ * G6 (git-canonical memory): inbox-folder captures on a strict (canonical: git) managed source are door-only.+ *+ * The inbox-folder source (ingestion/sources/inbox-folder.ts) writes no page itself: it emits one IngestionEvent per+ * dropped file, which the ingestion daemon submits as an ingest_capture job (minions/handlers/ingest-capture.ts). That+ * handler is the writer, so this drives both: three files dropped in the inbox, each event handed to the handler the+ * way the job worker runs it. After the batch every captured page is at HEAD with the bytes on disk, the tree is clean,+ * the git-gap census reports no gap, and the batch makes at most one commit per publication group.+ * PGLite here; Postgres in test/e2e/g6-ingestion-strict-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { EventEmitter } from 'node:events';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { FSWatcher } from 'chokidar';+import { createInboxFolderSource } from '../src/core/ingestion/sources/inbox-folder.ts';+import { IngestionTestHarness } from '../src/core/ingestion/test-harness.ts';+import { makeIngestCaptureHandler } from '../src/core/minions/handlers/ingest-capture.ts';+import type { MinionJobContext } from '../src/core/minions/types.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { describeMeasure, expectDoorOnly, head, initStrictCheckout, measureBatch, strictSource } from './helpers/strict-door-census.ts';++/** A chokidar stand-in: `ready` fires on start, `add` when the test drops a file. */+function stubWatcher() {+ const emitter = new EventEmitter();+ const watcher = { on: (event: string, fn: (...args: unknown[]) => void) => { emitter.on(event, fn); return watcher; },+ once: (event: string, fn: (...args: unknown[]) => void) => { if (event === 'ready') queueMicrotask(() => fn()); else emitter.once(event, fn); return watcher; },+ close: async () => { emitter.removeAllListeners(); } } as unknown as FSWatcher;+ return { watcher, add: (path: string) => emitter.emit('add', path) };+}++const job = (data: Record<string, unknown>): MinionJobContext => ({ id: 1, name: 'ingest_capture', data, attempts_made: 1, signal: new AbortController().signal,+ deadlineAtMs: null, shutdownSignal: new AbortController().signal, updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {},+ isActive: async () => true, readInbox: async () => [] });++const drops: Record<string, string> = {+ 'alice-example.md': '---\ntitle: Alice example capture\n---\n\nMet alice-example about the acme-example launch.\n',+ 'acme-example.md': '---\ntitle: Acme example capture\n---\n\nAcme example quarterly notes.\n',+ 'bob-example.md': '---\ntitle: Bob example capture\n---\n\nBob example follow-up.\n',+};++for (const backend of testBackends()) describe(`[${backend}] G6: inbox-folder captures on a strict source`, () => {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ test('three dropped files: every captured page at HEAD, clean tree, no census gap, one commit per group', () => managedBrain(async ({ engine, root }) => {+ await strictSource(engine);+ const inbox = mkdtempSync(join(tmpdir(), 'gbrain-g6-inbox-'));+ try {+ const stub = stubWatcher();+ const harness = new IngestionTestHarness();+ await harness.run(createInboxFolderSource({ inboxDir: inbox, debounceMs: 10, _watchFactory: () => stub.watcher }));+ mkdirSync(inbox, { recursive: true });+ for (const [name, body] of Object.entries(drops)) { writeFileSync(join(inbox, name), body); stub.add(join(inbox, name)); }+ for (let i = 0; i < 200 && harness.events.length < 3; i++) await Bun.sleep(10);+ await harness.stop();+ expect(harness.events).toHaveLength(3);+ const base = head(root);+ const handler = makeIngestCaptureHandler(engine);+ const slugs = Object.keys(drops).map(name => `inbox/${name.replace(/\.md$/, '')}`);+ const results = await Promise.allSettled(harness.events.map(event => handler(job({ event, slug: `inbox/${String(event.metadata?.original_filename).replace(/\.md$/, '')}` }))));+ console.log(`[G6 ingest-capture/${backend}] results=${JSON.stringify(results.map(r => r.status === 'fulfilled' ? r.value.status : (r.reason as { code?: string }).code ?? String(r.reason)))}`);+ const m = await measureBatch(engine, 'default', root, base, slugs);+ console.log(describeMeasure(`ingest-capture/${backend}`, m));+ expect(results.map(r => r.status)).toEqual(slugs.map(() => 'fulfilled'));+ expectDoorOnly(m, expect);+ } finally { rmSync(inbox, { recursive: true, force: true }); }+ }, { databaseUrl, setup: ({ root }) => initStrictCheckout(root) }), 120_000);+});diff --git a/test/git-door-g6-enrichment.test.ts b/test/git-door-g6-enrichment.test.tsnew file mode 100644index 0000000000..09a287668b--- /dev/null+++ b/test/git-door-g6-enrichment.test.ts@@ -0,0 +1,59 @@+/**+ * G6 (git-canonical memory): extract_entities (enrichment-service.ts enrichEntity) on a strict source. Its managed+ * branch writes a stub page through put_page and the mention's timeline bullet through add_timeline_entry, both page+ * mutations through the door. Target for a batch of three entities: every page at HEAD with the content its row+ * holds, a clean tree, no git-gap census gap, and at most one commit per publication group (test/helpers/strict-door-audit.ts).+ * Runs on PGLite, and on Postgres through test/e2e/git-door-g6-enrichment-postgres.test.ts. Synthetic content only.+ */+import { describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { operations } from '../src/core/operations.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { durableGitRepo } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { auditDoor, expectDoorTarget, headCommit, strictSource, summarizeAudit } from './helpers/strict-door-audit.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const SOURCE = 'meetings/source-a';+const TEXT = 'lunch with Alice Example, then a call with Carol Example and a visit to Acme Example Labs.';+const ENTITIES = ['people/alice-example', 'people/carol-example', 'companies/acme-example-labs'];+const op = operations.find(o => o.name === 'extract_entities')!;+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+const put = (ctx: OperationContext, slug: string, content: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content } });++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe(`[${backend}] G6: extract_entities on a strict source writes only through the door`, () => {+ test('three new entity stubs and their timeline bullets: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ await put(ctx, SOURCE, '---\ntype: meeting\ntitle: Source A\n---\n\nMet people.\n');+ await settleManagedGitEffects(engine);+ const since = await headCommit(root);+ const result = await op.handler(ctx, { text: TEXT, source_slug: SOURCE }) as { entities: Array<{ slug: string; action: string; timelineAdded: boolean }> };+ expect(result.entities.map(e => [e.slug, e.action, e.timelineAdded]).sort()).toEqual(ENTITIES.map(slug => [slug, 'created', true]).sort());+ await settleManagedGitEffects(engine);+ const audit = await auditDoor(engine, root, { since, slugs: ENTITIES });+ console.log(summarizeAudit(`enrichment stubs ${backend}`, audit));+ expectDoorTarget(audit, engine.kind);+ }, { databaseUrl, setup }), 180_000);++ test('three existing entity pages get their timeline bullets: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ await put(ctx, SOURCE, '---\ntype: meeting\ntitle: Source A\n---\n\nMet people.\n');+ await put(ctx, ENTITIES[0]!, '---\ntype: person\ntitle: Alice Example\n---\n\nA person.\n');+ await put(ctx, ENTITIES[1]!, '---\ntype: person\ntitle: Carol Example\n---\n\nA person.\n');+ await put(ctx, ENTITIES[2]!, '---\ntype: company\ntitle: Acme Example Labs\n---\n\nA company.\n');+ await settleManagedGitEffects(engine);+ const since = await headCommit(root);+ const result = await op.handler(ctx, { text: TEXT, source_slug: SOURCE }) as { entities: Array<{ slug: string; action: string; timelineAdded: boolean }> };+ expect(result.entities.map(e => [e.slug, e.action, e.timelineAdded]).sort()).toEqual(ENTITIES.map(slug => [slug, 'updated', true]).sort());+ await settleManagedGitEffects(engine);+ const audit = await auditDoor(engine, root, { since, slugs: ENTITIES });+ console.log(summarizeAudit(`enrichment timeline ${backend}`, audit));+ expectDoorTarget(audit, engine.kind);+ }, { databaseUrl, setup }), 180_000);+ });+}diff --git a/test/git-door-g6-extract-atoms.test.ts b/test/git-door-g6-extract-atoms.test.tsnew file mode 100644index 0000000000..af46bb1266--- /dev/null+++ b/test/git-door-g6-extract-atoms.test.ts@@ -0,0 +1,93 @@+/**+ * G6 (git-canonical memory): dream extract-atoms on a strict source. Its managed branch (extract-atoms.ts+ * publishManagedAtomGeneration, persistence/atom-maintenance.ts) admits one managed generation per origin: create+ * members (managed_atom_page), the managed_generation_activate request, overwrite and retire members, and the batch+ * completion. That is also the generations page adapter's managed path (generations/managed.ts): adapters/page.ts+ * importPageItem only runs inside an unmanaged activation transaction. Target for a batch of three atoms: every atom+ * (and the origin page) at HEAD with the content its row holds, a clean tree, no git-gap census gap, and at most one+ * commit per publication group (test/helpers/strict-door-audit.ts). The LLM is a stub (_chat), as in+ * test/managed-extract-atoms.test.ts. Runs on PGLite, and on Postgres through+ * test/e2e/git-door-g6-extract-atoms-postgres.test.ts. Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { configureGateway, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { durableGitRepo, gitAsync } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { auditDoor, expectDoorTarget, headCommit, strictSource, summarizeAudit } from './helpers/strict-door-audit.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';++const ORIGIN = 'notes/source-a';+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+const chatReturning = (titles: string[]) => async (): Promise<ChatResult> => ({+ text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}, from the Acme Example review.` }))), blocks: [], stopReason: 'end',+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' });+const seedOrigin = async (ctx: OperationContext, body: string) => {+ const current = await ctx.engine.readPageSnapshot(ORIGIN, { sourceId: 'default' });+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: ORIGIN, request_id: randomUUID(),+ content: `---\ntype: source\ntitle: Source A\n---\n\n${body}\n`, ...(current ? { expected_revision: current.revision } : {}) } });+ await settleManagedGitEffects(ctx.engine);+};+const extract = async (engine: BrainEngine, titles: string[]) => {+ const page = (await engine.getPage(ORIGIN, { sourceId: 'default' }))!;+ return runPhaseExtractAtoms(engine, { sourceId: 'default', _transcripts: [], _pages: [{ slug: page.slug, content: page.compiled_truth, contentHash: page.content_hash! }],+ _chat: chatReturning(titles) });+};+const liveAtoms = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE source_id='default' AND type='atom' AND deleted_at IS NULL ORDER BY slug")).map(row => row.slug);++beforeAll(() => configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} }));+afterAll(() => resetGateway());++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe(`[${backend}] G6: extract-atoms on a strict source writes only through the door`, () => {+ test('a three-atom generation: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ await seedOrigin(ctx, 'Alice Example reviewed the Acme Example launch plan with the team. '.repeat(40));+ const before = await auditDoor(engine, root, { since: await headCommit(root), slugs: [ORIGIN] });+ expect(before.census.states).toMatchObject({ equal: 1, database_ahead: 0, worktree_only: 0, undeclared_database_only: 0 });+ const since = await headCommit(root);+ const result = await extract(engine, ['Measure progress weekly', 'Ship small changes', 'Write the exit criteria first']);+ expect(result.status).toBe('ok');+ expect(result.details?.atoms_extracted).toBe(3);+ await settleManagedGitEffects(engine);+ const atoms = await liveAtoms(engine);+ expect(atoms).toHaveLength(3);+ const audit = await auditDoor(engine, root, { since, slugs: [...atoms, ORIGIN] });+ console.log(summarizeAudit(`extract-atoms create ${backend}`, audit));+ expectDoorTarget({ ...audit, pages: audit.pages.filter(page => page.slug !== ORIGIN) }, engine.kind);+ expect(audit.pages.find(page => page.slug === ORIGIN)).toMatchObject({ row: { state: 'equal' }, commits: 0 });+ }, { databaseUrl, setup }), 180_000);++ test('a re-extraction after an origin edit (three creates, three retirements): at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ await seedOrigin(ctx, 'Alice Example reviewed the Acme Example launch plan with the team. '.repeat(40));+ expect((await extract(engine, ['Measure progress weekly', 'Ship small changes', 'Write the exit criteria first'])).status).toBe('ok');+ await settleManagedGitEffects(engine);+ const first = await liveAtoms(engine);+ expect(first).toHaveLength(3);+ await seedOrigin(ctx, 'Alice Example revised the Acme Example launch plan after the pilot. '.repeat(40));+ const since = await headCommit(root);+ const result = await extract(engine, ['Pilot before launch', 'Keep the checklist short', 'Review outcomes monthly']);+ expect(result.status).toBe('ok');+ await settleManagedGitEffects(engine);+ const second = await liveAtoms(engine);+ expect(second).toHaveLength(3);+ expect(second.filter(slug => first.includes(slug))).toEqual([]);+ const audit = await auditDoor(engine, root, { since, slugs: second });+ console.log(summarizeAudit(`extract-atoms re-extract ${backend}`, audit));+ for (const slug of first) expect({ slug, head: await gitAsync(root, 'cat-file', '-e', `HEAD:${slug}.md`).then(() => 'present', () => 'absent') }).toEqual({ slug, head: 'absent' });+ expectDoorTarget(audit, engine.kind);+ // A retirement is a page publication of the same generation: its six members are one group.+ const generation = new Set([...first, ...second].map(slug => `${slug}.md`));+ expect(audit.commits.filter(commit => commit.paths.some(path => generation.has(path))).length).toBeLessThanOrEqual(engine.kind === 'postgres' ? 1 : generation.size);+ }, { databaseUrl, setup }), 240_000);+ });+}diff --git a/test/git-door-g6-patterns.test.ts b/test/git-door-g6-patterns.test.tsnew file mode 100644index 0000000000..353441f340--- /dev/null+++ b/test/git-door-g6-patterns.test.ts@@ -0,0 +1,117 @@+/**+ * G6 (git-canonical memory): the patterns phase (src/core/cycle/patterns.ts runPhasePatterns) and the claim-source+ * de-duplication it runs first (src/core/cycle/pattern-claim-sources.ts dedupePatternClaimSources) on a strict source.+ * On a managed brain the patterns child writes each page with put_page (the admitted subagent operation), the phase+ * rewrites each grounded page (writeGroundedPage) and stamps its provenance (stampMaintenancePage), both maintenance+ * publications (publishMaintenancePage); de-duplication publishes each rewritten page the same way. Target for a batch+ * of three pages: every page at HEAD with the content its row holds, a clean tree, no git-gap census gap, and at most one+ * commit per publication group (test/helpers/strict-door-audit.ts). Runs on PGLite, and on Postgres through+ * test/e2e/git-door-g6-patterns-postgres.test.ts. The model is a mocked chat transport; synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { runPhasePatterns } from '../src/core/cycle/patterns.ts';+import { dedupePatternClaimSources, resolveClaimSources } from '../src/core/cycle/pattern-claim-sources.ts';+import { maintenancePreflight } from '../src/core/persistence/prepared-maintenance.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';+import { durableGitRepo } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { auditDoor, expectDoorTarget, headCommit, strictSource, summarizeAudit } from './helpers/strict-door-audit.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const PREFIX = 'wiki/personal/patterns';+const REFLECTIONS = [0, 1, 2].map(i => 'wiki/personal/reflections/source-a-' + i);+const PATTERNS = ['ask-early', 'morning-focus', 'ship-smaller'].map(name => PREFIX + '/' + name);+const QUOTES = ['ask early', 'protect the morning', 'ship smaller pieces'];+const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+const put = (ctx: OperationContext, slug: string, content: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content } });++/** The batch starts from a clean checkout and a census with no gap, so any gap after it is the writer's. */+async function expectCleanBaseline(engine: BrainEngine, root: string, since: string): Promise<void> {+ const baseline = await auditDoor(engine, root, { since, slugs: [] });+ expect(baseline.porcelain).toBe('');+ expect({ gaps: baseline.gaps, sample: baseline.gapSample }).toEqual({ gaps: { database_ahead: 0, worktree_only: 0, undeclared_database_only: 0 }, sample: [] });+}++beforeAll(() => { configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} }); });+afterAll(() => { __setChatTransportForTests(null); resetGateway(); });++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;+ describe('[' + backend + '] G6: patterns writers on a strict source write only through the door', () => {+ test('runPhasePatterns: three child-written pattern pages, grounded and stamped: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ for (const [i, slug] of REFLECTIONS.entries()) {+ await put(ctx, slug, '---\ntype: note\ntitle: Reflection ' + i + '\n---\nI keep saying "ship smaller pieces", "protect the morning" and "ask early". Entry ' + i + ' from source-a.\n');+ }+ await settleManagedGitEffects(engine);+ await engine.setConfig('dream.patterns.enabled', 'true');+ await engine.setConfig('dream.quote_verify', 'true');+ await engine.setConfig('models.dream.patterns', 'anthropic:claude-sonnet-4-6');+ await engine.setConfig('agent.use_gateway_loop', 'true');+ const since = await headCommit(root);+ await expectCleanBaseline(engine, root, since);+ let calls = 0;+ __setChatTransportForTests(async opts => {+ const i = calls++;+ const write = i < PATTERNS.length;+ const links = REFLECTIONS.map(slug => '[[' + slug + ']]').join(', ');+ return { text: write ? '' : 'Saved the patterns.', blocks: write ? [{ type: 'tool-call', toolCallId: 'pattern-write-' + i, toolName: 'brain_put_page', input: {+ slug: PATTERNS[i], content: '---\ntitle: Pattern ' + i + '\ntype: note\n---\nAcross three reflections you repeat "' + QUOTES[i] + '" (' + links + ').\n',+ } }] : [{ type: 'text', text: 'Saved the patterns.' }], stopReason: write ? 'tool_calls' : 'end',+ usage: { input_tokens: 100, output_tokens: 100, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: opts.model!, providerId: 'anthropic' };+ });+ try {+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-g6-patterns' }, async () => {+ const result = await runPhasePatterns(engine, { brainDir: root, sourceId: 'default', dryRun: false, once: true, cycleDate: '2026-02-03' });+ expect({ status: result.status, written: result.details.patterns_written, held: result.details.publish_deferred, child: result.details.child_outcome,+ grounded: (result.details.quote_verify as { pages?: number } | undefined)?.pages })+ .toEqual({ status: 'ok', written: 3, held: 0, child: 'completed', grounded: 3 });+ });+ } finally { __setChatTransportForTests(null); }+ for (const slug of PATTERNS) {+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page.frontmatter)+ .toMatchObject({ dream_generated: true, dream_cycle_date: '2026-02-03', quote_verified_at: '2026-02-03', raw_trace_exempt: true });+ }+ await settleManagedGitEffects(engine);+ const audit = await auditDoor(engine, root, { since, slugs: PATTERNS });+ console.log(summarizeAudit('patterns phase ' + backend, audit));+ expectDoorTarget(audit, engine.kind);+ }, { databaseUrl, setup }), 180_000);++ test('dedupePatternClaimSources: three pattern pages with inline claim-source lists: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ const list = Array.from({ length: 20 }, (_, i) => 'wiki/personal/reflections/source-a-old-' + i);+ const claims = Array.from({ length: 3 }, (_, i) => ' - text: claim ' + i + ' about acme-example\n reason: quote_not_in_source\n sources:\n'+ + list.map(p => ' - ' + p).join('\n')).join('\n');+ for (const [i, slug] of PATTERNS.entries()) {+ await put(ctx, slug, '---\ntype: note\ntitle: Legacy pattern ' + i + "\ndream_generated: true\nquote_verified_at: '2026-01-01'\nunverified_claims:\n" + claims+ + '\n---\nA legacy pattern body ' + i + ' for alice-example.\n');+ }+ await settleManagedGitEffects(engine);+ const since = await headCommit(root);+ await expectCleanBaseline(engine, root, since);+ const maintenance = await maintenancePreflight(engine, 'default', root);+ expect(maintenance).not.toBeNull();+ const result = await dedupePatternClaimSources(engine, maintenance, PREFIX, 'default');+ expect(result).toEqual({ rewritten: PATTERNS, held: [] });+ for (const slug of PATTERNS) {+ const fm = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page.frontmatter as Record<string, unknown>;+ for (const claim of fm.unverified_claims as Array<{ sources: string[] }>) {+ expect(claim.sources).toHaveLength(1);+ expect(resolveClaimSources(fm, claim)).toEqual(list);+ }+ }+ await settleManagedGitEffects(engine);+ const audit = await auditDoor(engine, root, { since, slugs: PATTERNS });+ console.log(summarizeAudit('pattern-claim-sources ' + backend, audit));+ expectDoorTarget(audit, engine.kind);+ }, { databaseUrl, setup }), 180_000);+ });+}diff --git a/test/git-door-g6-synthesize.test.ts b/test/git-door-g6-synthesize.test.tsnew file mode 100644index 0000000000..fb3545a37d--- /dev/null+++ b/test/git-door-g6-synthesize.test.ts@@ -0,0 +1,184 @@+/**+ * G6 (git-canonical memory): the dream synthesis writers on a strict source.+ *+ * - synthesize_concepts (synthesize-concepts.ts runPhaseSynthesizeConcepts): on a managed brain it publishes each concept+ * through publishManagedConcept (concept-publication.ts), private first and then world once the provenance edges land.+ * A new concept publishes database-only (`file: false`) under the derive-phase folder `concepts/`, a declared+ * database-only class (DERIVE_PHASE_DB_ONLY_DEFAULTS); a concept that already has a file republishes it.+ * - synthesize quote-verify repair: verifyAndRepairDreamPages (synthesize-verify.ts) is the unmanaged branch only; a+ * managed brain routes to postprocessManagedSynthesis (synthesize-postprocess.ts), driven here through the whole+ * synthesize phase with a stubbed provider whose oneshot child writes three reflection pages, each carrying an+ * invented quotation the repair must strip.+ *+ * Target for each batch (test/helpers/strict-door-audit.ts): every filed page at HEAD with the content its row holds, a+ * clean tree, no git-gap census gap, and at most one commit per publication group. Runs on PGLite, and on Postgres+ * through test/e2e/git-door-g6-synthesize-postgres.test.ts. Synthetic content only.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { OperationContext } from '../src/core/ops/contract.ts';+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';+import { runPhaseSynthesizeConcepts } from '../src/core/cycle/synthesize-concepts.ts';+import { runPhaseSynthesize } from '../src/core/cycle/synthesize.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { durableGitRepo, gitAsync } from './helpers/git-publication.ts';+import { managedBrain, settleManagedGitEffects } from './helpers/managed-brain.ts';+import { auditDoor, expectDoorTarget, headCommit, strictSource, summarizeAudit, type DoorAudit } from './helpers/strict-door-audit.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const setup = ({ root }: { root: string }) => { writeFileSync(join(root, '.gitignore'), '\n'); durableGitRepo(root, ['.gitignore']); };+const put = (ctx: OperationContext, slug: string, content: string) => submitPageMutation(ctx, { operation: 'put_page', params: { slug, request_id: randomUUID(), content } });+const NO_GAP = { database_ahead: 0, worktree_only: 0, undeclared_database_only: 0 };++/** What each batch commit put in Git for one probe per path: the intermediate states history keeps after the batch. */+const commitProbe = async (root: string, audit: DoorAudit, probe: (blob: string) => unknown) =>+ Promise.all(audit.commits.flatMap(commit => commit.paths.map(async path => ({ sha: commit.sha.slice(0, 8), path, probe: probe(await gitAsync(root, 'show', `${commit.sha}:${path}`).catch(() => '')) }))));++/** Three concept groups: one T2 (five atoms, LLM narrative) and two T3 (two atoms each, deterministic narrative). */+const GROUPS: Record<string, number> = { 'flywheels-example': 5, 'moats-example': 2, 'network-effects-example': 2 };+const CONCEPTS = Object.keys(GROUPS).map(stem => `concepts/${stem}`);+const ATOMS = Object.entries(GROUPS).flatMap(([stem, n]) => Array.from({ length: n }, (_, i) => ({ stem, slug: `atoms/2026-10-01/${stem}-${i + 1}`, i })));+const atomPage = (stem: string, i: number) => `---\ntype: atom\ntitle: ${stem} ${i + 1}\nvisibility: world\nconcepts: [${stem}]\n---\n\nAtom ${i + 1} about ${stem.replace(/-/g, ' ')}, from source-a.\n`;++/** The synthesis model stub (as test/cycle/extract-atoms-synthesize-concepts.test.ts stubs `_chat`); records each prompt's first line. */+const conceptChat = () => {+ const calls: string[] = [];+ const chat = async (o: ChatOpts): Promise<ChatResult> => {+ calls.push(String(o.messages?.[0]?.content ?? '').split('\n')[0]!);+ const text = 'Flywheels compound when each turn makes the next one cheaper, as the member atoms from source-a describe.';+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 500, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 },+ model: 'anthropic:claude-sonnet-4-6', providerId: 'anthropic' };+ };+ return { calls, chat };+};++async function seedAtoms(ctx: OperationContext) {+ for (const atom of ATOMS) await put(ctx, atom.slug, atomPage(atom.stem, atom.i));+}++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;++ describe(`[${backend}] G6: synthesize_concepts on a strict source writes only through the door`, () => {+ test('three new concepts: declared database-only, clean, no census gap, no commit under concepts/', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ await seedAtoms(ctx);+ await settleManagedGitEffects(engine);+ const baseline = await auditDoor(engine, root, { since: await headCommit(root), slugs: ATOMS.map(a => a.slug) });+ expect({ porcelain: baseline.porcelain, gaps: baseline.gaps }).toEqual({ porcelain: '', gaps: NO_GAP });+ expect(baseline.pages.map(page => [page.slug, page.row?.state])).toEqual(ATOMS.map(a => [a.slug, 'equal']));+ const since = await headCommit(root);+ const { calls, chat } = conceptChat();+ const result = await runPhaseSynthesizeConcepts(engine, { sourceId: 'default', brainDir: root, _chat: chat });+ expect(result.status).toBe('ok');+ expect(result.details?.concepts_written).toBe(3);+ expect(calls).toEqual(['Concept slug: flywheels-example']);+ for (const slug of CONCEPTS) {+ const page = await engine.getPage(slug, { sourceId: 'default' });+ expect({ slug, by: page?.frontmatter?.synthesized_by, visibility: page?.frontmatter?.visibility })+ .toEqual({ slug, by: 'synthesize_concepts-v0.41', visibility: 'world' });+ }+ await settleManagedGitEffects(engine);+ const audit = await auditDoor(engine, root, { since, slugs: CONCEPTS });+ console.log(summarizeAudit(`synthesize_concepts new ${backend}`, audit));+ // A never-filed concept is the declared derive-phase class (git-gap.ts declaredDatabaseOnly 'derive_folder'): no+ // file is its target, so the page half of expectDoorTarget does not apply; the tree, census and commits do.+ expect(audit.porcelain).toBe('');+ expect({ gaps: audit.gaps, sample: audit.gapSample }).toEqual({ gaps: NO_GAP, sample: [] });+ expect(audit.census.declared.derive_folder).toBeGreaterThanOrEqual(CONCEPTS.length);+ expect(audit.pages.map(page => ({ slug: page.slug, head: page.head, worktree: page.worktree }))).toEqual(CONCEPTS.map(slug => ({ slug, head: null, worktree: null })));+ expect(audit.commits.filter(commit => commit.paths.some(path => path.startsWith('concepts/')))).toEqual([]);+ }, { databaseUrl, setup }), 180_000);++ test('three file-backed concepts republished: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ await seedAtoms(ctx);+ for (const slug of CONCEPTS) {+ await put(ctx, slug, `---\ntype: concept\ntitle: ${slug.split('/')[1]}\nsynthesized_by: synthesize_concepts-v0.41\nsynthesis_mode: llm\nmember_hash: stale-example\nvisibility: world\n---\n\nAn older narrative from source-a.\n`);+ }+ await settleManagedGitEffects(engine);+ const seeded = [...ATOMS.map(a => a.slug), ...CONCEPTS];+ const baseline = await auditDoor(engine, root, { since: await headCommit(root), slugs: seeded });+ expect({ porcelain: baseline.porcelain, gaps: baseline.gaps }).toEqual({ porcelain: '', gaps: NO_GAP });+ expect(baseline.pages.map(page => [page.slug, page.row?.state])).toEqual(seeded.map(slug => [slug, 'equal']));+ const since = await headCommit(root);+ const { calls, chat } = conceptChat();+ const result = await runPhaseSynthesizeConcepts(engine, { sourceId: 'default', brainDir: root, _chat: chat });+ expect(result.status).toBe('ok');+ expect(result.details?.concepts_written).toBe(3);+ expect(calls).toEqual(['Concept slug: flywheels-example']);+ for (const slug of CONCEPTS) {+ const page = await engine.getPage(slug, { sourceId: 'default' });+ expect({ slug, stale: page?.frontmatter?.member_hash === 'stale-example', visibility: page?.frontmatter?.visibility, old: page?.compiled_truth.includes('An older narrative') })+ .toEqual({ slug, stale: false, visibility: 'world', old: false });+ }+ await settleManagedGitEffects(engine);+ const audit = await auditDoor(engine, root, { since, slugs: CONCEPTS });+ console.log(summarizeAudit(`synthesize_concepts republish ${backend}`, audit));+ console.log(`[g6-measure] synthesize_concepts republish commits ${backend}: ${JSON.stringify(await commitProbe(root, audit, blob => /^visibility: (\w+)/m.exec(blob)?.[1] ?? null))}`);+ expectDoorTarget(audit, engine.kind);+ }, { databaseUrl, setup }), 180_000);+ });++ describe(`[${backend}] G6: synthesize postprocess (managed quote-verify repair) on a strict source writes only through the door`, () => {+ beforeAll(() => configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} }));+ afterAll(() => { __setChatTransportForTests(null); resetGateway(); });++ test('three child-written reflections repaired and stamped: at HEAD, clean, no census gap, one commit per group', () => managedBrain(async ({ engine, ctx, root }) => {+ await strictSource(engine);+ await put(ctx, 'people/example', '---\ntitle: Example\ntype: note\n---\nExample evidence.\n');+ await settleManagedGitEffects(engine);+ const inputs = join(root, '..', 'inputs'); mkdirSync(inputs);+ const inputFile = join(inputs, '2026-09-20-session.txt');+ const quote = 'we charge for durability because reliable memories should survive every tool';+ writeFileSync(inputFile, `User: ${quote}.\n${'Assistant: Discuss the long term roadmap.\n'.repeat(15)}`);+ for (const [key, value] of Object.entries({+ 'dream.synthesize.enabled': 'true', 'dream.synthesize.cooldown_hours': '0',+ 'dream.synthesize.min_chars': '100', 'dream.synthesize.link_manifest': 'false',+ 'dream.synthesize.mode': 'oneshot', 'dream.synthesize.quote_verify': 'true',+ 'models.dream.synthesize': 'anthropic:claude-sonnet-4-6', 'models.dream.triage': 'anthropic:claude-sonnet-4-6',+ })) await engine.setConfig(key, value);+ // The provider stub of test/helpers/managed-synthesis-fixture.ts: triage scores the transcript 0.9 and the oneshot+ // child writes three reflections, each with an invented quotation quote-verify must strip.+ let calls = 0;+ __setChatTransportForTests(async opts => {+ calls++;+ const hash = /hash suffix \(USE THIS in slugs\): ([a-z0-9-]+)/i.exec(String(opts.messages?.[0]?.content ?? ''))?.[1] ?? 'missing';+ const text = (opts.system ?? '').startsWith('You triage a conversation transcript')+ ? JSON.stringify({ score: 0.9, content_type: 'reflection', segments: [{ quote, note: 'evidence' }], entities: [], reasons: ['durable insight'] })+ : JSON.stringify({ pages: Array.from({ length: 3 }, (_, i) => ({+ slug: `wiki/personal/reflections/session${i ? `-${i}` : ''}-${hash}`, title: `Session ${i}`, type: 'note',+ body: `A memory strategy with [[people/example]]. Evidence item ${i}. Allegedly: "an entirely invented quotation that should lose its marks".`,+ })), skipped: false });+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',+ usage: { input_tokens: 100, output_tokens: 100, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: opts.model!, providerId: 'anthropic' };+ });+ const baseline = await auditDoor(engine, root, { since: await headCommit(root), slugs: ['people/example'] });+ expect({ porcelain: baseline.porcelain, gaps: baseline.gaps }).toEqual({ porcelain: '', gaps: NO_GAP });+ const since = await headCommit(root);+ const result = await withEnv({ ANTHROPIC_API_KEY: 'sk-test-synthesis' }, () =>+ runPhaseSynthesize(engine, { brainDir: root, sourceId: 'default', dryRun: false, inputFile, date: '2026-09-20' }));+ expect(result.status).toBe('ok');+ expect(calls).toBe(2);+ const outputs = (result.details.written_slugs as string[]).slice().sort();+ expect(outputs).toHaveLength(3);+ expect((result.details.synthesis as { quote_verify: { pages_repaired: number } }).quote_verify.pages_repaired).toBe(3);+ for (const slug of outputs) {+ const page = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.page;+ expect({ slug, stamped: page.frontmatter.dream_generated, invented: page.compiled_truth.includes('"an entirely invented') })+ .toEqual({ slug, stamped: true, invented: false });+ }+ await settleManagedGitEffects(engine);+ const audit = await auditDoor(engine, root, { since, slugs: outputs });+ console.log(summarizeAudit(`synthesize postprocess ${backend}`, audit));+ console.log(`[g6-measure] synthesize postprocess commits ${backend}: ${JSON.stringify(await commitProbe(root, audit, blob => ({ invented_quote_in_body: blob.slice(blob.indexOf('\n---\n', 3) + 5).includes('"an entirely invented'), dream_generated: /^dream_generated: true/m.test(blob) })))}`);+ console.log(summarizeAudit(`synthesize summary ${backend}`, await auditDoor(engine, root, { since, slugs: [String(result.details.summary_slug)] })));+ expectDoorTarget(audit, engine.kind);+ }, { databaseUrl, setup }), 180_000);+ });+}diff --git a/test/helpers/strict-door-audit.ts b/test/helpers/strict-door-audit.tsnew file mode 100644index 0000000000..415063b92b--- /dev/null+++ b/test/helpers/strict-door-audit.ts@@ -0,0 +1,122 @@+/**+ * G6 (git-canonical memory, docs/designs/GIT_CANONICAL_MEMORY.md): what a writer's batch left behind on a strict source+ * (`sources.config.canonical = "git"`). The door (src/core/persistence/git-door.ts) commits each published file before+ * its row, so after a batch every page the writer touched is at HEAD with the bytes its row holds, the tree is clean,+ * the git-gap census (`gbrain sources git-gap`) reports no gap, and the batch made at most one commit per publication+ * group. Read-only: plumbing reads of the checkout and the census.+ */+import { expect } from 'bun:test';+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { readExportPage, readExportWithdrawals } from '../../src/core/export-snapshot.ts';+import { compareInlineExportFile, type ExportFileComparison } from '../../src/core/persistence/git-gap.ts';+import { censusGitGap, type GitGapCensus } from '../../src/commands/sources-git-gap.ts';+import { PAGE_BATCH_GROUP_MAX } from '../../src/core/persistence/group-publish.ts';+import { gitAsync } from './git-publication.ts';++/** Flags `sourceId` strict (git-canonical), exactly as test/git-door-strict-gbra133.test.ts does. */+export const strictSource = (engine: BrainEngine, sourceId = 'default') =>+ engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id=$1`, [sourceId]);++export const headCommit = async (root: string) => (await gitAsync(root, 'rev-parse', 'HEAD')).trim();++/** The census states that mean the database holds page content Git does not. */+export const GAP_STATES = ['database_ahead', 'worktree_only', 'undeclared_database_only'] as const;++export interface PageAudit {+ slug: string;+ path: string;+ /** The HEAD blob of the page's file, or null when HEAD has none. */+ head: string | null;+ /** The working-tree bytes, or null when the file is absent. */+ worktree: string | null;+ /** The live row against the HEAD blob under the census equality contract (compareInlineExportFile); null without a row or a HEAD blob. */+ row: ExportFileComparison | null;+ /** Commits since the batch started that touch this page's file. */+ commits: number;+}++export interface DoorAudit {+ /** Commits made since `since`, oldest first, each with the paths it touched. */+ commits: Array<{ sha: string; paths: string[] }>;+ /** `git status --porcelain` (untracked files included). */+ porcelain: string;+ census: GitGapCensus;+ gaps: Record<typeof GAP_STATES[number], number>;+ /** Census sample entries in a gap state. */+ gapSample: GitGapCensus['sample'];+ pages: PageAudit[];+}++/**+ * Audits the checkout and the census after a writer's batch. `slugs` are the live pages the batch wrote (their files+ * are `<slug>.md` under `root`); `since` is HEAD before the batch.+ */+export async function auditDoor(engine: BrainEngine, root: string, opts: { since: string; slugs: string[]; sourceId?: string }): Promise<DoorAudit> {+ const sourceId = opts.sourceId ?? 'default';+ const log = (await gitAsync(root, 'log', '--reverse', '--format=@%H', '--name-only', `${opts.since}..HEAD`)).split('\n');+ const commits: DoorAudit['commits'] = [];+ for (const line of log) {+ if (line.startsWith('@')) commits.push({ sha: line.slice(1), paths: [] });+ else if (line.trim()) commits.at(-1)!.paths.push(line.trim());+ }+ const porcelain = await gitAsync(root, 'status', '--porcelain', '--untracked-files=all');+ const census = await censusGitGap(engine, sourceId, { sample: 1000 });+ const gaps = Object.fromEntries(GAP_STATES.map(state => [state, census.states[state]])) as DoorAudit['gaps'];+ const gapSample = census.sample.filter(entry => (GAP_STATES as readonly string[]).includes(entry.state));+ const withdrawals = await engine.transaction(tx => readExportWithdrawals(tx, sourceId));+ const pages: PageAudit[] = [];+ for (const slug of opts.slugs) {+ const path = `${slug}.md`;+ const head = await gitAsync(root, 'show', `HEAD:${path}`).catch(() => null);+ const worktree = existsSync(join(root, path)) ? readFileSync(join(root, path), 'utf8') : null;+ const [key] = await engine.executeRaw<{ id: string; source_id: string; slug: string }>(+ 'SELECT id::text AS id, source_id, slug FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);+ const row = key && head !== null ? compareInlineExportFile(Buffer.from(head), path, await engine.transaction(tx => readExportPage(tx, key, withdrawals))) : null;+ pages.push({ slug, path, head, worktree, row, commits: commits.filter(commit => commit.paths.includes(path)).length });+ }+ return { commits, porcelain, census, gaps, gapSample, pages };+}++/** A compact measurement line for a report. */+export function summarizeAudit(label: string, audit: DoorAudit): string {+ const batchPaths = new Set(audit.pages.map(page => page.path));+ return `[g6-measure] ${label}: ${JSON.stringify({+ commits: audit.commits.length,+ commits_touching_batch: audit.commits.filter(commit => commit.paths.some(path => batchPaths.has(path))).length,+ paths_per_commit: audit.commits.map(commit => commit.paths.length),+ clean: audit.porcelain === '',+ porcelain: audit.porcelain.split('\n').filter(Boolean).slice(0, 10),+ census: Object.fromEntries(Object.entries(audit.census.states).filter(([, n]) => n > 0)),+ gap_sample: audit.gapSample.slice(0, 10).map(entry => ({ slug: entry.slug, state: entry.state, fields: entry.fields, worktree: entry.worktree })),+ rows_without_git_home: audit.census.rows_without_git_home,+ pages: audit.pages.map(page => ({ slug: page.slug, at_head: page.head !== null, row_vs_head: page.row,+ head_equals_worktree: page.head === page.worktree, commits: page.commits })),+ })}`;+}++/**+ * The G6 target for one writer batch on a strict source:+ * - every page is at HEAD, the working tree holds the same bytes, and the row equals the HEAD blob (the census+ * equality contract, compareInlineExportFile: the row holds no content HEAD does not);+ * - `git status --porcelain` is empty;+ * - the census has no page in database_ahead, worktree_only or undeclared_database_only;+ * - the batch made at most one commit per publication group, and no page was committed twice. One writer batch is+ * one group of up to PAGE_BATCH_GROUP_MAX pages on Postgres (group-publish.ts, as put_pages). PGLite's consumer+ * groups only managed import batches (consumer.ts executeOrGroup), so there each page is its own publication, as+ * test/git-door-strict-gbra133.test.ts accepts for put_pages.+ */+export function expectDoorTarget(audit: DoorAudit, backend: BrainEngine['kind']): void {+ for (const page of audit.pages) {+ expect({ slug: page.slug, atHead: page.head !== null }).toEqual({ slug: page.slug, atHead: true });+ expect({ slug: page.slug, worktree: page.worktree }).toEqual({ slug: page.slug, worktree: page.head });+ expect({ slug: page.slug, row: page.row }).toEqual({ slug: page.slug, row: { state: 'equal' } });+ }+ expect(audit.porcelain).toBe('');+ expect({ gaps: audit.gaps, sample: audit.gapSample }).toEqual({ gaps: { database_ahead: 0, worktree_only: 0, undeclared_database_only: 0 }, sample: [] });+ const groups = backend === 'postgres' ? Math.max(1, Math.ceil(audit.pages.length / PAGE_BATCH_GROUP_MAX)) : audit.pages.length;+ const batchPaths = new Set(audit.pages.map(page => page.path));+ expect(audit.commits.filter(commit => commit.paths.some(path => batchPaths.has(path))).length).toBeLessThanOrEqual(groups);+ expect(audit.pages.filter(page => page.commits > 1).map(page => ({ slug: page.slug, commits: page.commits }))).toEqual([]);+}diff --git a/test/helpers/strict-door-census.ts b/test/helpers/strict-door-census.tsnew file mode 100644index 0000000000..80cf587867--- /dev/null+++ b/test/helpers/strict-door-census.ts@@ -0,0 +1,83 @@+/**+ * G6 measurement: what a writer's batch leaves on a strict (canonical: git) source. Git is the parent there, so after+ * a batch every page the batch wrote must be committed at HEAD with the exact bytes the door published, the working tree+ * must be clean, the git-gap census must report no gap, and the batch may make at most one door commit per publication+ * group (journal.ts publicationGroupKey; an ungrouped write is a group of one).+ */+import { readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { censusGitGap, type GitGapCensus } from '../../src/commands/sources-git-gap.ts';+import { publicationGroupKey } from '../../src/core/persistence/journal.ts';+import { durableGitRepo, git } from './git-publication.ts';++export const strictSource = (engine: BrainEngine, sourceId = 'default') =>+ engine.executeRaw(`UPDATE sources SET config = config || '{"canonical":"git"}'::jsonb WHERE id=$1`, [sourceId]);++/** A Git checkout at `root` with one initial commit, so the door has a HEAD to commit on. */+export function initStrictCheckout(root: string): void {+ writeFileSync(join(root, '.gitignore'), '\n');+ durableGitRepo(root, ['.gitignore']);+}++export const head = (root: string) => git(root, 'rev-parse', 'HEAD').trim();++export interface BatchMeasure {+ /** Commits on HEAD made since `base`, oldest first, each with the files it touched. */+ commits: { sha: string; files: string[] }[];+ /** The publication groups of the batch's committed requests: group key, or the request id for an ungrouped write. */+ groups: number;+ /** Distinct `outcome.persistence.git_commit` stamps on the batch's receipts (null: a receipt with no door commit). */+ receiptCommits: (string | null)[];+ porcelain: string;+ census: GitGapCensus;+ /** Census page states other than equal and declared_database_only, with their counts. */+ gaps: Record<string, number>;+ /** Pages of the batch with no live row, no file at HEAD, or a HEAD blob that differs from the working-tree file. */+ notAtHead: { slug: string; path: string; reason: string }[];+}++/** Measures the batch that wrote `slugs` to `sourceId`, whose checkout is `root`, against the commit `base` taken before it. */+export async function measureBatch(engine: BrainEngine, sourceId: string, root: string, base: string, slugs: string[]): Promise<BatchMeasure> {+ const commits = git(root, 'rev-list', '--reverse', `${base}..HEAD`).split('\n').filter(Boolean)+ .map(sha => ({ sha, files: git(root, 'show', '--name-only', '--format=', sha).split('\n').filter(Boolean) }));+ const requests = await engine.executeRaw<{ request_id: string; operation: string; intent: Record<string, unknown> | null; outcome: Record<string, any> | null }>(+ "SELECT request_id, operation, intent, outcome FROM persistence_requests WHERE source_id=$1 AND slug = ANY($2::text[]) AND state='committed'", [sourceId, slugs]);+ const groups = new Set(requests.map(row => publicationGroupKey(row as never) ?? row.request_id));+ const receiptCommits = [...new Set(requests.map(row => (row.outcome?.persistence?.git_commit as string | undefined) ?? null))];+ const porcelain = git(root, 'status', '--porcelain', '--untracked-files=all');+ const census = await censusGitGap(engine, sourceId, { sample: 100 });+ const gaps = Object.fromEntries(Object.entries(census.states).filter(([state, n]) => n > 0 && state !== 'equal' && state !== 'declared_database_only'));+ const rows = await engine.executeRaw<{ slug: string; source_path: string | null }>(+ 'SELECT slug, source_path FROM pages WHERE source_id=$1 AND slug = ANY($2::text[]) AND deleted_at IS NULL', [sourceId, slugs]);+ const notAtHead: BatchMeasure['notAtHead'] = [];+ for (const slug of slugs) {+ const row = rows.find(r => r.slug === slug);+ if (!row) { notAtHead.push({ slug, path: '', reason: 'no live row' }); continue; }+ const path = row.source_path ?? `${slug}.md`;+ let committed: string | null = null;+ try { committed = git(root, 'show', `HEAD:${path}`); } catch { committed = null; }+ let disk: string | null = null;+ try { disk = readFileSync(join(root, path), 'utf8'); } catch { disk = null; }+ if (committed === null) notAtHead.push({ slug, path, reason: disk === null ? 'no file at HEAD or on disk' : 'file not at HEAD' });+ else if (disk !== committed) notAtHead.push({ slug, path, reason: 'working tree differs from HEAD' });+ }+ return { commits, groups: groups.size, receiptCommits, porcelain, census, gaps, notAtHead };+}++/** One line per measurement, printed by each test for the report. */+export function describeMeasure(writer: string, m: BatchMeasure): string {+ return `[G6 ${writer}] commits=${m.commits.length} ${JSON.stringify(m.commits.map(c => c.files))} groups=${m.groups} receipt_commits=${JSON.stringify(m.receiptCommits)}`+ + ` porcelain=${JSON.stringify(m.porcelain)} gaps=${JSON.stringify(m.gaps)} worktree=${JSON.stringify(m.census.worktree)}`+ + ` not_at_head=${JSON.stringify(m.notAtHead)} sample=${JSON.stringify(m.census.sample.filter(s => s.state !== 'equal'))}`;+}++/** The target every G6 writer is held to on a strict source. */+export function expectDoorOnly(m: BatchMeasure, expect: (value: unknown) => any): void {+ expect(m.notAtHead).toEqual([]);+ expect(m.porcelain).toBe('');+ expect(m.gaps).toEqual({});+ expect(m.receiptCommits).not.toContain(null);+ expect(m.commits.length).toBeGreaterThan(0);+ expect(m.commits.length).toBeLessThanOrEqual(m.groups);+}