Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): submit ingest pages through the persistence coordinator (#5408)

time-attacke8646b1f8981
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 1ab58624b1..df3ef94c8a 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -114,7 +114,7 @@ src/core/takes-write.ts 8 filesystem_guard Managed operation routes through jour
src/core/think/index.ts 1 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/core/timeline-dedup-repair.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.
src/core/timeline-write-through.ts 2 filesystem_guard Managed semantic operation journals page changes; legacy atomic writes check root.
-src/core/transcripts/ingest.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).
+src/core/transcripts/ingest.ts 2 engine_guard On writer-claimed brains the CLI ingest submits rendered parts as put_page write requests (submitPageMutation with its trusted-local context). The remaining direct importFromContent (unmanaged brains) and stale-part deletePage calls refuse on managed brains before any write (assertUnmanagedCanonicalWriter / canonical table trigger).
src/core/workspace-push.ts 0 filesystem_guard The resolved git root is checked before staging, committing or pulling.
src/core/write-through.ts 1 filesystem_guard Source filesystem lock and canonical page SQL guards reject legacy publication.
src/eval/brainbench/seed.ts 3 isolated_eval Explicit isolated evaluation database only; never opened against the active managed brain. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index 8184402852..80fc9a9f91 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -10,7 +10,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/takes-mutation.ts` — one parser and operation adapter for local, resident PGLite, and HTTP take mutations. Allocates a request UUID before delivery; retries retain that UUID and caller intent. `--source` remains claim provenance, `--source-id` selects the logical source, and `--dir` becomes a trusted local canonical-root assertion. Default owner/resolver choices remain unset until admission freezes them. The CLI and thin-client router share this parser for all four mutations before connecting; queued/error responses never print completed-mutation text. Remote failures use the shared typed reporter directly, retaining UUIDs, unknown delivery status and original receipt fields in JSON. `test/persistence-cli-delegation.test.ts` drives the real CLI through a held PGLite owner's socket, checks all four parameter mappings and pending receipts, and rejects malformed numeric/precondition input.
-- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest`; embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`.
+- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`.
- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report).
diff --git a/src/cli.ts b/src/cli.ts
index d4e3364b76..3746f22e54 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1919,6 +1919,7 @@ const CLI_DISPATCH_CONTEXT: CliDispatchContext = {
dbMarkerBrainId,
SELECTED_CONFIG_BY_ENGINE,
cliModuleUrl: import.meta.url,
+ makeContext,
};
/**
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 13acfd1620..2c078a0c0d 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -36,6 +36,7 @@
import type { GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
import type { Effect, Notice } from '../core/agent-output.ts';
+import type { OperationContext } from '../core/ops/contract.ts';
export type CliPhase = 'pre-connect' | 'pre-connect-own-engine' | 'post-connect';
export type CliThinClientMode = 'none' | 'refuse' | 'route-then-refuse';
@@ -51,6 +52,8 @@ export interface CliDispatchContext {
cliModuleUrl: string;
/** Agent contract v1 (A6): CLI notice channel (TTY stderr lines, non-TTY `[AGENT]` block, `--json` `notices`). */
emitNotice?: (n: Notice) => void;
+ /** The CLI's trusted-local operation context (src/cli.ts makeContext), for a command that submits coordinated writes. */
+ makeContext?: (engine: BrainEngine, params: Record<string, unknown>) => Promise<OperationContext>;
}
/** One curated flag in a lazy help module (D3). */
diff --git a/src/cli/commands/transcripts.ts b/src/cli/commands/transcripts.ts
index ddcc9bd790..7dbae6368e 100644
--- a/src/cli/commands/transcripts.ts
+++ b/src/cli/commands/transcripts.ts
@@ -5,8 +5,9 @@
* src/cli/command-table.ts.
*/
import type { BrainEngine } from '../../core/engine.ts';
+import type { CliDispatchContext } from '../command-table.ts';
-export async function run(engine: BrainEngine, args: string[]): Promise<void> {
+export async function run(engine: BrainEngine, args: string[], ctx: CliDispatchContext): Promise<void> {
const { runTranscripts } = await import('../../commands/transcripts.ts');
- await runTranscripts(engine, args);
+ await runTranscripts(engine, args, { makeContext: ctx.makeContext });
}
diff --git a/src/commands/transcripts-recover.ts b/src/commands/transcripts-recover.ts
index 9945fdbc39..b99dfec372 100644
--- a/src/commands/transcripts-recover.ts
+++ b/src/commands/transcripts-recover.ts
@@ -6,6 +6,7 @@
*/
import type { BrainEngine } from '../core/engine.ts';
+import type { CliDispatchContext } from '../cli/command-table.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
export const TRANSCRIPTS_RECOVER_HELP = `Usage:
@@ -24,7 +25,7 @@ facts are extracted and the --since last watermark is untouched.
--json Machine-readable plan (and ingest result with --apply)
`;
-export async function runTranscriptsRecover(engine: BrainEngine, args: string[]): Promise<void> {
+export async function runTranscriptsRecover(engine: BrainEngine, args: string[], dispatch: Pick<CliDispatchContext, 'makeContext'> = {}): Promise<void> {
if (args.includes('--help') || args.includes('-h')) {
console.log(TRANSCRIPTS_RECOVER_HELP);
return;
@@ -48,7 +49,8 @@ export async function runTranscriptsRecover(engine: BrainEngine, args: string[])
const sourceId = (await resolveSourceWithTier(engine, source)).source_id;
const { planCodexRecovery, applyCodexRecovery } = await import('../core/transcripts/recover.ts');
const plan = await planCodexRecovery(engine, { sourceId, rolloutPaths: paths.length ? paths : undefined });
- const result = apply ? await applyCodexRecovery(engine, plan) : null;
+ const context = apply ? await dispatch.makeContext?.(engine, { source: sourceId }) : undefined;
+ const result = apply ? await applyCodexRecovery(engine, plan, { context }) : null;
if (json) {
console.log(JSON.stringify({ plan, applied: apply, ...(result ? { ingest: { pages: result.pages, sessions_imported: result.sessionsImported, sessions_errored: result.sessionsErrored } } : {}) }, null, 2));
if (result && (result.sessionsErrored > 0 || result.erroredFiles > 0)) setCliExitVerdict(1);
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index 1292b825ce..a6bae5369f 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -17,6 +17,7 @@
import { homedir } from 'node:os';
import type { BrainEngine } from '../core/engine.ts';
+import type { CliDispatchContext } from '../cli/command-table.ts';
import type { RecentTranscript } from '../core/transcripts.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import type { TranscriptFormat } from '../core/transcripts/types.ts';
@@ -359,7 +360,7 @@ export function fmtSummary(r: TranscriptsIngestResult): string {
return lines.join('\n');
}
-async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {
+async function runIngest(engine: BrainEngine, args: string[], dispatch: Pick<CliDispatchContext, 'makeContext'>): Promise<void> {
const parsed = parseIngestArgs(args);
if ('help' in parsed) {
console.log(HELP);
@@ -491,6 +492,7 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {
reporter.start('transcripts.ingest', paths.length);
let result: TranscriptsIngestResult;
+ const context = await dispatch.makeContext?.(engine, { source: sourceId, dry_run: parsed.dryRun === true });
try {
result = await runTranscriptsIngest(engine, {
paths,
@@ -502,6 +504,7 @@ async function runIngest(engine: BrainEngine, args: string[]): Promise<void> {
maxBytes: parsed.maxBytes,
embed: parsed.embed,
activePack,
+ context,
onFileDone: () => reporter.tick(),
// Multi-session stores (one hermes state.db = thousands of sessions)
// need liveness BETWEEN file ticks.
@@ -593,10 +596,10 @@ async function runStatus(engine: BrainEngine, args: string[]): Promise<void> {
}
}
-export async function runTranscripts(engine: BrainEngine, args: string[]): Promise<void> {
+export async function runTranscripts(engine: BrainEngine, args: string[], dispatch: Pick<CliDispatchContext, 'makeContext'> = {}): Promise<void> {
const sub = args[0];
if (sub === 'ingest') {
- await runIngest(engine, args.slice(1));
+ await runIngest(engine, args.slice(1), dispatch);
return;
}
if (sub === 'status') {
@@ -605,7 +608,7 @@ export async function runTranscripts(engine: BrainEngine, args: string[]): Promi
}
if (sub === 'recover') {
const { runTranscriptsRecover } = await import('./transcripts-recover.ts');
- await runTranscriptsRecover(engine, args.slice(1));
+ await runTranscriptsRecover(engine, args.slice(1), dispatch);
return;
}
if (sub !== 'recent') {
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts
index 15328a7e61..e677a17133 100644
--- a/src/core/transcripts/ingest.ts
+++ b/src/core/transcripts/ingest.ts
@@ -29,6 +29,9 @@
import type { BrainEngine } from '../engine.ts';
import { importFromContent } from '../import-file.ts';
+import type { OperationContext } from '../ops/contract.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { submitPageMutation } from '../persistence/page-mutations.ts';
import { canonicalJson } from '../remediation-step.ts';
import type { FileDiagnostics, TranscriptAdapter, TranscriptFormat } from './types.ts';
import { detectAdapter } from './detect.ts';
@@ -70,6 +73,12 @@ export interface TranscriptsIngestOpts {
*/
maxBytes?: number;
activePack?: IngestActivePack;
+ /**
+ * The CLI's trusted-local operation context. On a writer-claimed brain each
+ * rendered part is submitted as a `put_page` write request through it; the
+ * direct importer is refused there. Without it the direct importer runs.
+ */
+ context?: OperationContext;
/** Test seam for the redaction user-pattern file. */
userPatternsPath?: string;
/** Adapter registry override (tests). */
@@ -190,6 +199,7 @@ export async function runTranscriptsIngest(
// recompiles the pattern file on every call, which a bulk import would
// otherwise repeat thousands of times.
const redactionPatterns = loadImportRedactionPatterns(opts.userPatternsPath);
+ const coordinator = !opts.dryRun && opts.context && await managedPersistenceEnabled(engine) ? opts.context : null;
const total = opts.paths.length;
let done = 0;
@@ -311,14 +321,15 @@ export async function runTranscriptsIngest(
for (const part of rendered.parts) {
try {
await preserveForeignFrontmatter(engine, opts.sourceId ?? 'default', part);
- const r = await importFromContent(engine, part.slug, part.content, {
- noEmbed: !opts.embed,
- sourceId: opts.sourceId,
- activePack: opts.activePack,
- source_kind: `transcript:${session.meta.harness}`,
- source_uri: path,
- ingested_via: 'cli:transcripts-ingest',
- });
+ const provenance = { source_kind: `transcript:${session.meta.harness}`, source_uri: path, ingested_via: 'cli:transcripts-ingest' };
+ const r = coordinator
+ ? await submitTranscriptPart(coordinator, engine, opts.sourceId, part, provenance)
+ : await importFromContent(engine, part.slug, part.content, {
+ noEmbed: !opts.embed,
+ sourceId: opts.sourceId,
+ activePack: opts.activePack,
+ ...provenance,
+ });
outcome.statuses.push(r.status);
if (r.status === 'imported') result.pages.imported++;
else if (r.status === 'skipped') result.pages.skipped++;
@@ -453,6 +464,31 @@ export async function runTranscriptsIngest(
return result;
}
+/**
+ * A writer-claimed brain refuses the direct importer, so a rendered part is
+ * submitted as a `put_page` write request: the same importer runs behind the
+ * coordinator, naming the current revision so a replacement is never a blind
+ * overwrite (no revision means create-only). Embedding is deferred there, as
+ * for every coordinated page write.
+ */
+async function submitTranscriptPart(
+ ctx: OperationContext,
+ engine: BrainEngine,
+ sourceId: string,
+ part: RenderedPart,
+ provenance: { source_kind: string; source_uri: string; ingested_via: string },
+): Promise<{ slug: string; status: 'imported' | 'skipped' | 'error' }> {
+ const snapshot = await engine.readPageSnapshot(part.slug, { sourceId, includeDeleted: true });
+ const receipt = await submitPageMutation(ctx, {
+ operation: 'put_page',
+ params: { slug: part.slug, content: part.content, source_id: sourceId, ...provenance,
+ ...(snapshot?.revision ? { expected_revision: snapshot.revision } : {}) },
+ });
+ const slug = typeof receipt.slug === 'string' && receipt.slug ? receipt.slug : part.slug;
+ if (receipt.state !== 'committed') return { slug, status: 'error' };
+ return { slug, status: receipt.noop === true || receipt.status === 'skipped' ? 'skipped' : 'imported' };
+}
+
/**
* The slug embeds the title (and start day) for export formats, so a rename
* renders a new slug for the same session. Import at the slug the session's
diff --git a/test/transcripts-managed-ingest.test.ts b/test/transcripts-managed-ingest.test.ts
new file mode 100644
index 0000000000..8fd693c9a2
--- /dev/null
+++ b/test/transcripts-managed-ingest.test.ts
@@ -0,0 +1,123 @@
+/**
+ * `gbrain transcripts ingest` on a writer-claimed (managed) brain (#5235).
+ *
+ * Protects: on a managed brain the direct importer is refused
+ * (writer_coordinator_required), so each rendered part must be submitted as a
+ * `put_page` write request through the CLI's trusted-local context. Fails
+ * when: the ingest still calls the direct importer (every page errors), a
+ * replacement is sent without the page's revision, or the coordinator path
+ * leaks onto an unmanaged brain or a dry run. The context comes from the
+ * CLI's own constructor (`makeContext`), so `remote: false` is never
+ * hand-built here.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { makeContext } from '../src/cli.ts';
+import { runTranscriptsIngest } from '../src/core/transcripts/ingest.ts';
+import { runTranscripts } from '../src/commands/transcripts.ts';
+import { disposePersistenceConsumer, stopPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+let dir: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 120_000);
+
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await stopPersistenceConsumer(engine);
+ await resetPgliteState(engine);
+ dir = mkdtempSync(join(tmpdir(), 'gb-managed-ingest-'));
+ return () => rmSync(dir, { recursive: true, force: true });
+});
+
+function exportFile(name: string, grown: boolean): string {
+ const message = (role: string, t: number, text: string) => ({ author: { role }, create_time: t, content: { content_type: 'text', parts: [text] } });
+ const mapping: Record<string, unknown> = {
+ root: { id: 'root', parent: null, children: ['n1'], message: null },
+ n1: { id: 'n1', parent: 'root', children: ['n2'], message: message('user', 1786080005, 'First question about acme-example.') },
+ n2: { id: 'n2', parent: 'n1', children: grown ? ['n3'] : [], message: message('assistant', 1786080015, 'First answer.') },
+ };
+ if (grown) {
+ mapping.n3 = { id: 'n3', parent: 'n2', children: ['n4'], message: message('user', 1786090005, 'FOLLOWUP-MARKER new question') };
+ mapping.n4 = { id: 'n4', parent: 'n3', children: [], message: message('assistant', 1786090015, 'Follow-up answer.') };
+ }
+ const path = join(dir, name);
+ writeFileSync(path, JSON.stringify([{ title: 'Managed ingest', create_time: 1786080000, update_time: grown ? 1786090015 : 1786080015,
+ conversation_id: 'cgpt-managed-1', current_node: grown ? 'n4' : 'n2', mapping }]));
+ return path;
+}
+
+async function ingest(path: string, opts: { context?: boolean; dryRun?: boolean } = {}) {
+ return withEnv({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const context = opts.context === false ? undefined : await makeContext(engine, { source: 'default', dry_run: opts.dryRun === true });
+ return runTranscriptsIngest(engine, { paths: [path], sourceId: 'default', format: 'chatgpt', dryRun: opts.dryRun, context });
+ });
+}
+
+const conversationPages = () => engine.executeRaw<{ slug: string; has_new: boolean }>(
+ `SELECT slug, compiled_truth LIKE '%FOLLOWUP-MARKER%' AS has_new FROM pages
+ WHERE deleted_at IS NULL AND slug LIKE 'conversations/%' ORDER BY slug`);
+const pageRequests = () => engine.executeRaw<{ slug: string; state: string; principal_kind: string }>(
+ `SELECT slug, state, principal_kind FROM persistence_requests WHERE operation = 'put_page' ORDER BY sequence`);
+const claimBrain = () => engine.executeRaw('UPDATE persistence_brain SET enabled = true WHERE singleton = 1');
+
+describe('transcripts ingest on a writer-claimed brain', () => {
+ test('parts commit as local put_page write requests; a grown session updates in place by revision; a repeat is skipped', async () => {
+ await claimBrain();
+ const first = await ingest(exportFile('a.json', false));
+ expect(first).toMatchObject({ erroredFiles: 0, sessionsErrored: 0, pages: { imported: 1, errored: 0 } });
+ const [page] = await conversationPages();
+ expect(await pageRequests()).toEqual([{ slug: page.slug, state: 'committed', principal_kind: 'local_cli' }]);
+
+ const grown = await ingest(exportFile('b.json', true));
+ expect(grown).toMatchObject({ sessionsErrored: 0, pages: { imported: 1, errored: 0 } });
+ expect(await conversationPages()).toEqual([{ slug: page.slug, has_new: true }]);
+ expect((await pageRequests()).map(r => r.state)).toEqual(['committed', 'committed']);
+
+ const repeat = await ingest(exportFile('c.json', true));
+ expect(repeat.pages).toMatchObject({ imported: 0, skipped: 1, errored: 0 });
+ }, 120_000);
+
+ test('`gbrain transcripts ingest` passes the dispatcher\'s makeContext through to the coordinated path', async () => {
+ await claimBrain();
+ const path = exportFile('a.json', false);
+ await withEnv({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () =>
+ runTranscripts(engine, ['ingest', path, '--format', 'chatgpt', '--source', 'default', '--quiet'], { makeContext }));
+ const [page] = await conversationPages();
+ expect(await pageRequests()).toEqual([{ slug: page!.slug, state: 'committed', principal_kind: 'local_cli' }]);
+ }, 120_000);
+
+ test('without the trusted context the direct importer is still refused (the gate this routes around)', async () => {
+ await claimBrain();
+ await expect(ingest(exportFile('a.json', false), { context: false })).rejects.toThrow(/cannot mutate a managed brain through the legacy writer/);
+ expect(await conversationPages()).toEqual([]);
+ }, 120_000);
+
+ test('a dry run on a managed brain plans without submitting anything', async () => {
+ await claimBrain();
+ const planned = await ingest(exportFile('a.json', false), { dryRun: true });
+ expect(planned.pages).toMatchObject({ planned: 1, imported: 0 });
+ expect(await pageRequests()).toEqual([]);
+ expect(await conversationPages()).toEqual([]);
+ }, 120_000);
+});
+
+test('an unmanaged brain keeps the direct importer: no write requests are journaled', async () => {
+ const result = await ingest(exportFile('a.json', false));
+ expect(result.pages).toMatchObject({ imported: 1, errored: 0 });
+ expect(await conversationPages()).toHaveLength(1);
+ expect(await pageRequests()).toEqual([]);
+}, 120_000);