Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Conversation archive days with long cron names archive, and a partly failed run lists its failed days (#9501)

Garry Tan638b1fd4a9de
diff --git a/changelog.d/capy-archive-slug-exit-fix.md b/changelog.d/capy-archive-slug-exit-fix.md
new file mode 100644
index 0000000000..176aa7fb82
--- /dev/null
+++ b/changelog.d/capy-archive-slug-exit-fix.md
@@ -0,0 +1,7 @@
+**`gbrain transcripts archive` no longer has a day page refused by the write gate over its name, and a run exits 1 exactly when its `errors` list is not empty.**
+
+### Fixed
+- Day page names always pass the write gate. A cron job name cut at 24 characters no longer ends in a hyphen, and a label's repeated hyphens fold into one and its leading or trailing hyphen drops.
+- Every day a run fails to write is listed in the run's `errors` (in `--json`) with its `day` and `code`, and a shared brain with no owner lists the `archive_owner_unset` hold there too. `run` and `backfill` exit 1 exactly when that list is not empty, and 0 otherwise.
+- `--dry-run` reports `write_mode: coordinator` when the real run would write through the write coordinator, even before the archive source exists.
+- Days recorded by `gbrain transcripts archive adopt-legacy` are still skipped after the brain turns shared and the archive moves to its owner-only source.
diff --git a/docs/guides/conversation-archive.md b/docs/guides/conversation-archive.md
index 0c6cd3a96e..0f6f6d13e2 100644
--- a/docs/guides/conversation-archive.md
+++ b/docs/guides/conversation-archive.md
@@ -54,6 +54,14 @@ and the next pass picks up the rest.
`gbrain transcripts archive run` archives now, on demand, whatever the pass is doing; it works with automatic
maintenance turned off (`maintenance.auto false`).
+`run` and `backfill` exit 1 when anything in the run failed, and 0 otherwise, even when most days were written:
+the days that did not make it are retried by the next run on their own, and a script or scheduler should see that
+this run left work behind. Every failure is in the `errors` list of `--json` (a reader that could not be read, a day
+that could not be written, with its `day` and `code`, a day index, or the `archive_owner_unset` hold on a shared
+brain), so the list is empty exactly when the exit code is 0. A `--dry-run` reports the `write_mode` the real run
+will use (`coordinator` on a brain whose writes go through the write coordinator), even before the archive source
+exists.
+
On a managed brain the pass writes each day page as a `put_page` write request through the write coordinator, under the
same local identity as `gbrain transcripts archive run` (`local_cli`). Waiting for the coordinator counts against the
120 seconds; a write it accepted but has not published yet counts as archived, publishes on the coordinator's next turn,
@@ -127,7 +135,9 @@ gbrain transcripts archive adopt-legacy --dir ~/brain/conversations #
gbrain transcripts archive adopt-legacy --dir ~/brain/conversations --apply # record the covered days
```
-The old pages are never changed or deleted. Second, remove the old script's schedule yourself (its crontab line or
+The covered days are recorded in the brain's config, so they count before the archive source exists, and later
+runs skip them whichever archive source they write to (the brain turning shared included). The old pages are never
+changed or deleted. Second, remove the old script's schedule yourself (its crontab line or
scheduled job), so two archivers do not run side by side. Third, let the maintenance pass fill the gap, or run
`gbrain transcripts archive backfill --from <day>` now.
diff --git a/src/commands/transcripts-archive.ts b/src/commands/transcripts-archive.ts
index f2d6215e4a..f38a884f93 100644
--- a/src/commands/transcripts-archive.ts
+++ b/src/commands/transcripts-archive.ts
@@ -107,10 +107,10 @@ export async function runTranscriptsArchive(engine: BrainEngine, args: string[],
console.log(' days written ' + result.written + ', unchanged ' + result.unchanged + ', held ' + result.held + ', planned ' + result.planned + ', covered by legacy ' + result.skipped_legacy);
const redacted = result.days.filter(d => (d.redactions ?? 0) > 0);
if (redacted.length) console.log(' redacted values on ' + redacted.length + ' page(s): ' + redacted.map(d => d.slug + ' (' + d.redactions + ')').join(', '));
- for (const d of result.days.filter(d => d.status === 'held' || d.status === 'error')) console.log(' ' + d.status + ': ' + d.harness + ' ' + d.day + ' (' + d.code + ')');
+ for (const d of result.days.filter(d => d.status === 'held')) console.log(' held: ' + d.harness + ' ' + d.day + ' (' + d.code + ')');
for (const line of result.info) console.log(' ' + line);
- for (const e of result.errors) console.log(' error: ' + e.reader + ' ' + e.code + ': ' + e.message);
+ for (const e of result.errors) console.log(' error: ' + (e.reader ?? e.harness + (e.day ? ' ' + e.day : '')) + ' ' + e.code + ': ' + e.message);
if (sub === 'backfill' && result.written) console.log(' backfilled pages are keyword-only; preview their embedding cost with: gbrain embed --held --dry-run');
});
- if (result.errors.length || result.days.some(d => d.status === 'error') || (result.held && result.fix)) setCliExitVerdict(1);
+ if (result.errors.length) setCliExitVerdict(1);
}
diff --git a/src/core/transcripts/archive-day.ts b/src/core/transcripts/archive-day.ts
index f72754b0ac..129c1ece15 100644
--- a/src/core/transcripts/archive-day.ts
+++ b/src/core/transcripts/archive-day.ts
@@ -78,14 +78,16 @@ export function conversationHash8(harness: TranscriptFormat, conversationKey: st
}
export function conversationLabel(harness: TranscriptFormat, conversationKey: string, channel?: ArchiveChannel): string {
- if (channel?.cronJob) return 'cron-' + (slugifySegment(channel.cronJob).slice(0, 24) || conversationHash8(harness, conversationKey));
+ if (channel?.cronJob) return 'cron-' + (slugifySegment(channel.cronJob).slice(0, 24).replace(/-+$/, '') || conversationHash8(harness, conversationKey));
if (channel?.verified && (channel.chatType === 'group' || channel.chatType === 'room')) return channel.chatType + '-' + conversationHash8(harness, conversationKey);
if (channel?.verified && channel.chatType === 'direct') return 'dm';
return harness;
}
+/** The day page's slug; the label's hyphen runs fold and its edge hyphens drop, so the write gate never refuses it (slug_hyphen_run). */
export function archiveDayBaseSlug(harness: TranscriptFormat, day: string, label: string, conversationKey: string): string {
- return 'conversations/' + harness + '/' + day + '/' + label + '-' + transcriptSlugId(conversationKey).slice(0, 8);
+ const safe = label.replace(/-+/g, '-').replace(/^-|-$/g, '') || harness;
+ return 'conversations/' + harness + '/' + day + '/' + safe + '-' + transcriptSlugId(conversationKey).slice(0, 8);
}
export function archiveDayId(harness: TranscriptFormat, conversationKey: string, day: string, part: number): string {
diff --git a/src/core/transcripts/archive-maintenance.ts b/src/core/transcripts/archive-maintenance.ts
index a933346bec..b31f2d572b 100644
--- a/src/core/transcripts/archive-maintenance.ts
+++ b/src/core/transcripts/archive-maintenance.ts
@@ -102,7 +102,7 @@ function nonNegative(value: string | null | undefined, fallback: number): number
function resultErrors(result: ArchiveRunResult): ArchiveMaintenanceError[] {
return [
- ...result.errors.map(e => ({ code: e.code, message: (e.reader + ': ' + e.message).slice(0, 300) })),
+ ...result.errors.filter(e => e.reader).map(e => ({ code: e.code, message: (e.reader + ': ' + e.message).slice(0, 300) })),
...result.days.filter(d => d.status === 'error').map(d => ({ code: d.code ?? 'archive_day_failed', message: (d.harness + ' ' + d.day + ': ' + (d.message ?? 'no detail')).slice(0, 300) })),
];
}
diff --git a/src/core/transcripts/archive.ts b/src/core/transcripts/archive.ts
index 3d43657894..f9bf4bbe47 100644
--- a/src/core/transcripts/archive.ts
+++ b/src/core/transcripts/archive.ts
@@ -174,6 +174,12 @@ export interface ArchiveDayOutcome {
export interface ArchiveReaderError { harness: string; reader: string; code: string; message: string; fix?: Action; /** When the run that met it read (status only). */ at?: string }
+/**
+ * One thing a run could not do: a reader that failed (reader set), a conversation day that failed (day set), the day
+ * index, or the owner-unset hold on a shared brain. A run returns exit 1 exactly when this list is not empty.
+ */
+export interface ArchiveRunError { harness: string; reader?: string; day?: string; conversation_key_hash?: string; code: string; message: string; fix?: Action }
+
/** One reader as the last run that read it found it: the newest message any run saw, and the last run's error until a later read succeeds. */
interface ArchiveReadRecord {
harness: string;
@@ -214,7 +220,8 @@ export interface ArchiveRunResult {
index_pages: string[];
deferred_days: string[];
info: string[];
- errors: ArchiveReaderError[];
+ /** Every failure of this run (ArchiveRunError); empty exactly when the run exits 0. */
+ errors: ArchiveRunError[];
message?: string;
fix?: Action;
/** The run reached deadlineAtMs and left conversations for the next run. */
@@ -306,10 +313,19 @@ async function writeLedger(engine: BrainEngine, entry: ArchiveLedgerEntry): Prom
await engine.setConfig(ledgerKey(source_id, harness, conversation_key_hash, day), JSON.stringify({ ...value, updated_at: new Date().toISOString() }));
}
-async function legacyCovered(engine: BrainEngine, sourceId: string): Promise<Set<string>> {
- const prefix = LEGACY_PREFIX + sourceId + '.';
- const rows = await engine.executeRaw<{ key: string }>('SELECT key FROM config WHERE key LIKE $1', [prefix + '%']);
- return new Set(rows.map(r => r.key.slice(prefix.length)));
+/**
+ * Days an old archive folder covers, as adopt-legacy recorded them. adopt-legacy records them under the source it
+ * resolved then (the configured archive source, or its <source>-owner twin on a shared brain whose source is a
+ * checkout), so they are read under both ids: a brain that turned shared or personal in between still skips them.
+ */
+async function legacyCovered(engine: BrainEngine, configured: string): Promise<Set<string>> {
+ const out = new Set<string>();
+ for (const id of [configured, configured + '-owner']) {
+ const prefix = LEGACY_PREFIX + id + '.';
+ const rows = await engine.executeRaw<{ key: string }>('SELECT key FROM config WHERE key LIKE $1', [prefix + '%']);
+ for (const r of rows) out.add(r.key.slice(prefix.length));
+ }
+ return out;
}
function machineTimeZone(): string {
@@ -620,7 +636,8 @@ async function archiveSource(engine: BrainEngine, opts: ArchiveRunOpts, ctx: { e
: await ensureSource(engine, sourceId);
const context = dryRun ? undefined
: opts.context ?? (opts.makeContext && await managedPersistenceEnabled(engine) ? await opts.makeContext(sourceId) : undefined);
- const managed = !!context && await managedPersistenceEnabled(engine);
+ // A dry run builds no write context, but reports the write path the real run would take with the same options.
+ const managed = (dryRun ? !!(opts.context ?? opts.makeContext) : !!context) && await managedPersistenceEnabled(engine);
const writeMode: ArchiveRunResult['write_mode'] = managed ? 'coordinator' : (!privacy.shared && isGitRepo(source.local_path) ? 'repo' : 'database');
if (!dryRun) await reconcileAudience(engine, await configuredSource(engine, opts.sourceId), privacy);
const tz = await archiveTimeZone(engine, sourceId);
@@ -649,6 +666,7 @@ async function archiveSource(engine: BrainEngine, opts: ArchiveRunOpts, ctx: { e
if (privacy.shared && !privacy.owner) {
result.message = 'This brain is shared and names no owner member, so every archive day is held (archive_owner_unset) and nothing was written.';
result.fix = ownerFix;
+ result.errors.push({ harness: '*', code: 'archive_owner_unset', message: result.message, fix: ownerFix });
}
const readers = opts.readers ?? await defaultArchiveReaders();
@@ -675,7 +693,7 @@ async function archiveSource(engine: BrainEngine, opts: ArchiveRunOpts, ctx: { e
const patterns = loadImportRedactionPatterns();
const redactionVersion = sha256(ARCHIVE_REDACTION_RULES + '\u0000' + patterns.map(p => p.source).join('\u0000'));
const ledger = new Map((await readArchiveLedger(engine, sourceId)).map(e => [e.harness + '.' + e.conversation_key_hash + '.' + e.day, e]));
- const legacy = await legacyCovered(engine, sourceId);
+ const legacy = await legacyCovered(engine, await configuredSource(engine, opts.sourceId));
const covered = (harness: string, day: string) => legacy.has(harness + '.' + day) || legacy.has('*.' + day);
interface Item { entry: ArchiveScanEntry; hash: string; days: string[] }
@@ -878,6 +896,9 @@ async function archiveSource(engine: BrainEngine, opts: ArchiveRunOpts, ctx: { e
pending.sort((a, b) => b.day.localeCompare(a.day));
result.days.push(...pending);
+ for (const d of pending) {
+ if (d.status === 'error') result.errors.push({ harness: d.harness, day: d.day, conversation_key_hash: d.conversation_key_hash, code: d.code ?? 'archive_day_failed', message: d.message ?? 'no detail' });
+ }
for (const d of result.days) {
if (d.status === 'written') result.written++;
else if (d.status === 'accepted') result.accepted++;
@@ -1047,7 +1068,7 @@ export async function archiveStatus(engine: BrainEngine, opts: { sourceId?: stri
enabled: await archiveEnabled(engine), source_id: sourceId, timezone: pinned, configured_timezone: configured, harnesses: [],
archived_days: entries.filter(e => e.hash && !e.held).length,
held: entries.filter(e => e.held).map(e => ({ harness: e.harness, day: e.day, code: e.held!.code })),
- legacy_days: (await legacyCovered(engine, sourceId)).size, errors: [],
+ legacy_days: (await legacyCovered(engine, await configuredSource(engine, opts.sourceId))).size, errors: [],
};
const reads = await readArchiveReads(engine, sourceId);
const zone = pinned ?? configured;
diff --git a/test/transcripts-archive-managed-slug.test.ts b/test/transcripts-archive-managed-slug.test.ts
new file mode 100644
index 0000000000..b12b3eed98
--- /dev/null
+++ b/test/transcripts-archive-managed-slug.test.ts
@@ -0,0 +1,76 @@
+/**
+ * The conversation archive on a writer-claimed (managed) brain, through the real put_page write gate: a day label that
+ * used to end in a hyphen (a cron job name cut at 24 characters right after a hyphen) is refused there with
+ * slug_hyphen_run. Every archive slug now passes the gate, the day archives, and a dry run names the coordinator write
+ * path the real run takes. Same harness as test/transcripts-archive-managed.test.ts; every value is synthetic.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } 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/main.ts';
+import { disposePersistenceConsumer, stopPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { ARCHIVE_TIMEZONE_KEY, runTranscriptArchive, setArchiveEnabled } from '../src/core/transcripts/archive.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { archivedPages, conversation, staticReader } from './helpers/transcript-archive.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-archive-slug-'));
+ await engine.setConfig(ARCHIVE_TIMEZONE_KEY, 'UTC');
+ await engine.setConfig('brain.audience', 'personal');
+ await setArchiveEnabled(engine, true);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled = true WHERE singleton = 1');
+ await withEnv({ GBRAIN_HOME: dir }, () => registerLocalWriter(engine, 'cli'));
+ return () => rmSync(dir, { recursive: true, force: true });
+});
+
+/** 'aaa-' six times is 24 characters, so the old 24-character cut ended the label in a hyphen. */
+const CRON = 'aaa-bbb-ccc-ddd-eee-fff-ggg-hhh';
+const readers = () => [staticReader('openclaw', [conversation('openclaw', 'session-cron-1', [
+ ['user', '2026-10-01T10:00:00.000Z', 'scheduled prompt'], ['assistant', '2026-10-01T10:01:00.000Z', 'scheduled answer'],
+], { chatType: 'direct', verified: true, cronJob: CRON })])];
+
+function archive(dryRun = false) {
+ return withEnv({ GBRAIN_HOME: dir, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, () =>
+ runTranscriptArchive(engine, { mode: 'backfill', from: '2026-10-01', to: '2026-10-02', readers: readers(), dryRun,
+ makeContext: source => makeContext(engine, { source, dry_run: false }), now: new Date('2026-10-10T00:00:00Z') }));
+}
+
+describe('archive slugs through the managed write gate', () => {
+ test('a dry run names the coordinator write path, before the archive source exists', async () => {
+ expect((await engine.executeRaw("SELECT 1 FROM sources WHERE id = 'conversations'")).length).toBe(0);
+ const preview = await archive(true);
+ expect(preview.write_mode).toBe('coordinator');
+ expect(preview.planned).toBe(1);
+ const run = await archive();
+ expect(run.write_mode).toBe(preview.write_mode);
+ }, 120_000);
+
+ test('a cron day whose label was cut after a hyphen archives, with no hyphen run in its slug', async () => {
+ const result = await archive();
+ expect(result.errors).toEqual([]);
+ expect(result.days.map(d => [d.day, d.status])).toEqual([['2026-10-01', 'written']]);
+ const slugs = (await archivedPages(engine)).map(p => p.slug).filter(s => s.startsWith('conversations/openclaw/'));
+ expect(slugs).toHaveLength(1);
+ expect(slugs[0]).toMatch(/^conversations\/openclaw\/2026-10-01\/cron-aaa-bbb-ccc-ddd-eee-fff-[0-9a-f]{8}$/);
+ }, 120_000);
+});
diff --git a/test/transcripts-archive-slug-errors.test.ts b/test/transcripts-archive-slug-errors.test.ts
new file mode 100644
index 0000000000..de1c2fbd84
--- /dev/null
+++ b/test/transcripts-archive-slug-errors.test.ts
@@ -0,0 +1,148 @@
+/**
+ * Conversation archive slugs, run errors and legacy marks. Every day slug passes the write gate's admission for a new
+ * page (no hyphen run, no segment-final hyphen, a portable file name) for any session key, cron job name or part
+ * number, and different conversations never share a slug. A day that fails is listed in the run's errors with its day
+ * and code (the CLI exits 1 exactly when that list is not empty) and archives on the next run. Days adopt-legacy
+ * recorded are skipped even when the brain turned shared in between. PGLite, synthetic values only.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { addMember } from '../src/core/access/members.ts';
+import { setOwner } from '../src/core/access/owner.ts';
+import { archiveDayBaseSlug, conversationLabel } from '../src/core/transcripts/archive-day.ts';
+import { ARCHIVE_TIMEZONE_KEY, adoptLegacyArchive, runTranscriptArchive, setArchiveEnabled, type ArchiveReader } from '../src/core/transcripts/archive.ts';
+import { suffixedSlugAdmission } from '../src/core/persistence/suffixed-slug.ts';
+import { slugPortabilityProblem } from '../src/core/portable-slug.ts';
+import { hyphenFoldedSlug } from '../src/core/sync.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { conversation, staticReader } from './helpers/transcript-archive.ts';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const HOSTILE = [
+ 'aaa-bbb-ccc-ddd-eee-fff-ggg', 'x-'.repeat(20), '-leading', 'trailing-', '--', '-', '', ' ', 'a--b---c', 'Ünïcödé-名前-', '🙂-🙂-',
+ 'dots.and.dots.', 'under_score_', 'slash/inside/', 'aux', 'con', 'nul.txt', 'x'.repeat(300), 'a-'.repeat(12) + 'tail', 'abcdefghijklmnopqrstuvw-xyz',
+];
+
+function* hostileCases(): Generator<{ key: string; cron?: string; chatType?: 'direct' | 'group' | 'room'; verified: boolean }> {
+ let n = 0;
+ for (const cron of HOSTILE) {
+ for (const chatType of ['direct', 'group', 'room', undefined] as const) {
+ for (const verified of [true, false]) {
+ n++;
+ yield { key: 'agent:main:cron:' + cron + ':' + n, cron, ...(chatType ? { chatType } : {}), verified };
+ yield { key: cron + '-' + n, ...(chatType ? { chatType } : {}), verified };
+ }
+ }
+ }
+}
+
+describe('archive day slugs pass the write gate', () => {
+ const ctx = { remote: false } as OperationContext;
+ test('for every hostile key, cron name, channel and part number', () => {
+ const seen = new Map<string, string>();
+ for (const c of hostileCases()) {
+ for (const harness of ['openclaw', 'claude-code', 'codex'] as const) {
+ const channel = c.verified || c.cron ? { verified: c.verified, ...(c.chatType ? { chatType: c.chatType } : {}), ...(c.cron !== undefined ? { cronJob: c.cron } : {}) } : undefined;
+ const base = archiveDayBaseSlug(harness, '2026-11-02', conversationLabel(harness, c.key, channel), c.key);
+ for (const slug of [base, base + '-p2', base + '-p17']) {
+ expect([slug, hyphenFoldedSlug(slug)]).toEqual([slug, null]);
+ expect([slug, slugPortabilityProblem(slug)]).toEqual([slug, null]);
+ expect(suffixedSlugAdmission(ctx, slug, false)).toBeNull();
+ }
+ const prior = seen.get(base);
+ expect([base, prior ?? harness + c.key]).toEqual([base, harness + c.key]);
+ seen.set(base, harness + c.key);
+ }
+ }
+ expect(seen.size).toBeGreaterThan(300);
+ });
+});
+
+describe('run errors and retries (pglite)', () => {
+ let engine: PGLiteEngine;
+ const dirs: string[] = [];
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => {
+ await engine.disconnect();
+ for (const d of dirs) rmSync(d, { recursive: true, force: true });
+ });
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig(ARCHIVE_TIMEZONE_KEY, 'UTC');
+ await engine.setConfig('brain.audience', 'personal');
+ await setArchiveEnabled(engine, true);
+ });
+
+ const conv = () => conversation('codex', 'rollout-retry', [['user', '2026-11-02T10:00:00.000Z', 'hello'], ['assistant', '2026-11-02T10:01:00.000Z', 'hi']]);
+ const opts = { mode: 'backfill' as const, from: '2026-11-01', to: '2026-11-03', now: new Date('2026-11-10T00:00:00Z') };
+
+ test('a day that fails is listed in errors with its day and code, and archives on the next run', async () => {
+ let fail = true;
+ const reader: ArchiveReader = {
+ harness: 'codex', name: 'codex',
+ async *scan() {
+ const c = conv();
+ yield { harness: 'codex', conversationKey: c.conversationKey, sessionId: c.conversationKey, days: ['2026-11-02'], newest: '2026-11-02T10:01:00.000Z',
+ load: async () => { if (fail) throw new Error('synthetic read failure'); return c; } };
+ },
+ };
+ const first = await runTranscriptArchive(engine, { ...opts, readers: [reader] });
+ expect(first.days.map(d => [d.day, d.status, d.code])).toEqual([['2026-11-02', 'error', 'archive_reader_failed']]);
+ expect(first.errors).toEqual([expect.objectContaining({ harness: 'codex', day: '2026-11-02', code: 'archive_reader_failed', message: 'synthetic read failure' })]);
+ fail = false;
+ const second = await runTranscriptArchive(engine, { ...opts, readers: [reader] });
+ expect(second.errors).toEqual([]);
+ expect(second.days.map(d => [d.day, d.status])).toEqual([['2026-11-02', 'written']]);
+ }, 60_000);
+
+ test('a shared brain with no owner lists the hold in errors', async () => {
+ await engine.setConfig('brain.audience', 'shared');
+ const result = await runTranscriptArchive(engine, { ...opts, readers: [staticReader('codex', [conv()])] });
+ expect(result.held).toBe(1);
+ expect(result.errors.map(e => e.code)).toEqual(['archive_owner_unset']);
+ }, 60_000);
+
+ test('days adopt-legacy recorded are skipped after the brain turned shared and the archive moved to its owner-only source', async () => {
+ const legacy = mkdtempSync(join(tmpdir(), 'archive-legacy-'));
+ const checkout = mkdtempSync(join(tmpdir(), 'archive-checkout-'));
+ dirs.push(legacy, checkout);
+ mkdirSync(join(legacy, 'codex'), { recursive: true });
+ writeFileSync(join(legacy, 'codex', '2026-11-02.md'), '# old archive day\n');
+ const adopted = await adoptLegacyArchive(engine, { dir: legacy, apply: true });
+ expect(adopted.source_id).toBe('conversations');
+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('conversations', 'Conversation archive checkout', $1)", [checkout]);
+ await engine.setConfig('brain.audience', 'shared');
+ await addMember(engine, 'alice-example');
+ await setOwner(engine, 'alice-example');
+ const result = await runTranscriptArchive(engine, { ...opts, readers: [staticReader('codex', [conv()])] });
+ expect(result.source_id).toBe('conversations-owner');
+ expect(result.skipped_legacy).toBe(1);
+ expect(result.written).toBe(0);
+ }, 60_000);
+
+ test('days adopt-legacy recorded on a shared brain are still skipped after the brain turned personal again', async () => {
+ const legacy = mkdtempSync(join(tmpdir(), 'archive-legacy-'));
+ const checkout = mkdtempSync(join(tmpdir(), 'archive-checkout-'));
+ dirs.push(legacy, checkout);
+ mkdirSync(join(legacy, 'codex'), { recursive: true });
+ writeFileSync(join(legacy, 'codex', '2026-11-02.md'), '# old archive day\n');
+ await engine.executeRaw("INSERT INTO sources (id, name, local_path) VALUES ('conversations', 'Conversation archive checkout', $1)", [checkout]);
+ await engine.setConfig('brain.audience', 'shared');
+ await addMember(engine, 'alice-example');
+ await setOwner(engine, 'alice-example');
+ const adopted = await adoptLegacyArchive(engine, { dir: legacy, apply: true });
+ expect(adopted.source_id).toBe('conversations-owner');
+ await engine.setConfig('brain.audience', 'personal');
+ const result = await runTranscriptArchive(engine, { ...opts, readers: [staticReader('codex', [conv()])] });
+ expect(result.source_id).toBe('conversations');
+ expect(result.skipped_legacy).toBe(1);
+ expect(result.written).toBe(0);
+ }, 60_000);
+});