Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(connectors): keep failed conversations until they import (#6387)

time-attack5ec659e7ce75
diff --git a/src/commands/connectors/status.ts b/src/commands/connectors/status.ts
index 1e82f69e36..5654c3bd82 100644
--- a/src/commands/connectors/status.ts
+++ b/src/commands/connectors/status.ts
@@ -3,7 +3,9 @@
*
* Reuses the `connectors_status` op handler shape via the same helpers, but runs
* locally (trusted). Never prints the raw cookie/token — only provenance,
- * expiry, and sync state.
+ * expiry, and sync state. `unresolved` lists conversations the source has not
+ * archived yet (#6387): attempts, next retry, and whether only a `--full` sync
+ * can retry them.
*/
import type { BrainEngine } from '../../core/engine.ts';
@@ -17,6 +19,7 @@ import {
readConnectorState,
sourceIdKey,
} from '../../core/connectors/config-keys.ts';
+import { fullSyncArgv, readFailedLedger } from '../../core/connectors/failed-ledger.ts';
export async function runConnectorStatus(engine: BrainEngine, args: string[]): Promise<void> {
const json = args.includes('--json');
@@ -35,6 +38,13 @@ export async function runConnectorStatus(engine: BrainEngine, args: string[]): P
for (const prov of providers) {
if (!prov) continue;
const resolved = resolveCredential(prov.name);
+ const unresolved = Object.entries(await readFailedLedger(engine, prov.name, sourceId)).map(([id, e]) => ({
+ id,
+ attempts: e.attempts,
+ updated_at: e.updatedAt,
+ next_retry_at: e.nextRetryAt ?? null,
+ needs_full_sync: !!prov.routesByOrg && !e.orgId,
+ }));
rows.push({
provider: prov.name,
strategies: prov.strategies,
@@ -48,6 +58,7 @@ export async function runConnectorStatus(engine: BrainEngine, args: string[]): P
last_sync_at: await readConnectorState(engine, prov.name, sourceId, 'last_sync_at'),
auth_error_at: (await engine.getConfig(authErrorAtKey(prov.name))) || null,
watermark_iso: await readConnectorState(engine, prov.name, sourceId, 'watermark_iso'),
+ unresolved,
});
}
@@ -63,5 +74,11 @@ export async function runConnectorStatus(engine: BrainEngine, args: string[]): P
`${r.provider} [${r.spec_target_status}] ${cred} auto_sync=${r.auto_sync}\n` +
` last_sync: ${r.last_sync_at ?? 'never'} watermark: ${r.watermark_iso ?? 'none'}${auth}`,
);
+ if (r.unresolved.length === 0) continue;
+ const needsFull = r.unresolved.filter((u) => u.needs_full_sync).length;
+ console.log(
+ ` ⚠ archive incomplete: ${r.unresolved.length} conversation(s) not archived yet; sync retries them automatically` +
+ (needsFull ? `; ${needsFull} need one full re-sync (re-downloads the whole history; ask first): ${fullSyncArgv(r.provider, r.source_id).join(' ')}` : ''),
+ );
}
}
diff --git a/src/commands/doctor/checks/connectors.ts b/src/commands/doctor/checks/connectors.ts
index 0564f52c46..f34bfd4adb 100644
--- a/src/commands/doctor/checks/connectors.ts
+++ b/src/commands/doctor/checks/connectors.ts
@@ -7,6 +7,10 @@
* `connectors.doctor_stale_hours` (default 72 — NOT the dispatch floor, so
* a manual sync a few hours ago never nags)
* - drift: the latest connector receipt reports skipped conversations
+ * - archive incomplete (#6387): the source's failed ledger holds
+ * conversations not archived yet; sync retries them on its own, and a
+ * legacy entry only a `--full` sync can retry carries an ask-first fix
+ * (a full sync re-downloads the whole history with the user's session)
*
* Gated on a credential existing; a manual-lane user (auto_sync off) is never
* flagged for staleness. Never prints the credential value.
@@ -14,6 +18,10 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { Check } from '../../doctor.ts';
+import type { Action } from '../../../core/agent-output.ts';
+import { doctorVerify } from '../check-fix.ts';
+import { fullSyncArgv, readFailedLedger } from '../../../core/connectors/failed-ledger.ts';
+import { getConnectorProvider } from '../../../core/connectors/registry.ts';
import { connectorProviderNames } from '../../../core/connectors/registry.ts';
import { loadCredential } from '../../../core/connectors/credentials.ts';
import {
@@ -37,13 +45,39 @@ export async function connectorsHealthCheck(engine: BrainEngine): Promise<Check>
const problems: string[] = [];
let anyCredential = false;
+ let fix: Action | undefined;
const now = Date.now();
+ const sourceId = (await engine.getConfig(sourceIdKey())) || 'default';
for (const provider of connectorProviderNames()) {
const cred = loadCredential(provider);
if (!cred) continue;
anyCredential = true;
+ const failed = Object.values(await readFailedLedger(engine, provider, sourceId));
+ if (failed.length > 0) {
+ const needsFull = getConnectorProvider(provider)?.routesByOrg ? failed.filter((e) => !e.orgId).length : 0;
+ problems.push(
+ `${provider}: ${failed.length} unresolved conversation(s) — archive incomplete; sync retries them automatically ` +
+ `(\`gbrain connectors status ${provider} --json\` lists them)` +
+ (needsFull ? `; ${needsFull} need one full re-sync: ask the user, then run \`${fullSyncArgv(provider, sourceId).join(' ')}\`` : ''),
+ );
+ if (needsFull && !fix) {
+ fix = {
+ argv: fullSyncArgv(provider, sourceId),
+ consent: ['credentials'],
+ actor: 'agent',
+ why: `${needsFull} ${provider} conversation(s) failed before gbrain recorded which organization they belong to, so only a full re-sync can fetch them.`,
+ user_message:
+ `${needsFull} ${provider} conversation(s) are missing from your archive. Recovering them re-downloads your whole ${provider} ` +
+ 'history with your saved session (many requests to the provider; changed pages are re-imported). Run it now?',
+ verify: doctorVerify('connectors'),
+ docs: 'docs/guides/chat-connectors.md#recovering-an-archive-synced-before-this-fix',
+ requires_exclusive: false,
+ };
+ }
+ }
+
const authErrorAt = await engine.getConfig(authErrorAtKey(provider));
if (authErrorAt && cred.savedAt && authErrorAt > cred.savedAt) {
problems.push(`${provider}: re-auth needed — run \`gbrain connectors auth ${provider}\``);
@@ -51,7 +85,7 @@ export async function connectorsHealthCheck(engine: BrainEngine): Promise<Check>
}
if (isTruthy(await engine.getConfig(autoSyncKey(provider)))) {
- const lastSyncAt = await readConnectorState(engine, provider, (await engine.getConfig(sourceIdKey())) || 'default', 'last_sync_at');
+ const lastSyncAt = await readConnectorState(engine, provider, sourceId, 'last_sync_at');
const lastMs = lastSyncAt ? Date.parse(lastSyncAt) : NaN;
if (!Number.isFinite(lastMs) || now - lastMs >= staleHours * 3_600_000) {
problems.push(
@@ -78,5 +112,5 @@ export async function connectorsHealthCheck(engine: BrainEngine): Promise<Check>
if (problems.length === 0) {
return { name, status: 'ok', message: 'Chat connectors healthy.' };
}
- return { name, status: 'warn', message: problems.join('; ') };
+ return { name, status: 'warn', message: problems.join('; '), ...(fix ? { fix } : {}) };
}
diff --git a/src/core/connectors/failed-ledger.ts b/src/core/connectors/failed-ledger.ts
new file mode 100644
index 0000000000..05a0990ac4
--- /dev/null
+++ b/src/core/connectors/failed-ledger.ts
@@ -0,0 +1,149 @@
+/**
+ * failed-ledger.ts — the per-(provider, source) record of conversations a
+ * connector sync could not archive, and the retry plan built from it (#6387).
+ *
+ * An entry stays until its conversation imports. The watermark may pass it
+ * (a quarantined entry no longer holds the watermark back) and the provider
+ * may stop listing it, so a sync retries due entries by id: at most
+ * RETRY_BUDGET per run, oldest-due first, with slots reserved under `--limit`
+ * so new conversations cannot starve them. A quarantined entry waits
+ * HOLD_BACKOFF_MS[n] (then HOLD_DAILY_MS) after each further failure — the
+ * connector item-holds schedule, so connector retry timing is one policy.
+ * A conversation the provider lists with a new updatedAt, and `--full`,
+ * retry at once.
+ *
+ * Providers that route a detail fetch by organization (`routesByOrg`) record
+ * the org with the entry. An entry written before orgs were recorded cannot
+ * be retried by id safely (the wrong org returns 404 and would look like a
+ * content failure); it is held until a `--full` sync lists it again.
+ *
+ * No engine imports beyond config reads: status and doctor read this without
+ * loading the sync pipeline.
+ */
+
+import type { BrainEngine } from '../engine.ts';
+import { connectorSourceKey } from './config-keys.ts';
+import { HOLD_BACKOFF_MS, HOLD_DAILY_MS } from './item-holds.ts';
+import type { ConnectorProviderName, ConversationStub } from './types.ts';
+
+/** Failed fetches or ingests at one updatedAt before a conversation is quarantined. */
+export const QUARANTINE_ATTEMPTS = 3;
+/** Retained failures retried by id per sync run. */
+export const RETRY_BUDGET = 10;
+
+export interface FailedEntry {
+ attempts: number;
+ updatedAt: string;
+ lastAttemptAt?: string;
+ /** Absent: due now. Set once the entry is quarantined. */
+ nextRetryAt?: string;
+ orgId?: string;
+}
+
+export type FailedLedger = Record<string, FailedEntry>;
+
+export function isQuarantined(entry: FailedEntry): boolean {
+ return entry.attempts >= QUARANTINE_ATTEMPTS;
+}
+
+/** Record one failure; a quarantined entry gets its next retry time. */
+export function recordFailedAttempt(ledger: FailedLedger, stub: ConversationStub, nowMs: number): FailedEntry {
+ const updatedAt = stub.updatedAt ?? '';
+ const prior = ledger[stub.id];
+ const attempts = (prior?.updatedAt === updatedAt ? prior.attempts : 0) + 1;
+ const backoff = attempts >= QUARANTINE_ATTEMPTS ? HOLD_BACKOFF_MS[attempts - QUARANTINE_ATTEMPTS] ?? HOLD_DAILY_MS : 0;
+ const orgId = stub.orgId ?? prior?.orgId;
+ const entry: FailedEntry = {
+ attempts,
+ updatedAt,
+ lastAttemptAt: new Date(nowMs).toISOString(),
+ ...(backoff ? { nextRetryAt: new Date(nowMs + backoff).toISOString() } : {}),
+ ...(orgId ? { orgId } : {}),
+ };
+ ledger[stub.id] = entry;
+ return entry;
+}
+
+const isDue = (entry: FailedEntry, nowIso: string) => !entry.nextRetryAt || entry.nextRetryAt <= nowIso;
+
+export interface FetchPlan {
+ /** Listed conversations to fetch (new, edited, or failed but not quarantined). */
+ listed: ConversationStub[];
+ /** Due retained failures, fetched by id (oldest-due first). */
+ retries: ConversationStub[];
+ /** Listed new work the `--limit` cap left for a later run. */
+ capped: boolean;
+ skippedUnchanged: number;
+ /** Quarantined, not due yet. */
+ waiting: string[];
+ /** Legacy entries without an org on an org-routed provider; need `--full`. */
+ held: string[];
+}
+
+/**
+ * Decide what one run fetches. `--full` fetches every listed conversation;
+ * retained failures it does not list are left to the caller (a complete
+ * listing that omits them means the provider no longer has them).
+ */
+export function planConnectorFetch(input: {
+ stubs: ConversationStub[];
+ synced: Record<string, string>;
+ failed: FailedLedger;
+ full: boolean;
+ limit?: number;
+ nowMs: number;
+ routesByOrg: boolean;
+}): FetchPlan {
+ const nowIso = new Date(input.nowMs).toISOString();
+ const listedIds = new Set(input.stubs.map((s) => s.id));
+ const listed: ConversationStub[] = [];
+ const due: Array<{ stub: ConversationStub; at: string }> = [];
+ const waiting: string[] = [];
+ const held: string[] = [];
+ let skippedUnchanged = 0;
+
+ for (const stub of input.stubs) {
+ if (input.full) { listed.push(stub); continue; }
+ if (stub.updatedAt && input.synced[stub.id] === stub.updatedAt) { skippedUnchanged++; continue; }
+ const entry = input.failed[stub.id];
+ if (entry && entry.updatedAt === (stub.updatedAt ?? '') && isQuarantined(entry)) {
+ if (isDue(entry, nowIso)) due.push({ stub, at: entry.nextRetryAt ?? '' });
+ else waiting.push(stub.id);
+ continue;
+ }
+ listed.push(stub);
+ }
+ if (!input.full) {
+ for (const [id, entry] of Object.entries(input.failed)) {
+ if (listedIds.has(id)) continue;
+ if (input.routesByOrg && !entry.orgId) { held.push(id); continue; }
+ if (!isDue(entry, nowIso)) { waiting.push(id); continue; }
+ due.push({ stub: { id, updatedAt: entry.updatedAt, ...(entry.orgId ? { orgId: entry.orgId } : {}) }, at: entry.nextRetryAt ?? '' });
+ }
+ }
+
+ due.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
+ let retries = due.slice(0, RETRY_BUDGET).map((d) => d.stub);
+ let take = listed.length;
+ if (input.limit !== undefined) {
+ const reserved = Math.min(retries.length, Math.ceil(input.limit / 2));
+ take = Math.min(listed.length, input.limit - reserved);
+ retries = retries.slice(0, input.limit - take);
+ }
+ return { listed: listed.slice(0, take), retries, capped: take < listed.length, skippedUnchanged, waiting, held };
+}
+
+export async function readFailedLedger(engine: BrainEngine, provider: ConnectorProviderName, sourceId: string): Promise<FailedLedger> {
+ const raw = await engine.getConfig(connectorSourceKey(provider, sourceId, 'failed'));
+ if (!raw) return {};
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as FailedLedger : {};
+ } catch {
+ return {};
+ }
+}
+
+/** The full-repair command a held or pruned failure needs (it re-downloads the whole history; ask first). */
+export const fullSyncArgv = (provider: ConnectorProviderName, sourceId: string): string[] =>
+ ['gbrain', 'connectors', 'sync', provider, '--full', '--source', sourceId];
diff --git a/src/core/connectors/providers/claude.ts b/src/core/connectors/providers/claude.ts
index 1319d2e6a2..bb4af5b0a2 100644
--- a/src/core/connectors/providers/claude.ts
+++ b/src/core/connectors/providers/claude.ts
@@ -15,7 +15,9 @@
* (→ auth_required, no refreshAccessToken). Chat-capable orgs are discovered
* lazily and memoized per client instance (each sync builds a fresh client →
* account-safe); every one is listed, and each conversation is fetched from
- * the org that listed it. The list is paged with limit/offset (C-17).
+ * the org that listed it: stubs carry `orgId`, which the sync records with a
+ * failed conversation so a later retry by id reaches the same org (#6387).
+ * The list is paged with limit/offset (C-17).
*/
import type { HostSpecTarget } from '../../bootstrap/host-specs.ts';
@@ -109,6 +111,7 @@ export const claudeProvider: ChatHistoryProvider = {
strategies: ['browser-session'],
specTarget: CLAUDE_WEB_API_SPEC_TARGET,
baseUrl: CLAUDE_BASE_URL,
+ routesByOrg: true,
async authHeaders(cred: ConnectorCredential): Promise<Record<string, string>> {
const h: Record<string, string> = {};
@@ -177,6 +180,7 @@ export const claudeProvider: ChatHistoryProvider = {
title: typeof r.name === 'string' ? r.name : undefined,
updatedAt,
createdAt: toIso(r.created_at) || undefined,
+ orgId: org,
});
}
if (fresh === 0 || allOlder) break;
@@ -194,9 +198,9 @@ export const claudeProvider: ChatHistoryProvider = {
async fetchConversation(
client: ConnectorClient,
id: string,
- opts: { signal?: AbortSignal } = {},
+ opts: { signal?: AbortSignal; orgId?: string } = {},
): Promise<Record<string, unknown>> {
- const org = memoConversationOrg.get(client)?.get(id) ?? (await resolveOrgs(client, opts.signal))[0];
+ const org = opts.orgId ?? memoConversationOrg.get(client)?.get(id) ?? (await resolveOrgs(client, opts.signal))[0];
const conv = await client.fetchJSON<Record<string, unknown>>(
`/api/organizations/${encodeURIComponent(org)}/chat_conversations/${encodeURIComponent(id)}?tree=True&rendering_mode=messages`,
{ signal: opts.signal },
diff --git a/src/core/connectors/sync.ts b/src/core/connectors/sync.ts
index e4820d359d..07b678d73c 100644
--- a/src/core/connectors/sync.ts
+++ b/src/core/connectors/sync.ts
@@ -14,10 +14,15 @@
* a `synced` ledger (conversation id → ingested updatedAt) that lets a capped
* `--limit` run move on to older conversations, and a `failed` ledger. A
* conversation that fails to fetch OR to ingest QUARANTINE_ATTEMPTS times at
- * the same updatedAt is quarantined: reported, no longer re-fetched, and no
- * longer holding the watermark back. An edit (new updatedAt) or `--full`
- * retries it. Ingest outcomes are attributed per conversation (session id =
- * conversation id), so one failing conversation never blocks its batch.
+ * the same updatedAt is quarantined: it no longer holds the watermark back,
+ * but its entry stays until it imports and it is retried by id on a backoff
+ * even after the watermark passes it (#6387, see failed-ledger.ts). While any
+ * entry is unresolved the run reports `partial` with `unresolved`. An edit
+ * (new updatedAt) or `--full` retries it at once; a `--full` listing that no
+ * longer contains it drops it as `gone`. Aborts and auth stops never count as
+ * a conversation's failure. Ingest outcomes are attributed per conversation
+ * (session id = conversation id), so one failing conversation never blocks
+ * its batch.
*
* STATE LIVES IN CONFIG SCALARS (`connectors.<p>.source.<id>.*`), NOT
* op_checkpoint: op_checkpoint stores a completed-KEY set with no scalar since,
@@ -37,6 +42,7 @@ import { getConnectorProvider } from './registry.ts';
import { resolveCredential } from './credentials.ts';
import { CONNECTOR_SPOOL_BATCH, pruneSpool, removeSpool, writeSpool } from './spool.ts';
import type { ChatHistoryProvider, ConnectorProviderName, ConversationStub } from './types.ts';
+import { QUARANTINE_ATTEMPTS, fullSyncArgv, planConnectorFetch, readFailedLedger, recordFailedAttempt } from './failed-ledger.ts';
import {
authErrorAtKey,
connectorSourceKey,
@@ -47,8 +53,7 @@ import {
} from './config-keys.ts';
export const CONNECTOR_SYNC_VERSION = 1;
-/** Failed fetches or ingests at one updatedAt before a conversation is quarantined. */
-export const QUARANTINE_ATTEMPTS = 3;
+export { QUARANTINE_ATTEMPTS };
export type ConnectorSyncStatus =
| 'success'
@@ -86,8 +91,14 @@ export interface ConnectorSyncResult {
watermarkAdvancedTo?: string;
/** Listed conversations skipped because this source already ingested that updatedAt. */
skippedUnchanged: number;
- /** Conversation ids quarantined after repeated fetch or ingest failures (not re-fetched until edited). */
+ /** Conversation ids quarantined after repeated fetch or ingest failures (retried by id on a backoff). */
quarantined: string[];
+ /** Conversations in the failed ledger after this run: not archived yet (#6387). */
+ unresolved: number;
+ /** Unresolved conversations that only a `--full` sync can retry (recorded before their org was). */
+ held: string[];
+ /** Failed conversations a complete `--full` listing no longer contains; dropped from the ledger. */
+ gone: string[];
spoolPaths: string[];
embedKickoff: EmbedKickoffOutcome;
hint?: string;
@@ -183,6 +194,9 @@ export async function runConnectorSync(
fetchErrors: 0,
skippedUnchanged: 0,
quarantined: [],
+ unresolved: 0,
+ held: [],
+ gone: [],
spoolPaths: [],
embedKickoff: 'none',
};
@@ -223,7 +237,7 @@ export async function runConnectorSync(
const syncedKey = connectorSourceKey(opts.provider, sourceId, 'synced');
const failedKey = connectorSourceKey(opts.provider, sourceId, 'failed');
const synced = await readLedger<string>(engine, syncedKey);
- const failed = await readLedger<{ attempts: number; updatedAt: string }>(engine, failedKey);
+ const failed = await readFailedLedger(engine, opts.provider, sourceId);
const saveLedgers = async () => {
await engine.setConfig(syncedKey, JSON.stringify(synced));
await engine.setConfig(failedKey, JSON.stringify(failed));
@@ -251,32 +265,38 @@ export async function runConnectorSync(
}
base.listed = stubs.length;
- if (stubs.length === 0 && !listErrored) {
+ // A complete --full listing is the provider's whole history: a failed
+ // conversation it no longer contains cannot be archived any more.
+ if (opts.full && !listErrored && !opts.dryRun) {
+ const listedIds = new Set(stubs.map(s => s.id));
+ for (const id of Object.keys(failed)) {
+ if (listedIds.has(id)) continue;
+ delete failed[id];
+ base.gone.push(id);
+ }
+ if (base.gone.length) await saveLedgers();
+ }
+
+ if (stubs.length === 0 && !listErrored && Object.keys(failed).length === 0) {
await writeConnectorState(engine, opts.provider, sourceId, 'last_sync_at', new Date(now()).toISOString());
return { ...base, status: 'nothing_new' };
}
- // Skip what this source already holds and what is quarantined, BEFORE the
- // cap, so a capped run reaches conversations earlier runs did not.
- const quarantined: string[] = [];
- const pending = stubs.filter(stub => {
- if (opts.full) return true;
- if (stub.updatedAt && synced[stub.id] === stub.updatedAt) return false;
- const failure = failed[stub.id];
- if (failure && failure.updatedAt === (stub.updatedAt ?? '') && failure.attempts >= QUARANTINE_ATTEMPTS) {
- quarantined.push(stub.id);
- return false;
- }
- return true;
+ // Skip what this source already holds and what waits on its retry backoff,
+ // BEFORE the cap, so a capped run reaches conversations earlier runs did
+ // not; due retained failures get reserved slots under the cap (#6387).
+ const plan = planConnectorFetch({
+ stubs, synced, failed, full: !!opts.full, limit: opts.limit, nowMs: now(), routesByOrg: !!provider.routesByOrg,
});
- base.skippedUnchanged = stubs.length - pending.length - quarantined.length;
-
- // Apply the per-run fetch cap (a cap ⇒ NOT a clean run).
- const capped = typeof opts.limit === 'number' && pending.length > opts.limit;
- const toFetch = capped ? pending.slice(0, opts.limit) : pending;
+ const quarantined = [...plan.waiting];
+ base.skippedUnchanged = plan.skippedUnchanged;
+ base.held = plan.held;
+ const capped = plan.capped;
+ const retryIds = new Set(plan.retries.map(s => s.id));
+ const toFetch = [...plan.retries, ...plan.listed];
if (opts.dryRun) {
- return { ...base, status: 'dry_run', listed: stubs.length, hint: `${toFetch.length} conversation(s) would be fetched` };
+ return { ...base, status: 'dry_run', listed: stubs.length, unresolved: Object.keys(failed).length, hint: `${toFetch.length} conversation(s) would be fetched` };
}
// FETCH details + spool + ingest, in batches (memory-bounded; banks progress).
@@ -291,21 +311,24 @@ export async function runConnectorSync(
let partsDeletedTotal = 0;
let allBatchesClean = true;
let anyDrift = false;
+ let aborted = false;
const spoolFormat = provider.spoolFormat; // capture: nested closures lose narrowing
const batches = chunk(toFetch, CONNECTOR_SPOOL_BATCH);
- for (let bi = 0; bi < batches.length; bi++) {
+ for (let bi = 0; bi < batches.length && !aborted; bi++) {
const batch = batches[bi];
const convs: Array<Record<string, unknown>> = [];
const convStubs: ConversationStub[] = [];
for (const stub of batch) {
if (opts.signal?.aborted) break;
try {
- convs.push(await provider.fetchConversation(client, stub.id, { signal: opts.signal }));
+ convs.push(await provider.fetchConversation(client, stub.id, { signal: opts.signal, orgId: stub.orgId }));
convStubs.push(stub);
fetched++;
opts.onProgress?.({ phase: 'fetch', listed: stubs.length, fetched, imported: importedTotal });
} catch (e) {
+ // A cancelled run says nothing about the conversation: no strike.
+ if (opts.signal?.aborted) { aborted = true; break; }
const term = classifyThrow(e);
if (term === 'auth_required') {
await stampAuthError(engine, opts.provider, now);
@@ -327,13 +350,15 @@ export async function runConnectorSync(
if (convs.length) await ingestBatch();
await saveLedgers();
- /** Count one failure; quarantined conversations stop blocking the watermark. */
+ /**
+ * Count one failure; quarantined conversations stop blocking the
+ * watermark, and a retry by id never blocked it (the watermark describes
+ * listed history).
+ */
function recordFailure(stub: ConversationStub): number {
- const updatedAt = stub.updatedAt ?? '';
- const attempts = (failed[stub.id]?.updatedAt === updatedAt ? failed[stub.id].attempts : 0) + 1;
- failed[stub.id] = { attempts, updatedAt };
+ const { attempts } = recordFailedAttempt(failed, stub, now());
if (attempts >= QUARANTINE_ATTEMPTS) quarantined.push(stub.id);
- else blockingFailures++;
+ else if (!retryIds.has(stub.id)) blockingFailures++;
return attempts;
}
@@ -398,11 +423,11 @@ export async function runConnectorSync(
if (clean && maxUpdatedAt && maxUpdatedAt !== watermark) {
await writeConnectorState(engine, opts.provider, sourceId, 'watermark_iso', maxUpdatedAt);
base.watermarkAdvancedTo = maxUpdatedAt;
- // Conversations older than the next run's list window are never listed
- // again, so their ledger entries are dead weight.
+ // Synced conversations older than the next run's list window are never
+ // listed again, so their entries are dead weight. Failed entries stay
+ // until they import (#6387): they are the only record of the omission.
const floor = subtractDays(maxUpdatedAt, windowDays, now);
for (const [id, updatedAt] of Object.entries(synced)) if (updatedAt < floor) delete synced[id];
- for (const [id, entry] of Object.entries(failed)) if (entry.updatedAt < floor) delete failed[id];
await saveLedgers();
}
@@ -429,8 +454,19 @@ export async function runConnectorSync(
// Prune the spool dir (belt-and-suspenders; batches already removed inline).
pruneSpool(opts.provider, 0);
+ base.unresolved = Object.keys(failed).length;
+ if (base.unresolved > 0) {
+ base.hint =
+ `${base.unresolved} conversation(s) not archived yet; sync retries them automatically ` +
+ `(\`gbrain connectors status ${opts.provider} --json\` lists them).` +
+ (base.held.length
+ ? ` ${base.held.length} recorded before their organization was tracked need one full re-sync, which ` +
+ `re-downloads the whole history: ask the user, then run \`${fullSyncArgv(opts.provider, sourceId).join(' ')}\`.`
+ : '');
+ }
+
base.status =
- fetchErrors > 0 || capped || !allBatchesClean || listErrored
+ fetchErrors > 0 || capped || !allBatchesClean || listErrored || aborted || base.unresolved > 0
? 'partial'
: importedTotal === 0
? 'nothing_new'
diff --git a/src/core/connectors/types.ts b/src/core/connectors/types.ts
index e1c4cfe7ad..af1335485d 100644
--- a/src/core/connectors/types.ts
+++ b/src/core/connectors/types.ts
@@ -73,6 +73,8 @@ export interface ConversationStub {
/** ISO 8601 UTC last-update time — the axis the watermark compares against. */
updatedAt: string;
createdAt?: string;
+ /** The organization that listed it, for providers that route detail fetches by org (claude). */
+ orgId?: string;
}
/** Verdict from a provider `probe()` — did the credential reach history? */
@@ -100,6 +102,12 @@ export interface ChatHistoryProvider {
oauth?: OAuthPkceConfig;
/** Compile-time base origin; overridable in tests via `baseUrlOverride`. */
baseUrl: string;
+ /**
+ * True when a detail fetch must name the organization that listed the
+ * conversation (stubs carry `orgId`). A retained failure without a recorded
+ * org is then never retried by id; it waits for a `--full` sync (#6387).
+ */
+ routesByOrg?: boolean;
/**
* Build the auth headers for a request from a resolved credential. Default
* shape is `{ cookie, authorization: Bearer <accessToken> }` (either/both).
@@ -128,12 +136,13 @@ export interface ChatHistoryProvider {
* Fetch one conversation, normalized to the provider's NATIVE EXPORT object
* shape — the exact shape the `spoolFormat` adapter already parses. Throws a
* drift error when the payload lacks its required shape (missing `mapping`
- * for chatgpt, missing `chat_messages` for claude).
+ * for chatgpt, missing `chat_messages` for claude). `orgId` (from the
+ * stub or the failed ledger) routes the fetch on `routesByOrg` providers.
*/
fetchConversation(
client: ConnectorClient,
id: string,
- opts?: { signal?: AbortSignal },
+ opts?: { signal?: AbortSignal; orgId?: string },
): Promise<Record<string, unknown>>;
/** Paste-in credential-capture instructions for the browser-session lane. */
sessionInstructions(): string;
diff --git a/test/e2e/connectors-ingest-failure-pglite.test.ts b/test/e2e/connectors-ingest-failure-pglite.test.ts
index 977080f327..9076ed83e2 100644
--- a/test/e2e/connectors-ingest-failure-pglite.test.ts
+++ b/test/e2e/connectors-ingest-failure-pglite.test.ts
@@ -103,6 +103,8 @@ describe('connector ingest failures', () => {
expect(results[2].quarantined).toEqual(['c-1']);
expect(results[2].watermarkAdvancedTo).toBe(new Date((T0 + 30) * 1000).toISOString());
expect(results[3].fetched).toBe(0);
- expect(results[3].status).toBe('nothing_new');
+ // #6387: the quarantined conversation is still unresolved, so the run is partial.
+ expect(results[3].status).toBe('partial');
+ expect(results[3].unresolved).toBe(1);
});
});
diff --git a/test/e2e/connectors-sync-checkpoints-pglite.test.ts b/test/e2e/connectors-sync-checkpoints-pglite.test.ts
index 59e6fcfef0..9041bb4b0c 100644
--- a/test/e2e/connectors-sync-checkpoints-pglite.test.ts
+++ b/test/e2e/connectors-sync-checkpoints-pglite.test.ts
@@ -4,6 +4,13 @@
* progress across runs, and one permanently failing conversation is
* quarantined instead of freezing the watermark forever.
*
+ * #6387: a failed conversation stays in the `failed` ledger until it imports,
+ * even after the watermark passes it, and is retried by id on a backoff
+ * (inside a per-run budget that `--limit` cannot starve), so recovering at
+ * the provider is enough to archive it. #6388: a long message keeps its tail.
+ * Both describe the installed-state recovery: an archive written before the
+ * fix recovers with one (consent-gated) `connectors sync --full`.
+ *
* Real ConnectorClient against the scriptable fixture backend, real ingest,
* isolated GBRAIN_HOME. No network, no provider spend.
*/
@@ -15,8 +22,10 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { runConnectorSync } from '../../src/core/connectors/sync.ts';
import { saveCredential } from '../../src/core/connectors/credentials.ts';
-import { readConnectorState, watermarkKey } from '../../src/core/connectors/config-keys.ts';
+import { connectorSourceKey, readConnectorState, watermarkKey } from '../../src/core/connectors/config-keys.ts';
import { CHATGPT_BASE_URL } from '../../src/core/connectors/providers/chatgpt.ts';
+import { CLAUDE_BASE_URL } from '../../src/core/connectors/providers/claude.ts';
+import { runTranscriptsIngest } from '../../src/core/transcripts/ingest.ts';
import {
type FixtureConversation,
type FixtureState,
@@ -58,16 +67,26 @@ function conv(id: string, updateTime: number, marker = id): FixtureConversation
turns: [{ role: 'user', text: `question ${marker}` }, { role: 'assistant', text: `answer ${marker}` }] };
}
-async function run(state: FixtureState, opts: Record<string, unknown> = {}) {
+interface RunExtras {
+ nowMs?: number;
+ runIngest?: typeof runTranscriptsIngest;
+ onFetch?: (url: string) => void;
+}
+
+async function run(state: FixtureState, opts: Record<string, unknown> = {}, extras: RunExtras = {}) {
const srv = startFixture(chatgptHandler(state));
try {
return await runConnectorSync(engine, {
provider: 'chatgpt',
sourceId: 'default',
deps: {
- fetchImpl: (url, init) => fetch(url.replace(CHATGPT_BASE_URL, srv.baseUrl), init),
- now: () => NOW_MS,
+ fetchImpl: (url, init) => {
+ extras.onFetch?.(url);
+ return fetch(url.replace(CHATGPT_BASE_URL, srv.baseUrl), init);
+ },
+ now: () => extras.nowMs ?? NOW_MS,
sleep: () => Promise.resolve(),
+ ...(extras.runIngest ? { runIngest: extras.runIngest } : {}),
},
...(opts as object),
});
@@ -76,6 +95,28 @@ async function run(state: FixtureState, opts: Record<string, unknown> = {}) {
}
}
+const HOUR = 3_600_000;
+const DAY_S = 86_400;
+
+async function failedLedger(provider: 'chatgpt' | 'claude' = 'chatgpt'): Promise<Record<string, { attempts: number; updatedAt: string; nextRetryAt?: string; orgId?: string }>> {
+ return JSON.parse((await engine.getConfig(connectorSourceKey(provider, 'default', 'failed'))) || '{}');
+}
+
+async function hasText(marker: string, provider = 'chatgpt'): Promise<boolean> {
+ const rows = await engine.executeRaw<{ n: number }>(
+ `SELECT count(*)::int AS n FROM pages WHERE slug LIKE $1 AND deleted_at IS NULL AND compiled_truth LIKE $2`,
+ [`conversations/${provider}/%`, `%${marker}%`]);
+ return rows[0].n > 0;
+}
+
+/** Fail `ids` until quarantine (QUARANTINE_ATTEMPTS runs at NOW_MS); the watermark then passes them. */
+async function quarantine(state: FixtureState, ids: string[], opts: Record<string, unknown> = {}) {
+ for (const id of ids) state.script.push({ pathIncludes: `/backend-api/conversation/${id}`, status: 404, body: { error: 'flaky' } });
+ const results = [];
+ for (let k = 0; k < 3; k++) results.push(await run(state, opts));
+ return results;
+}
+
async function conversationPages(sourceId: string): Promise<number> {
const rows = await engine.executeRaw<{ n: number }>(
`SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug LIKE 'conversations/chatgpt/%' AND deleted_at IS NULL`, [sourceId]);
@@ -134,7 +175,9 @@ describe('connector checkpoints', () => {
expect(results[2].watermarkAdvancedTo).toBe(new Date((T0 + 30) * 1000).toISOString());
expect(results[2].quarantined).toEqual(['c-1']);
expect(results[3].fetched).toBe(0);
- expect(results[3].status).toBe('nothing_new');
+ // #6387: a quarantined conversation is unresolved, not "nothing new".
+ expect(results[3].status).toBe('partial');
+ expect(results[3].unresolved).toBe(1);
expect(state.hits['detail:c-2']).toBe(1);
expect(state.hits['detail:c-3']).toBe(1);
@@ -158,3 +201,245 @@ describe('connector checkpoints', () => {
expect(rows).toEqual([{ has_new: true }]);
});
});
+
+describe('#6387 failed conversations are retained until they import', () => {
+ test('an old conversation quarantined during backfill imports once the provider recovers, after the watermark passed it', async () => {
+ const state = newFixtureState([conv('old-failure', T0 - 30 * DAY_S), conv('new-ok', T0)]);
+ const first = await quarantine(state, ['old-failure']);
+ expect(first[2].quarantined).toEqual(['old-failure']);
+ expect(first[2].watermarkAdvancedTo).toBe(new Date(T0 * 1000).toISOString());
+ expect(first[2].status).toBe('partial');
+ expect(Object.keys(await failedLedger())).toEqual(['old-failure']);
+
+ state.script = [];
+ const recovered = await run(state, {}, { nowMs: NOW_MS + 2 * HOUR });
+ expect(recovered.fetched).toBe(1);
+ expect(recovered.status).toBe('success');
+ expect(recovered.unresolved).toBe(0);
+ expect(await conversationPages('default')).toBe(2);
+ expect(await failedLedger()).toEqual({});
+ expect(state.hits['detail:new-ok']).toBe(1);
+ });
+
+ test('an empty listing still retries a due failure, and reports partial while it is not due yet', async () => {
+ const state = newFixtureState([conv('old-1', T0 - 30 * DAY_S), conv('new-1', T0)]);
+ await quarantine(state, ['old-1'], { windowDays: 0 });
+ state.script = [];
+
+ const notDue = await run(state, { windowDays: 0 }, { nowMs: NOW_MS + 60_000 });
+ expect(notDue.listed).toBe(0);
+ expect(notDue.fetched).toBe(0);
+ expect(notDue.status).toBe('partial');
+ expect(notDue.unresolved).toBe(1);
+ expect(state.hits['detail:old-1']).toBeUndefined();
+
+ const due = await run(state, { windowDays: 0 }, { nowMs: NOW_MS + 2 * HOUR });
+ expect(due.listed).toBe(0);
+ expect(due.fetched).toBe(1);
+ expect(due.status).toBe('success');
+ expect(await conversationPages('default')).toBe(2);
+ });
+
+ test('at most 10 retries run per sync, oldest-due first, so the rest get their turn next', async () => {
+ const olds = Array.from({ length: 12 }, (_, i) => conv(`old-${i}`, T0 - (30 + i) * DAY_S));
+ const state = newFixtureState([...olds, conv('new-1', T0)]);
+ await quarantine(state, olds.map(c => c.id));
+ // The client retries a 404 within one fetch, so count distinct conversations.
+ const detailIds = (urls: string[]) => [...new Set(urls.flatMap(u => u.match(/\/backend-api\/conversation\/([^/?]+)$/)?.[1] ?? []))];
+
+ const fetchedA: string[] = [];
+ const a = await run(state, {}, { nowMs: NOW_MS + 2 * HOUR, onFetch: u => fetchedA.push(u) });
+ expect(detailIds(fetchedA)).toHaveLength(10);
+ expect(a.unresolved).toBe(12);
+ expect(a.status).toBe('partial');
+
+ const fetchedB: string[] = [];
+ await run(state, {}, { nowMs: NOW_MS + 2 * HOUR + 60_000, onFetch: u => fetchedB.push(u) });
+ expect(detailIds(fetchedB)).toHaveLength(2);
+ expect(new Set([...detailIds(fetchedA), ...detailIds(fetchedB)])).toEqual(new Set(olds.map(c => c.id)));
+ });
+
+ test('--limit keeps capacity for due retries while new conversations keep arriving', async () => {
+ const state = newFixtureState([conv('old-1', T0 - 30 * DAY_S), conv('new-0', T0)]);
+ await quarantine(state, ['old-1']);
+ state.script = [];
+ for (let i = 1; i <= 5; i++) state.conversations.push(conv(`fresh-${i}`, T0 + i * 10));
+
+ const r = await run(state, { limit: 3 }, { nowMs: NOW_MS + 2 * HOUR });
+ expect(state.hits['detail:old-1']).toBe(1);
+ expect(r.fetched).toBe(3);
+ expect(await failedLedger()).toEqual({});
+ expect(r.status).toBe('partial');
+ });
+
+ test('an abort mid-fetch is not counted against the conversation', async () => {
+ const state = newFixtureState([conv('c-1', T0 + 10), conv('c-2', T0 + 20)]);
+ const ac = new AbortController();
+ const r = await run(state, { signal: ac.signal }, {
+ onFetch: (url) => { if (url.includes('/backend-api/conversation/c-1')) ac.abort(); },
+ });
+ expect(r.watermarkAdvancedTo).toBeUndefined();
+ expect(await failedLedger()).toEqual({});
+ const next = await run(state);
+ expect(next.status).toBe('success');
+ expect(await conversationPages('default')).toBe(2);
+ });
+
+ test('an ingest that throws keeps the unresolved record', async () => {
+ const state = newFixtureState([conv('old-1', T0 - 30 * DAY_S), conv('new-1', T0)]);
+ await quarantine(state, ['old-1']);
+ state.script = [];
+ const broken: typeof runTranscriptsIngest = async () => { throw new Error('database went away'); };
+ await expect(run(state, {}, { nowMs: NOW_MS + 2 * HOUR, runIngest: broken })).rejects.toThrow(/database went away/);
+ expect(Object.keys(await failedLedger())).toEqual(['old-1']);
+ const r = await run(state, {}, { nowMs: NOW_MS + 2 * HOUR });
+ expect(r.status).toBe('success');
+ });
+
+ test('--full drops a failure whose conversation the provider no longer lists', async () => {
+ const state = newFixtureState([conv('old-1', T0 - 30 * DAY_S), conv('new-1', T0)]);
+ await quarantine(state, ['old-1']);
+ state.conversations = state.conversations.filter(c => c.id !== 'old-1');
+ const r = await run(state, { full: true }, { nowMs: NOW_MS + 60_000 });
+ expect(r.gone).toEqual(['old-1']);
+ expect(r.unresolved).toBe(0);
+ expect(await failedLedger()).toEqual({});
+ });
+
+ test('upgrade state: a failure pruned before the fix is recovered by connectors sync --full', async () => {
+ // Pre-fix brains: the watermark passed the conversation, the prune emptied the
+ // ledger, and the conversation was never imported. Nothing records it.
+ const state = newFixtureState([conv('new-ok', T0)]);
+ await run(state);
+ state.conversations.push(conv('lost-old', T0 - 30 * DAY_S));
+ await engine.setConfig(connectorSourceKey('chatgpt', 'default', 'failed'), '{}');
+
+ const ordinary = await run(state);
+ expect(ordinary.fetched).toBe(0);
+ expect(await conversationPages('default')).toBe(1);
+
+ const full = await run(state, { full: true });
+ expect(full.status).toBe('success');
+ expect(state.hits['detail:lost-old']).toBe(1);
+ expect(await conversationPages('default')).toBe(2);
+ });
+});
+
+describe('#6388 long messages through the connector', () => {
+ const longText = `${'x'.repeat(5000)}END-OF-MESSAGE-MARKER`;
+ const longConv = (text: string): FixtureConversation => ({
+ id: 'long-1', title: 'Long', createTime: T0 - 100, updateTime: T0,
+ turns: [{ role: 'user', text }, { role: 'assistant', text: 'ok' }],
+ });
+
+ test('a 5,000-character message is archived with its tail, and an unchanged rerun fetches nothing', async () => {
+ const state = newFixtureState([longConv(longText)]);
+ const r = await run(state);
+ expect(r.status).toBe('success');
+ expect(await hasText('END-OF-MESSAGE-MARKER')).toBe(true);
+ const again = await run(state);
+ expect(again.fetched).toBe(0);
+ });
+
+ test('upgrade state: a page archived truncated before the fix recovers with connectors sync --full', async () => {
+ // The pre-fix renderer kept the first 4,000 characters and the sync ledger
+ // recorded the conversation as synced at this updatedAt.
+ const state = newFixtureState([longConv(longText.slice(0, 4000))]);
+ await run(state);
+ state.conversations = [longConv(longText)];
+
+ const ordinary = await run(state);
+ expect(ordinary.fetched).toBe(0);
+ expect(await hasText('END-OF-MESSAGE-MARKER')).toBe(false);
+
+ const full = await run(state, { full: true });
+ expect(full.fetched).toBe(1);
+ expect(await hasText('END-OF-MESSAGE-MARKER')).toBe(true);
+ expect(await conversationPages('default')).toBe(1);
+ });
+});
+
+describe('#6387 Claude retries use the organization that listed the conversation', () => {
+ interface OrgConv { org: string; id: string; updateTime: number; fail?: boolean }
+
+ function twoOrgHandler(convs: OrgConv[], hits: string[]) {
+ return (req: Request): Response => {
+ const url = new URL(req.url);
+ const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status, headers: { 'content-type': 'application/json' } });
+ if (url.pathname === '/api/organizations') return json([{ uuid: 'org-a' }, { uuid: 'org-b' }]);
+ const list = url.pathname.match(/^\/api\/organizations\/([^/]+)\/chat_conversations$/);
+ if (list) {
+ if (Number(url.searchParams.get('offset') ?? '0') > 0) return json([]);
+ return json(convs.filter(c => c.org === list[1]).sort((a, b) => b.updateTime - a.updateTime).map(c => ({
+ uuid: c.id, name: c.id, created_at: new Date((c.updateTime - 100) * 1000).toISOString(), updated_at: new Date(c.updateTime * 1000).toISOString(),
+ })));
+ }
+ const detail = url.pathname.match(/^\/api\/organizations\/([^/]+)\/chat_conversations\/([^/]+)$/);
+ if (detail) {
+ hits.push(`${detail[1]}/${detail[2]}`);
+ const c = convs.find(x => x.org === detail[1] && x.id === detail[2]);
+ if (!c || c.fail) return json({ error: 'not found' }, 404);
+ return json({
+ uuid: c.id, name: c.id, created_at: new Date((c.updateTime - 100) * 1000).toISOString(), updated_at: new Date(c.updateTime * 1000).toISOString(),
+ chat_messages: [
+ { uuid: `${c.id}-m1`, sender: 'human', created_at: new Date((c.updateTime - 90) * 1000).toISOString(), text: `question ${c.id}` },
+ { uuid: `${c.id}-m2`, sender: 'assistant', created_at: new Date((c.updateTime - 80) * 1000).toISOString(), text: `answer ${c.id}` },
+ ],
+ });
+ }
+ return json({ error: 'unhandled' }, 404);
+ };
+ }
+
+ async function runClaude(convs: OrgConv[], hits: string[], opts: Record<string, unknown> = {}, nowMs = NOW_MS) {
+ const srv = startFixture(twoOrgHandler(convs, hits));
+ try {
+ return await runConnectorSync(engine, {
+ provider: 'claude', sourceId: 'default',
+ deps: { fetchImpl: (url, init) => fetch(url.replace(CLAUDE_BASE_URL, srv.baseUrl), init), now: () => nowMs, sleep: () => Promise.resolve() },
+ ...(opts as object),
+ });
+ } finally {
+ srv.stop();
+ }
+ }
+
+ beforeEach(() => {
+ saveCredential({ provider: 'claude', strategy: 'browser-session', cookie: 'sessionKey=fixture', savedAt: new Date(0).toISOString() });
+ });
+
+ test('a retained failure from the second organization is retried there', async () => {
+ const convs: OrgConv[] = [{ org: 'org-a', id: 'new-a', updateTime: T0 }, { org: 'org-b', id: 'old-b', updateTime: T0 - 30 * DAY_S, fail: true }];
+ const hits: string[] = [];
+ for (let k = 0; k < 3; k++) await runClaude(convs, hits);
+ expect((await failedLedger('claude'))['old-b']?.orgId).toBe('org-b');
+
+ convs[1].fail = false;
+ hits.length = 0;
+ const r = await runClaude(convs, hits, {}, NOW_MS + 2 * HOUR);
+ expect(hits).toEqual(['org-b/old-b']);
+ expect(r.status).toBe('success');
+ expect(await failedLedger('claude')).toEqual({});
+ });
+
+ test('a legacy failure with no recorded organization is held for --full, which recovers it', async () => {
+ const convs: OrgConv[] = [{ org: 'org-a', id: 'new-a', updateTime: T0 }, { org: 'org-b', id: 'old-b', updateTime: T0 - 30 * DAY_S }];
+ const hits: string[] = [];
+ await runClaude(convs.slice(0, 1), hits);
+ // A pre-fix ledger entry: no orgId, no retry schedule.
+ await engine.setConfig(connectorSourceKey('claude', 'default', 'failed'),
+ JSON.stringify({ 'old-b': { attempts: 3, updatedAt: new Date((T0 - 30 * DAY_S) * 1000).toISOString() } }));
+
+ hits.length = 0;
+ const held = await runClaude(convs, hits);
+ expect(hits).toEqual([]);
+ expect(held.held).toEqual(['old-b']);
+ expect(held.status).toBe('partial');
+ expect(held.hint).toContain('gbrain connectors sync claude --full');
+
+ const full = await runClaude(convs, hits, { full: true });
+ expect(hits).toContain('org-b/old-b');
+ expect(full.held).toEqual([]);
+ expect(await failedLedger('claude')).toEqual({});
+ });
+});
diff --git a/test/e2e/doctor-connectors-pglite.test.ts b/test/e2e/doctor-connectors-pglite.test.ts
index 5a8d9306e7..8f8ec07d93 100644
--- a/test/e2e/doctor-connectors-pglite.test.ts
+++ b/test/e2e/doctor-connectors-pglite.test.ts
@@ -1,6 +1,9 @@
/**
* doctor-connectors e2e (PGLite) — D3.2: re-auth-needed / stalled-sync / drift,
* gated on a credential + auto_sync. A manual-lane user is NEVER nagged.
+ * #6387: unresolved conversations warn "archive incomplete" (doctor and
+ * `connectors status`); a legacy Claude entry only `--full` can retry carries
+ * an ask-first fix.
*/
import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
@@ -10,7 +13,8 @@ import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import { connectorsHealthCheck } from '../../src/commands/doctor/checks/connectors.ts';
import { saveCredential } from '../../src/core/connectors/credentials.ts';
-import { authErrorAtKey, autoSyncKey, lastSyncAtKey } from '../../src/core/connectors/config-keys.ts';
+import { authErrorAtKey, autoSyncKey, connectorSourceKey, lastSyncAtKey } from '../../src/core/connectors/config-keys.ts';
+import { runConnectorStatus } from '../../src/commands/connectors/status.ts';
let engine: PGLiteEngine;
let tmp: string;
@@ -76,4 +80,38 @@ describe('connectorsHealthCheck', () => {
expect(c.status).toBe('warn');
expect(c.message).toMatch(/stall/i);
});
+
+ test('unresolved conversations → warn: archive incomplete, retried automatically, no fix needed', async () => {
+ saveCred('2026-08-25T00:00:00.000Z');
+ await engine.setConfig(connectorSourceKey('chatgpt', 'default', 'failed'),
+ JSON.stringify({ 'conv-1': { attempts: 3, updatedAt: '2026-07-01T00:00:00.000Z', nextRetryAt: '2026-10-11T00:00:00.000Z' } }));
+ const c = await connectorsHealthCheck(engine);
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('chatgpt: 1 unresolved conversation(s) — archive incomplete');
+ expect(c.fix).toBeUndefined();
+ });
+
+ test('a legacy Claude failure without an organization → ask-first --full fix; status lists it', async () => {
+ saveCredential({ provider: 'claude', strategy: 'browser-session', cookie: 'sessionKey=x', savedAt: '2026-08-25T00:00:00.000Z' });
+ await engine.setConfig(connectorSourceKey('claude', 'default', 'failed'),
+ JSON.stringify({ 'conv-legacy': { attempts: 3, updatedAt: '2026-07-01T00:00:00.000Z' } }));
+ const c = await connectorsHealthCheck(engine);
+ expect(c.status).toBe('warn');
+ expect(c.message).toContain('archive incomplete');
+ expect(c.fix?.argv).toEqual(['gbrain', 'connectors', 'sync', 'claude', '--full', '--source', 'default']);
+ expect(c.fix?.consent).toEqual(['credentials']);
+
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (msg: string) => { lines.push(msg); };
+ try {
+ await runConnectorStatus(engine, ['claude', '--json']);
+ } finally {
+ console.log = orig;
+ }
+ const out = JSON.parse(lines.join('\n'));
+ expect(out.providers[0].unresolved).toEqual([
+ { id: 'conv-legacy', attempts: 3, updated_at: '2026-07-01T00:00:00.000Z', next_retry_at: null, needs_full_sync: true },
+ ]);
+ });
});