Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(dream): stamp the capturing seat on synthesized pages (#4618)
garrytane19c78d9432f
diff --git a/src/core/cycle/dream-provenance.ts b/src/core/cycle/dream-provenance.tsindex 4c08926254..abfd51d763 100644--- a/src/core/cycle/dream-provenance.ts+++ b/src/core/cycle/dream-provenance.ts@@ -5,17 +5,17 @@ import { throwIfAborted } from '../abort-check.ts';* Dream-provenance DB stamp (#2569): marks pages a dream child wrote with* `dream_generated` and a stable first cycle date. Shared by synthesize and* patterns (#5733); a page that existed before the child's first write to it- * is not stamped.+ * is not stamped. `seat` (#4618) credits the capturing agent seat.*/export async function stampDreamProvenance(engine: BrainEngine,- refs: Array<{ slug: string; source_id: string; raw_source?: string; raw_trace_exempt_reason?: string; first_write_at?: Date }>,+ refs: Array<{ slug: string; source_id: string; raw_source?: string; seat?: string; raw_trace_exempt_reason?: string; first_write_at?: Date }>,cycleDate: string,signal?: AbortSignal,): Promise<void> {if (refs.length === 0) return;const { executeRawJsonb } = await import('../sql-query.ts');- for (const { slug, source_id, raw_source, raw_trace_exempt_reason, first_write_at } of refs) {+ for (const { slug, source_id, raw_source, seat, raw_trace_exempt_reason, first_write_at } of refs) {// #4077: per-row abort check — the per-row try below is only for stamp// failures and must not swallow the cancellation unwind.throwIfAborted(signal, '[dream] synthesize provenance');@@ -45,6 +45,7 @@ export async function stampDreamProvenance([{dream_generated: true,...(raw_source ? { raw_source } : {}),+ ...(seat ? { seat } : {}),...(raw_trace_exempt_reason ? { raw_trace_exempt: true, raw_trace_exempt_reason } : {}),}],);diff --git a/src/core/cycle/patterns.ts b/src/core/cycle/patterns.tsindex eb524f7edb..cc5ed84bcf 100644--- a/src/core/cycle/patterns.ts+++ b/src/core/cycle/patterns.ts@@ -276,7 +276,7 @@ export async function runPhasePatterns(};const submitOpts: Partial<MinionJobInput> = {...(maintenance ? { idempotency_key: `dream:patterns:${digest({ source: maintenance.writer.sourceIncarnation,- authority: maintenance.writer, reflections, model: config.model, output: config.outputSlugPrefix })}` } : {}),+ authority: maintenance.writer, reflections: withoutSeats(reflections), model: config.model, output: config.outputSlugPrefix })}` } : {}),max_stalled: 3,timeout_ms: budgets.timeoutMs,queue: childQueueName,@@ -361,7 +361,7 @@ export async function runPhasePatterns(throwIfAborted(opts.signal, '[dream] patterns output');const writtenRefs = await collectChildPutPageSlugs(engine, [job.id], cycleSourceId);- await stampPatternOutputs(engine, maintenance, writtenRefs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, opts.signal);+ await stampPatternOutputs(engine, maintenance, writtenRefs.filter(ref => ref.slug.startsWith(`${config.outputSlugPrefix}/`)), cycleDate, config.sourceSlugPrefix, sharedSeat(reflections), opts.signal);const reverseWriteCount = maintenance ? await verifyMaintenanceOutputs(engine, maintenance, writtenRefs): await reverseWriteRefs(engine, opts.brainDir, writtenRefs, cycleSourceId, opts.signal);@@ -537,6 +537,20 @@ interface ReflectionRef {title: string;excerpt: string;updatedAt: Date;+ /** #4618: the seat the reflection was synthesized from, when stamped. */+ seat: string | null;+}++/** The submission key's reflection identity, unchanged by #4618's seat field+ * (a seat must never re-key, and so re-pay, a retained patterns child). */+function withoutSeats(reflections: ReflectionRef[]): Array<Omit<ReflectionRef, 'seat'>> {+ return reflections.map(({ slug, title, excerpt, updatedAt }) => ({ slug, title, excerpt, updatedAt }));+}++/** #4618: a pattern credits a seat only when every input reflection shares one. */+function sharedSeat(reflections: ReflectionRef[]): string | undefined {+ const seats = new Set(reflections.map(r => r.seat));+ return seats.size === 1 ? (reflections[0]?.seat ?? undefined) : undefined;}async function gatherReflections(@@ -549,9 +563,9 @@ async function gatherReflections(// Reflections live under the configured source slug prefix (bound as a// parameter; see PatternsConfig.sourceSlugPrefix / dream.patterns.source_slug_prefix).const rows = await engine.executeRaw<{- slug: string; title: string | null; compiled_truth: string | null; updated_at: string | Date;+ slug: string; title: string | null; compiled_truth: string | null; updated_at: string | Date; seat: string | null;}>(- `SELECT slug, title, compiled_truth, updated_at+ `SELECT slug, title, compiled_truth, updated_at, frontmatter->>'seat' AS seatFROM pagesWHERE slug LIKE $2AND source_id = $3 AND deleted_at IS NULL AND COALESCE(frontmatter->>'visibility','') <> 'private'@@ -571,6 +585,7 @@ async function gatherReflections(// into the minion job's JSONB payload. Use the shared safe truncator so a// reflection containing emoji cannot abort the entire patterns phase.excerpt: truncateUtf8(r.compiled_truth ?? '', 600),+ seat: r.seat ?? null,}));}@@ -619,12 +634,12 @@ When done, briefly list the pattern slugs you wrote/updated in your final messag* stamped raw-trace exempt (doctor raw_provenance) on every run that writes it.*/async function stampPatternOutputs(engine: BrainEngine, maintenance: MaintenanceAuthority | null,- refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, signal?: AbortSignal): Promise<void> {+ refs: Array<{ slug: string; source_id: string }>, cycleDate: string, sourceSlugPrefix: string, seat: string | undefined, signal?: AbortSignal): Promise<void> {const reason = `derived from reflections under ${sourceSlugPrefix}/; raw traces live on the cited reflection pages`;- if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason })), cycleDate, signal);+ if (!maintenance) return stampDreamProvenance(engine, refs.map(ref => ({ ...ref, raw_trace_exempt_reason: reason, ...(seat ? { seat } : {}) })), cycleDate, signal);for (const ref of refs) {throwIfAborted(signal, '[dream] patterns provenance');- await stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason);+ await stampMaintenancePage(engine, maintenance, ref.slug, cycleDate, undefined, reason, seat);}}diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.tsindex 4e6a628d36..98e1a926f7 100644--- a/src/core/cycle/synthesize-postprocess.ts+++ b/src/core/cycle/synthesize-postprocess.ts@@ -13,7 +13,7 @@ import type { PhaseResult } from '../cycle.ts';import type { DiscoveredTranscript } from './transcript-discovery.ts';import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPrior, verifyDreamPage, type GroundedSource, type GroundingPass } from './synthesize-verify.ts';-interface OutputRef { slug: string; source_id: string; raw_source?: string; first_write_at?: Date; }+interface OutputRef { slug: string; source_id: string; raw_source?: string; seat?: string; first_write_at?: Date; }interface RetainedOutput { job_id: number | bigint; job_key: string; request: WriteRequest; }export async function postprocessManagedSynthesis(@@ -76,7 +76,7 @@ export async function postprocessManagedSynthesis(const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || opts.cycleDate;const since = ref.first_write_at ?? opts.sinceByTranscript.get(transcript.filePath);let page = isDreamOwnedPage(snapshot.page, since) ? { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,- dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, raw_source: path } } : snapshot.page;+ dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, raw_source: path, ...(transcript.seat ? { seat: transcript.seat } : {}) } } : snapshot.page;if (opts.quoteVerify) {const prior = since ? await resolveVerifyPrior(engine, snapshot.page, ref.source_id, since) : null;if (prior === 'unchanged') stats.skipped_unchanged++;diff --git a/src/core/cycle/synthesize.ts b/src/core/cycle/synthesize.tsindex dc684991d2..2d01adf66c 100644--- a/src/core/cycle/synthesize.ts+++ b/src/core/cycle/synthesize.ts@@ -82,7 +82,7 @@ import { stampDreamProvenance } from './dream-provenance.ts';export { runSubagentsInline, runDrainRenewalTick };import { loadAllowedSlugPrefixes } from './filing-rules.ts';export { loadAllowedSlugPrefixes };-import { discoverTranscripts, DEFAULT_EXCLUDE_PATTERNS, type DiscoveredTranscript, conversationPagesOptedIn, conversationPagesNotConsumed, withConversationPages } from './transcript-discovery.ts';+import { discoverTranscripts, DEFAULT_EXCLUDE_PATTERNS, type DiscoveredTranscript, conversationPagesOptedIn, conversationPagesNotConsumed, withConversationPages, withTranscriptSeats } from './transcript-discovery.ts';import { loadStorageConfig, isDbOnly } from '../storage-config.ts';import { serializeMarkdown, serializePageToMarkdown } from '../markdown.ts';import type { Page, PageType } from '../types.ts';@@ -1135,7 +1135,7 @@ async function runPhaseSynthesizeInner(// rescued/passed transcript whose child declined to write (task D) is// distinguishable from a triage miss in the phase telemetry.const jobsWithPages = new Set<number>();- let writtenRefs = await collectChildPutPageSlugs(engine, childIds, chunkInfo, cycleSourceId, jobRawSource, jobsWithPages);+ let writtenRefs = withTranscriptSeats(await collectChildPutPageSlugs(engine, childIds, chunkInfo, cycleSourceId, jobRawSource, jobsWithPages), worthProcessing);let finalizedRefs = writtenRefs;// Grounding gate: verify every page the children wrote (whole page whendiff --git a/src/core/cycle/transcript-discovery.ts b/src/core/cycle/transcript-discovery.tsindex 463944f1b2..e6690368fd 100644--- a/src/core/cycle/transcript-discovery.ts+++ b/src/core/cycle/transcript-discovery.ts@@ -12,11 +12,12 @@*/import { readFileSync, readdirSync, statSync } from 'node:fs';-import { join, basename, sep } from 'node:path';+import { join, basename, dirname, sep } from 'node:path';import { createHash } from 'node:crypto';import { pruneDir } from '../sync.ts';import { realpathOrResolve, resolvedPrefixContained } from '../path-confine.ts';import { corpusFileSessionId } from '../context/corpus-segments.ts';+import { readSeatSidecar } from '../context/seat.ts';import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';import type { BrainEngine } from '../engine.ts';import type { PhaseResult } from '../cycle.ts';@@ -32,6 +33,8 @@ export interface DiscoveredTranscript {basename: string;/** Inferred date if the basename matches `YYYY-MM-DD...` (or null). */inferredDate: string | null;+ /** #4618: the capturing seat from the session's `.seat.json` sidecar, when one exists. */+ seat?: string;}export interface DiscoverOpts {@@ -336,12 +339,14 @@ export function discoverTranscripts(opts: DiscoverOpts): DiscoveredTranscript[]continue;}+ const seat = transcriptSeat(filePath);results.push({filePath,contentHash: hashContent(content),content,basename: baseName,inferredDate,+ ...(seat ? { seat } : {}),});}}@@ -393,15 +398,41 @@ export function readSingleTranscript(const ext = filePath.endsWith('.md') ? '.md' : '.txt';const baseName = basename(filePath, ext);const dateMatch = DATE_RE.exec(baseName);+ const seat = transcriptSeat(filePath);return {filePath,contentHash: hashContent(content),content,basename: baseName,inferredDate: dateMatch ? dateMatch[1] : null,+ ...(seat ? { seat } : {}),};}+/**+ * #4618: credit each ref to the seat of the transcript it was synthesized+ * from (the seat sidecar discovery read). The synthesis idempotency key never+ * includes the seat, so a sidecar added later triggers no re-synthesis.+ */+export function withTranscriptSeats<T extends { raw_source?: string }>(refs: T[], transcripts: DiscoveredTranscript[]): Array<T & { seat?: string }> {+ const seats = new Map(transcripts.flatMap(t => (t.seat ? [[t.filePath, t.seat] as const] : [])));+ return refs.map(ref => {+ const seat = ref.raw_source ? seats.get(ref.raw_source) : undefined;+ return seat ? { ...ref, seat } : ref;+ });+}++/**+ * #4618: the seat recorded for a transcript's session. A `.txt` corpus file+ * (session-end file, checkpoint segment or writeback turn) shares its+ * session's `<sessionId>.seat.json`; any other file uses its own basename.+ */+function transcriptSeat(filePath: string): string | undefined {+ const name = basename(filePath);+ const key = name.endsWith('.txt') ? corpusFileSessionId(name) : name.replace(/\.md$/, '');+ return readSeatSidecar(dirname(filePath), key)?.seat;+}+// ── #4419: imported type: conversation pages (database discovery) ───────/** Dream's synthesize phase discovers imported `type: conversation`diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex e1d7937c05..557bd29765 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -138,13 +138,14 @@ export async function submitDatabaseMaintenanceIntent(engine: BrainEngine, autho}export async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,- cycleDate: string, rawSource?: string, rawTraceExemptReason?: string): Promise<void> {+ cycleDate: string, rawSource?: string, rawTraceExemptReason?: string, seat?: string): Promise<void> {const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId });if (!snapshot) throw new OperationError('page_not_found', 'A maintenance output page disappeared.');const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || cycleDate;const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, ...(rawSource ? { raw_source: rawSource } : {}),- ...(rawTraceExemptReason ? { raw_trace_exempt: true, raw_trace_exempt_reason: rawTraceExemptReason } : {}) } };+ ...(rawTraceExemptReason ? { raw_trace_exempt: true, raw_trace_exempt_reason: rawTraceExemptReason } : {}),+ ...(seat ? { seat } : {}) } };await publishMaintenancePage(engine, authority, slug, serializePageToMarkdown(page, snapshot.tags), { expectedRevision: snapshot.revision });}diff --git a/test/e2e/session-seat-synthesize.test.ts b/test/e2e/session-seat-synthesize.test.tsnew file mode 100644index 0000000000..63d74618d7--- /dev/null+++ b/test/e2e/session-seat-synthesize.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../session-seat-synthesize.test.ts'));diff --git a/test/session-seat-synthesize.test.ts b/test/session-seat-synthesize.test.tsnew file mode 100644index 0000000000..853ef917d6--- /dev/null+++ b/test/session-seat-synthesize.test.ts@@ -0,0 +1,190 @@+/**+ * #4618 seat identity in dream output: synthesize credits each page to the+ * seat recorded in its transcript's `.seat.json` sidecar, on the managed+ * (maintenance publish) and unmanaged (provenance stamp) paths; patterns+ * credits a seat only when every input reflection shares one.+ *+ * Authoring gate: protects the user-visible `seat` frontmatter on synthesized+ * pages (the household case: two seats, one brain). A regression that drops+ * the stamp on either write path, credits the wrong transcript's seat, stamps+ * a seat without a sidecar, or keys synthesis on the seat (a paid re-run when+ * a sidecar appears later) fails here. Existing synthesis tests never write a+ * sidecar. No production seam: the chat transport stub is the existing one.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runPhaseSynthesize } from '../src/core/cycle/synthesize.ts';+import { runPhasePatterns } from '../src/core/cycle/patterns.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { __setMaintenanceWriteWaitForTests } from '../src/core/persistence/maintenance-wait.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { parseMarkdown } from '../src/core/markdown.ts';+import { configureGateway, resetGateway, __setChatTransportForTests } from '../src/core/ai/gateway.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { withEnv } from './helpers/with-env.ts';+import { testBackends } from './helpers/test-backends.ts';++const backends = testBackends();+const engines: BrainEngine[] = [];+let dataDir: string;+let closePostgres: (() => Promise<void>) | undefined;+beforeAll(async () => {+ __setMaintenanceWriteWaitForTests(5_000);+ dataDir = mkdtempSync(join(tmpdir(), 'gbrain-seat-synth-db-'));+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });+ if (backends.includes('pglite')) {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir });+ await engine.initSchema();+ engines.push(engine);+ }+ if (backends.includes('postgres')) {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engines.push(pg.engine);+ closePostgres = pg.close;+ }+}, 120_000);+afterAll(async () => {+ __setMaintenanceWriteWaitForTests(null);+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ resetGateway();+ rmSync(dataDir, { recursive: true, force: true });+});++const quote = 'we charge for durability because reliable memories should survive every tool';+const usage = { input_tokens: 100, output_tokens: 100, cache_read_tokens: 0, cache_creation_tokens: 0 };++interface Fixture { engine: BrainEngine; sourceId: string; root: string; corpus: string; calls: () => number }++async function fixture(managed: boolean, run: (f: Fixture) => Promise<void>) {+ for (const engine of engines) {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-seat-synth-'));+ const root = join(dir, 'brain');+ const corpus = join(dir, 'corpus');+ mkdirSync(root);+ mkdirSync(corpus);+ const sourceId = `seat-${randomUUID().slice(0, 8)}`;+ let calls = 0;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), ANTHROPIC_API_KEY: 'sk-test-seat' }, async () => {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.setConfig('sync.write_through', 'true');+ await claimWorktree(engine, sourceId, root);+ 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.session_corpus_dir': corpus,+ 'models.dream.synthesize': 'anthropic:claude-sonnet-4-6', 'models.dream.triage': 'anthropic:claude-sonnet-4-6',+ 'models.dream.patterns': 'anthropic:claude-sonnet-4-6', 'dream.patterns.enabled': 'true',+ })) await engine.setConfig(key, value);+ await submitPageMutation(pageCtx(engine, sourceId), { operation: 'put_page', params: {+ slug: 'people/example', content: '---\ntitle: Example\ntype: note\n---\nExample evidence.', request_id: randomUUID() } });+ if (managed) await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ __setChatTransportForTests(async opts => {+ calls++;+ const user = String(opts.messages?.[0]?.content ?? '');+ const hash = /hash suffix \(USE THIS in slugs\): ([a-z0-9-]+)/i.exec(user)?.[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: [{ slug: `wiki/personal/reflections/session-${hash}`, title: 'Session', type: 'note',+ body: 'A durable memory strategy with [[people/example]].' }], skipped: false });+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', usage, model: opts.model!, providerId: 'anthropic' };+ });+ await run({ engine, sourceId, root, corpus, calls: () => calls });+ });+ } finally {+ __setChatTransportForTests(null);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ rmSync(dir, { recursive: true, force: true });+ }+ }+}++const pageCtx = (engine: BrainEngine, sourceId: string) => ({ engine, sourceId, remote: false as const,+ config: { engine: engine.kind, embedding_disabled: true }, dryRun: false, logger: { info() {}, warn() {}, error() {} } });++function writeSession(corpus: string, sessionId: string, topic: string, seat?: string): string {+ const path = join(corpus, `${sessionId}.txt`);+ writeFileSync(path, `[user]\n${quote}. Today we covered ${topic}.\n\n${'[assistant]\nDiscuss the long term roadmap.\n\n'.repeat(15)}`);+ if (seat) {+ writeFileSync(join(corpus, `${sessionId}.seat.json`), JSON.stringify({+ version: 1, seat, seat_source: 'env', hook_lane: 'workspace', harness: 'claude-code', first_seen: '2026-09-20T00:00:00.000Z',+ }) + '\n', { mode: 0o600 });+ }+ return path;+}++/** Synthesized pages by the basename of the transcript each came from. */+async function pagesByTranscript(engine: BrainEngine, sourceId: string): Promise<Map<string, { slug: string; frontmatter: Record<string, unknown> }>> {+ const rows = await engine.executeRaw<{ slug: string; frontmatter: Record<string, unknown> }>(+ "SELECT slug, frontmatter FROM pages WHERE source_id=$1 AND slug LIKE 'wiki/personal/reflections/session-%'", [sourceId]);+ return new Map(rows.map(r => [basename(String(r.frontmatter.raw_source)), r]));+}++for (const managed of [true, false]) describe(`${managed ? 'managed' : 'unmanaged'} synthesis seat stamp (#4618)`, () => {+ test('7-9. two seats, one brain: each page credits its transcript\'s seat; no sidecar ⇒ no seat; a later sidecar re-synthesizes nothing', async () => {+ await fixture(managed, async ({ engine, sourceId, root, corpus, calls }) => {+ writeSession(corpus, 'sess-alice', 'the durable storage plan', 'alice-desk');+ writeSession(corpus, 'sess-bob', 'the household budget review', 'bob-desk');+ writeSession(corpus, 'sess-plain', 'the garden watering schedule');+ const opts = { brainDir: root, sourceId, dryRun: false };+ const first = await runPhaseSynthesize(engine, opts);+ expect(first.status).toBe('ok');+ const pages = await pagesByTranscript(engine, sourceId);+ expect([...pages.keys()].sort()).toEqual(['sess-alice.txt', 'sess-bob.txt', 'sess-plain.txt']);+ expect(pages.get('sess-alice.txt')!.frontmatter.seat).toBe('alice-desk');+ expect(pages.get('sess-bob.txt')!.frontmatter.seat).toBe('bob-desk');+ expect(pages.get('sess-plain.txt')!.frontmatter).not.toHaveProperty('seat');+ expect(pages.get('sess-alice.txt')!.frontmatter.dream_generated).toBe(true);+ const file = parseMarkdown(readFileSync(join(root, `${pages.get('sess-bob.txt')!.slug}.md`), 'utf8'));+ expect(file.frontmatter.seat).toBe('bob-desk');++ const spent = calls();+ const [{ n: jobs }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs');+ writeSession(corpus, 'sess-plain', 'the garden watering schedule', 'carol-desk');+ await disposePersistenceConsumer(engine);+ const replay = await runPhaseSynthesize(engine, opts);+ expect(replay.status).toBe('ok');+ expect(calls()).toBe(spent);+ const [{ n: jobsAfter }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs');+ expect(jobsAfter).toBe(jobs);+ expect((await pagesByTranscript(engine, sourceId)).get('sess-plain.txt')!.frontmatter).not.toHaveProperty('seat');+ });+ }, 120_000);++ test('patterns credit a seat only when every input reflection shares it', async () => {+ for (const seats of [['alice-desk', 'alice-desk', 'alice-desk'], ['alice-desk', 'bob-desk', 'alice-desk']]) {+ await fixture(managed, async ({ engine, sourceId, root }) => {+ await engine.setConfig('agent.use_gateway_loop', 'true');+ const ctx = pageCtx(engine, sourceId);+ for (const [i, seat] of seats.entries()) {+ await submitPageMutation(ctx, { operation: 'put_page', params: { slug: `wiki/personal/reflections/example-${i}`,+ content: `---\ntitle: Reflection ${i}\ntype: note\nseat: ${seat}\n---\nA recurring worry about durability, take ${i}.`, request_id: randomUUID() } });+ }+ let calls = 0;+ __setChatTransportForTests(async opts => {+ calls++;+ const write = calls === 1;+ return { text: write ? '' : 'Saved the pattern.', blocks: write ? [{ type: 'tool-call', toolCallId: 'pattern-write', toolName: 'brain_put_page', input: {+ slug: 'wiki/personal/patterns/durability', content: '---\ntitle: Durability pattern\ntype: note\n---\nA recurring theme in [[wiki/personal/reflections/example-0]].',+ } }] : [{ type: 'text', text: 'Saved the pattern.' }], stopReason: write ? 'tool_calls' : 'end', usage, model: opts.model!, providerId: 'anthropic' };+ });+ const result = await runPhasePatterns(engine, { brainDir: root, sourceId, dryRun: false, once: true, cycleDate: '2026-09-20' });+ expect(result.details.patterns_written).toBe(1);+ const page = (await engine.readPageSnapshot('wiki/personal/patterns/durability', { sourceId }))!;+ expect(page.page.frontmatter.dream_generated).toBe(true);+ if (new Set(seats).size === 1) expect(page.page.frontmatter.seat).toBe('alice-desk');+ else expect(page.page.frontmatter).not.toHaveProperty('seat');+ });+ }+ }, 120_000);+});diff --git a/test/transcript-discovery-seat.test.ts b/test/transcript-discovery-seat.test.tsnew file mode 100644index 0000000000..bb116258d0--- /dev/null+++ b/test/transcript-discovery-seat.test.ts@@ -0,0 +1,37 @@+/**+ * #4618: dream discovery reads a session's `.seat.json` sidecar for every+ * corpus file of that session (session-end file, checkpoint segment), never+ * ingests the sidecar as a transcript, and ignores a sidecar whose seat is not+ * a valid label (it would otherwise reach page frontmatter verbatim).+ *+ * Authoring gate: protects the discovery half of the seat contract; the+ * end-to-end stamp test only covers whole-session `.txt` files. No seam.+ */+import { afterEach, beforeEach, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { basename, join } from 'node:path';+import { discoverTranscripts } from '../src/core/cycle/transcript-discovery.ts';++let dir: string;+beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'gb-seat-disc-')); });+afterEach(() => rmSync(dir, { recursive: true, force: true }));++const body = (topic: string) => `[user]\nLet us talk about ${topic}.\n\n${'[assistant]\nA long and useful answer.\n\n'.repeat(10)}`;+const sidecar = (sid: string, seat: string) =>+ writeFileSync(join(dir, `${sid}.seat.json`), JSON.stringify({ version: 1, seat, seat_source: 'env', hook_lane: 'workspace', harness: 'claude-code', first_seen: '2026-09-20T00:00:00.000Z' }));++test('every corpus file of a session carries its seat; the sidecar is never a transcript; an invalid seat is ignored', () => {+ writeFileSync(join(dir, 'sess-a.txt'), body('the storage plan'));+ writeFileSync(join(dir, 'sess-a.seg-0123456789abcdef01234567.txt'), body('an earlier window'));+ sidecar('sess-a', 'alice-desk');+ writeFileSync(join(dir, 'sess-b.txt'), body('the budget'));+ sidecar('sess-b', '../Not A Seat');+ writeFileSync(join(dir, 'sess-c.txt'), body('the garden'));++ const found = discoverTranscripts({ corpusDir: dir, minChars: 50 });+ expect(found.map((t) => basename(t.filePath))).toEqual([+ 'sess-a.seg-0123456789abcdef01234567.txt', 'sess-a.txt', 'sess-b.txt', 'sess-c.txt',+ ]);+ expect(found.map((t) => t.seat)).toEqual(['alice-desk', 'alice-desk', undefined, undefined]);+});