Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(transcripts): one refused or pending part no longer aborts the ingest or the connector batch (GBRA-130 A-2)

garrytan25e8569a482a
diff --git a/docs/architecture/key-files/core-services-3.md b/docs/architecture/key-files/core-services-3.md
index 7784802dbd..202c4a9471 100644
--- a/docs/architecture/key-files/core-services-3.md
+++ b/docs/architecture/key-files/core-services-3.md
@@ -13,7 +13,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/think/intent.ts` + `src/core/think/entity-extract.ts` — pure `classifyIntent(question)` returns `'temporal' | 'knowledge_update' | 'other'` (regex-first, no LLM, `'other'` fast path short-circuits with zero SQL). `extractCandidateEntities(question, retrievedSlugs)` pulls high-precision candidates from retrieved entity-prefix slugs (`people/`, `companies/`, `organizations/`) and medium-precision noun phrases. Stop-word boundaries + leading-verb stripper handle "When did I last meet Marco" → `marco`. Both consumed by `runThink` and the LongMemEval harness so the two paths cannot drift. Pinned by `test/think-intent.test.ts` and `test/think-entity-extract.test.ts`.
-- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message (through 0.152) or `event_msg` item_completed with item.type UserMessage, text blocks only (0.153+, #5163; a turn recorded in both shapes is kept once, other item types incl. AgentMessage skipped), assistant from `response_item` output_text; a file with assistant turns and zero user turns sets `FileDiagnostics.userTurnsMissing` (codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats as `degraded`/`no_user_turns` on whole-file reads (pinned by `test/codex-rollout-0154.serial.test.ts`); role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), message-boundary splitting at `PART_TARGET_BYTES` = 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (failed sessions skip; integrity failures abort the run), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).
+- `src/core/transcripts/` (directory) — the transcript-adapter seam. `types.ts`: the `TranscriptAdapter` contract — `parse(path): AsyncGenerator<ParsedSession, FileDiagnostics>` (one FILE may hold many sessions; the generator RETURN value carries bytes/skipped-lines/zero-session diagnostics so an empty file explains itself), format-specific byte caps (JSONL 50MB hard cap — the 10MB default in `claude-code-jsonl.ts` belongs to the hook-lane tail reader, not imports; monolithic export JSON rejects-not-truncates at 200MB), and the ONE `buildTranscriptSlug` helper (per-provider dirs matching the conversation-archive layout; id suffixes are sha256 prefixes of the session id — hash12 in slugs, hash16 for the dedup identity — never a cleaned prefix of the source id, which would let same-prefix session ids collide). `detect.ts`: adapter registry + head-sample detection (explicit format wins; symlinks lstat-rejected) + injectable `harnessRoots` (the confined discovery surface). Adapters, each with a DATED `SPEC_TARGET` + scrubbed fixture + `bytes>0 && sessions==0` drift alarm: `claude-code.ts` (thin wrapper over the shipped `claude-code-jsonl.ts`, which also exposes the full-file `parseClaudeSessionFile` with real per-message timestamps — hook-lane `parseTranscript` output is pinned byte-identical; owns `isClaudeCodeSubagentFile` (a literal `subagents` path segment at ANY depth + `agent-*.jsonl` basename — both `<session>/subagents/agent-*.jsonl` and the workflow-nested `<session>/subagents/workflows/<wf>/agent-*.jsonl` are all-sidechain, zero-turn files carrying the PARENT session id; a project slug containing "subagents" is one segment and never matches) and `isClaudeCodeWorkflowArtifactFile` (everything under `<session>/subagents/workflows/<wf>/` — the agent logs plus the `journal.jsonl` run log that matches no adapter format; a UUID-named session directly under `subagents/` stays discoverable); `discover.ts` and the CLI's `expandPaths` skip both, so they never read as gap-table backlog, drift, or `unknown format` errors that hold the since-last watermark frozen; the adapter sets `expectedEmpty` when zero accepted turn-shaped records and zero skipped lines remain after root metadata/sidechain and explicit non-human user-text filtering. Metadata-only, non-human-text-only, and all-subagent files are understood empties and do not freeze the watermark; accepted turn records that yield no text and unparseable lines still signal drift. Pinned by `test/claude-code-jsonl-origin.test.ts`), `codex.ts` (turn selection is STRUCTURAL: user turns from `event_msg` user_message (through 0.152) or `event_msg` item_completed with item.type UserMessage, text blocks only (0.153+, #5163; a turn recorded in both shapes is kept once, other item types incl. AgentMessage skipped), assistant from `response_item` output_text; a file with assistant turns and zero user turns sets `FileDiagnostics.userTurnsMissing` (codex and claude-code; E-N4), which ingest counts as drift and the session-end hook heartbeats as `degraded`/`no_user_turns` on whole-file reads (pinned by `test/codex-rollout-0154.serial.test.ts`); role user/developer response_items are injected preambles and never leak; identity is `payload.id` — the per-thread id codex embeds in the rollout filename — with `payload.session_id` (the ROOT session shared by every forked/subagent thread) only as the legacy fallback, and the FIRST `session_meta` header wins because a child rollout carries its inherited parent header later in the file; the hook lane's `parseCodexHookTranscript` follows the same two rules), `openclaw.ts` (session header + message lines; `.checkpoint.*.jsonl` snapshots rejected), `hermes.ts` (COPY-THEN-READ of state.db + wal/shm sidecars — readonly WAL opens need -shm write access and lock against a live writer; schema from the installed hermes-agent source; PROVISIONAL), `grok.ts` (Grok Build session dirs — structural turn selection, sidecar-aware discovery; see its own entry), `chatgpt-export.ts` (the `mapping`-tree current_node walk; branches dropped by design, orphaned parents terminate quietly, latest-leaf fallback; extracted conversations.json only) + `claude-export.ts` (flat chat_messages); both export adapters load through the shared `export-json.ts` (monolithic JSON over the cap REJECTS with a split hint; a zip or wrong-shape file gets the unzip-first hint) and give id-less conversations content-derived fallback ids so two id-less exports cannot dedup-skip or overwrite each other. `render.ts`: session → part pages — imessage-slack line format with the regex IMPORTED from `conversation-parser/builtins.ts` (round-trip pinned), REAL timestamps (missing ones carry forward; zero-timestamp sessions refused — provenance is never fabricated), anchor-shaped BODY lines backslash-escaped (hostile message content cannot forge speakers), quoted facts/takes fence-marker tokens backslash-escaped at the same per-message seam (`gbrain\:facts:begin` — a session that read another page cannot plant a live or unbalanced fence on the transcript page; every fence consumer is a substring matcher, so the escape lands inside the token), fail-closed redaction (secret-scan + `harvest-private-patterns.txt` user patterns, slack-channel default excluded because it eats issue refs; imperatives COUNTED into hash-covered `transcript_import` frontmatter, never content_flag), message-boundary splitting at `PART_TARGET_BYTES` = 45,000 bytes (0.9 × the 50,000-byte content-sanity warn line, so no part takes the oversize-warn branch; far under the embed-skip threshold) with 2-message overlap, part 1 keeps the base slug, `frontmatter.id` unique per part. `ingest.ts`: the engine-facing core — a session whose part-1 `frontmatter.id` already has a live page imports at that page's slug (a renamed or re-dated conversation updates in place instead of being skipped as a cross-slug duplicate), SESSION atomicity (a failed session records its `classifyItemFailure` code and the run continues; a part the coordinator accepted but has not published leaves the session pending under a request id derived from source, slug, revision and content, so a rerun waits on that write and a write that ended without committing is retried under the next attempt id; only run-scoped failures and the `item_failures_systemic` breaker abort the run, GBRA-130 A-2, pinned by `test/pathological/a2-transcripts-ingest.test.ts`), stale-part reconciliation (deletes `part > of` leftovers), session metadata banked in the base page's raw_data as the REDACTED copy and healed by content-compare even on hash-skipped re-runs (a run that died before `putRawData`, or a private pattern added after first import, repairs on the next pass), `cleanScan`/`maxSessionTs` for the watermark. `ingest-facts.ts`: ONE `runExtractConversationFactsCore` invocation (batch `slugs` selector) inside ONE `withBudgetTracker`, `isFactsExtractionEnabled` pre-checked. Pinned by `test/transcript-adapters.test.ts`, `test/transcript-render.test.ts`, `test/transcripts-retitle.test.ts`, `test/transcripts-ingest-pglite.test.ts`, `test/e2e/transcripts-writeback-fidelity.test.ts` (raw files through the adapters into the gold-extractor facts path).
- `src/core/verbs.ts` — MEMORY_VERBS v1: the four frozen protocol verbs (`remember`, `entity`, `synthesize`, `forget`) as first-class Operations, plus `MEMORY_VERBS_VERSION` (single source of truth, =1), `VERB_NAMES`, the hand-authored `RESPONSE_SCHEMAS` registry (Operation carries input params only; response shapes live here and conformance validates LIVE responses against them), and `ERROR_SCHEMA`. The extended `recall` op is defined in ops/facts.ts and registered through operations.ts. Its response registry advertises optional `budget_packing` policy/applied/reason and per-arm integer accounting without changing required default fields or protocol version; `test/protocol-document.test.ts` pins discovery and malformed metadata rejection. The `context_pack` and `delta` fact items advertise optional `fact_id` and `provenance` (#6146). The recall registry advertises optional `facts_order`, `facts_degraded` and per-fact `relevance` (question ranking). RUNTIME LEAF invariant: operations.ts spreads `verbOperations` into its array at module-eval time, so this file must never statically import operations.ts VALUES (type-only imports fine; handlers use dynamic import) — violating it causes a TDZ crash on whichever module evaluates second. Every verb error carries a populated `suggestion` + `protocol_version` (via `verbError` in operations.ts). The `forget` verb deliberately has NO cliHints (CLI_ONLY `forget` dispatches first and would shadow it). Frozen contract: docs/protocol/MEMORY_VERBS_v1.md; pinned by test/memory-verbs-conformance.test.ts.
- `src/core/verbs/conformance.ts` + `src/core/verbs/conformance-fixtures.ts` — the conformance runner core (transport-agnostic: minimal `ConformanceClient` = list_tools + call_tool) and the embedded fixture set. Deterministic by construction: shape/enum/behavior/round-trip checks only, never ranking quality. Validation is NON-STRICT on extra fields (additive-forever means unknown fields are always legal). Entity-card cases seed via put_page when the target exposes it and skip honestly on verbs-only targets; synthesize is cost-gated behind --synthesize. `validateAgainstSchema` is a minimal JSON-Schema-subset validator (type unions, required, properties, enum, const, items). Fixtures mirror to `test/fixtures/memory-verbs/cases.json` (BrainBench seeds; drift-guarded by the conformance test). The negative self-test (test/memory-verbs-conformance.test.ts) proves the runner FAILS a lying server.
diff --git a/docs/guides/chat-connectors.md b/docs/guides/chat-connectors.md
index a4756c09ee..e8ea6746bb 100644
--- a/docs/guides/chat-connectors.md
+++ b/docs/guides/chat-connectors.md
@@ -108,6 +108,16 @@ watermark, so the watermark can advance. Any other failed conversation keeps
the watermark where it is, so the next run lists it and tries again.
Re-imports are free (content-hash idempotency), so re-running is safe.
+One conversation the brain refuses (a typed refusal such as `source_changed`)
+fails alone: the rest of its batch still imports, and `gbrain connectors status
+<provider> --json` shows the refusal's `code` on its row. Only a failure of the
+run itself (a lost database connection, the writer unavailable, an abort)
+stops the sync. On a managed brain, a conversation whose write was accepted but
+has not published within the wait is listed under `pending`: it is not marked
+synced and holds the watermark, and the next sync waits on that same write
+instead of submitting a second one. If that write ends without committing, the
+next sync submits it again.
+
A failed conversation is never forgotten. It stays in the source's failed
ledger until it imports, even after the watermark passes it and the provider
stops listing it. Each sync retries up to 10 due failures by id, oldest first,
diff --git a/src/commands/connectors/status.ts b/src/commands/connectors/status.ts
index 5654c3bd82..d87519d17c 100644
--- a/src/commands/connectors/status.ts
+++ b/src/commands/connectors/status.ts
@@ -43,6 +43,7 @@ export async function runConnectorStatus(engine: BrainEngine, args: string[]): P
attempts: e.attempts,
updated_at: e.updatedAt,
next_retry_at: e.nextRetryAt ?? null,
+ ...(e.code ? { code: e.code } : {}),
needs_full_sync: !!prov.routesByOrg && !e.orgId,
}));
rows.push({
diff --git a/src/commands/transcripts.ts b/src/commands/transcripts.ts
index f502795728..5f4d35baf5 100644
--- a/src/commands/transcripts.ts
+++ b/src/commands/transcripts.ts
@@ -316,7 +316,7 @@ export function fmtSummary(r: TranscriptsIngestResult): string {
const byHarness = new Map<string, number>();
for (const f of r.files) {
for (const s of f.sessions) {
- if (!s.error && !s.skipped) byHarness.set(s.harness, (byHarness.get(s.harness) ?? 0) + 1);
+ if (!s.error && !s.skipped && !s.pending) byHarness.set(s.harness, (byHarness.get(s.harness) ?? 0) + 1);
}
}
const lines: string[] = [];
@@ -324,6 +324,7 @@ export function fmtSummary(r: TranscriptsIngestResult): string {
lines.push(
`sessions: ${r.sessionsImported} imported (${counts || 'none'}), ` +
`${r.sessionsFiltered} filtered, ${r.sessionsErrored} errored, ` +
+ (r.sessionsPending ? `${r.sessionsPending} pending, ` : '') +
(r.sessionsSkippedNoTimestamp ? `${r.sessionsSkippedNoTimestamp} skipped (no timestamps), ` : '') +
`${r.sessionsSeen} seen`,
);
@@ -331,6 +332,7 @@ export function fmtSummary(r: TranscriptsIngestResult): string {
`pages: ${r.pages.imported} imported, ${r.pages.skipped} unchanged` +
(r.pages.errored ? `, ${r.pages.errored} ERRORED` : '') +
(r.pages.planned ? `, ${r.pages.planned} planned (dry run)` : '') +
+ (r.pages.pending ? `, ${r.pages.pending} accepted and still publishing (the next run finishes them without a second write)` : '') +
(r.partsDeleted ? `, ${r.partsDeleted} stale parts deleted` : ''),
);
if (r.redactions > 0) lines.push(`redactions: ${r.redactions} secrets/patterns redacted before write`);
diff --git a/src/core/connectors/failed-ledger.ts b/src/core/connectors/failed-ledger.ts
index 05a0990ac4..5c02529b67 100644
--- a/src/core/connectors/failed-ledger.ts
+++ b/src/core/connectors/failed-ledger.ts
@@ -38,6 +38,8 @@ export interface FailedEntry {
/** Absent: due now. Set once the entry is quarantined. */
nextRetryAt?: string;
orgId?: string;
+ /** The typed code of the last ingest failure (a fetch failure records none). */
+ code?: string;
}
export type FailedLedger = Record<string, FailedEntry>;
@@ -47,7 +49,7 @@ export function isQuarantined(entry: FailedEntry): boolean {
}
/** Record one failure; a quarantined entry gets its next retry time. */
-export function recordFailedAttempt(ledger: FailedLedger, stub: ConversationStub, nowMs: number): FailedEntry {
+export function recordFailedAttempt(ledger: FailedLedger, stub: ConversationStub, nowMs: number, code: string | null = null): FailedEntry {
const updatedAt = stub.updatedAt ?? '';
const prior = ledger[stub.id];
const attempts = (prior?.updatedAt === updatedAt ? prior.attempts : 0) + 1;
@@ -59,6 +61,7 @@ export function recordFailedAttempt(ledger: FailedLedger, stub: ConversationStub
lastAttemptAt: new Date(nowMs).toISOString(),
...(backoff ? { nextRetryAt: new Date(nowMs + backoff).toISOString() } : {}),
...(orgId ? { orgId } : {}),
+ ...(code ? { code } : {}),
};
ledger[stub.id] = entry;
return entry;
diff --git a/src/core/connectors/sync.ts b/src/core/connectors/sync.ts
index 44ad639d3b..e403cbe662 100644
--- a/src/core/connectors/sync.ts
+++ b/src/core/connectors/sync.ts
@@ -94,6 +94,8 @@ export interface ConnectorSyncResult {
skippedUnchanged: number;
/** Conversation ids quarantined after repeated fetch or ingest failures (retried by id on a backoff). */
quarantined: string[];
+ /** Conversation ids whose write was accepted and is still publishing: not synced, and they hold the watermark. */
+ pending: 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). */
@@ -195,6 +197,7 @@ export async function runConnectorSync(
fetchErrors: 0,
skippedUnchanged: 0,
quarantined: [],
+ pending: [],
unresolved: 0,
held: [],
gone: [],
@@ -344,7 +347,7 @@ export async function runConnectorSync(
return { ...base, status: 'forbidden', listed: stubs.length, fetched, fetchErrors, spoolPaths };
}
fetchErrors++;
- const attempts = recordFailure(stub);
+ const attempts = recordFailure(stub, null);
log(`[connector] fetch error for ${stub.id} (attempt ${attempts}): ${e instanceof Error ? e.message : String(e)}`);
}
}
@@ -356,8 +359,8 @@ export async function runConnectorSync(
* watermark, and a retry by id never blocked it (the watermark describes
* listed history).
*/
- function recordFailure(stub: ConversationStub): number {
- const { attempts } = recordFailedAttempt(failed, stub, now());
+ function recordFailure(stub: ConversationStub, code: string | null): number {
+ const { attempts } = recordFailedAttempt(failed, stub, now(), code);
if (attempts >= QUARANTINE_ATTEMPTS) quarantined.push(stub.id);
else if (!retryIds.has(stub.id)) blockingFailures++;
return attempts;
@@ -388,10 +391,17 @@ export async function runConnectorSync(
for (const stub of convStubs) {
const session = sessions.get(stub.id);
if (fileFailed || session?.error) {
- const attempts = recordFailure(stub);
+ const attempts = recordFailure(stub, session?.code ?? null);
log(`[connector] ingest error for ${stub.id} (attempt ${attempts}): ${session?.error ?? 'spool file failed to ingest'}`);
continue;
}
+ // An accepted write still publishing is neither synced nor a failure: the next run waits on the same
+ // request (transcripts ingest derives its id), and until then the conversation holds the watermark.
+ if (session?.pending) {
+ base.pending.push(stub.id);
+ if (!retryIds.has(stub.id)) blockingFailures++;
+ continue;
+ }
if (stub.updatedAt) synced[stub.id] = stub.updatedAt;
delete failed[stub.id];
}
@@ -456,18 +466,9 @@ export async function runConnectorSync(
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.hint = unresolvedHint(base, opts.provider, sourceId) ?? base.hint;
base.status =
- fetchErrors > 0 || capped || !allBatchesClean || listErrored || aborted || base.unresolved > 0
+ fetchErrors > 0 || capped || !allBatchesClean || listErrored || aborted || base.unresolved > 0 || base.pending.length > 0
? 'partial'
: importedTotal === 0
? 'nothing_new'
@@ -475,6 +476,25 @@ export async function runConnectorSync(
return base;
}
+/** What the run left unarchived (failed or still publishing) and the command that shows it. */
+function unresolvedHint(base: ConnectorSyncResult, provider: ConnectorProviderName, sourceId: string): string | undefined {
+ const parts: string[] = [];
+ if (base.unresolved > 0) {
+ parts.push(
+ `${base.unresolved} conversation(s) not archived yet; sync retries them automatically ` +
+ `(\`gbrain connectors status ${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(provider, sourceId).join(' ')}\`.`
+ : ''));
+ }
+ if (base.pending.length) {
+ parts.push(`${base.pending.length} conversation(s) were accepted and are still publishing; the next sync `
+ + `finishes them without a second write (\`gbrain sources writer status --source ${sourceId} --json\` shows the queue).`);
+ }
+ return parts.length ? parts.join(' ') : undefined;
+}
+
export async function maybeKickoffEmbed(
engine: BrainEngine,
sourceId: string,
diff --git a/src/core/item-failure.ts b/src/core/item-failure.ts
index d6c6afddac..2f5887b5f1 100644
--- a/src/core/item-failure.ts
+++ b/src/core/item-failure.ts
@@ -27,6 +27,7 @@ import { acceptedPendingReceipt } from './persistence/accepted-pending.ts';
/** Every per-item loop that isolates its items, with the inventory row it fixes (reports/GBRA-130-inventory.md). */
export const ISOLATE_SITES = {
+ 'transcripts.ingest_session': 'A-2',
} as const satisfies Record<string, string>;
export type IsolateSite = keyof typeof ISOLATE_SITES;
diff --git a/src/core/transcripts/ingest.ts b/src/core/transcripts/ingest.ts
index 1f93c90036..3949a7234b 100644
--- a/src/core/transcripts/ingest.ts
+++ b/src/core/transcripts/ingest.ts
@@ -14,12 +14,18 @@
*
* Error taxonomy:
* - per-FILE: unreadable / unknown format / symlink → counted, run continues.
- * - per-SESSION: scan failure, oversize part, adapter throw → counted,
- * file continues.
- * - RUN-LEVEL (fail-closed integrity): importFromContent duplicate-lookup
- * or read-back failures and putRawData misses rethrow and abort the run.
- * Heuristic seam: import errors matching /too large|invalid byte
- * sequence/ stay per-session.
+ * - per-SESSION: every failure `classifyItemFailure` calls the item's
+ * (a coordinator refusal, an oversize part, an encoding error) is
+ * recorded on the session with its typed code; the file continues.
+ * - PENDING: a part whose write the coordinator accepted but has not
+ * published within the wait is a pending session: never an error, never
+ * imported, and it keeps the scan unclean. Its request id is derived from
+ * the source, slug, revision and content, so a rerun waits on the same
+ * write instead of admitting a duplicate; a write that ended without
+ * committing is retried under the next attempt's id.
+ * - RUN-LEVEL: run-scoped failures (connection lost, a failed transaction,
+ * the writer unavailable, an abort) stop the run unchanged, and so does
+ * the ItemRun breaker (`item_failures_systemic`) when most sessions fail.
*
* Watermark: the RESULT carries `cleanScan` (no errors anywhere, no limit
* truncation) + `maxSessionTs`; the COMMAND advances the `--since last`
@@ -32,16 +38,22 @@ import { randomUUID } from 'node:crypto';
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 { initializeLocalPersistence, pendingAwareResponse, requestPrincipalForContext, submitPageMutation } from '../persistence/page-mutations.ts';
+import { waitForWrite } from '../persistence/service.ts';
+import { isTerminal, type WriteRequest } from '../persistence/model.ts';
+import { clientRequestUuid } from '../persistence/preconditions.ts';
+import { digest } from '../persistence/digest.ts';
+import { classifyItemFailure, ItemRun } from '../item-failure.ts';
import { unchangedPutPage } from '../persistence/put-page-screen.ts';
import { canonicalJson } from '../remediation-step.ts';
-import type { FileDiagnostics, TranscriptAdapter, TranscriptFormat } from './types.ts';
+import type { FileDiagnostics, ParsedSession, TranscriptAdapter, TranscriptFormat } from './types.ts';
import { detectAdapter } from './detect.ts';
import {
loadImportRedactionPatterns,
redactSession,
renderPartContent,
renderSessionParts,
+ type RedactedSession,
type RenderedPart,
type RenderSessionResult,
} from './render.ts';
@@ -99,11 +111,15 @@ export interface IngestSessionOutcome {
harness: TranscriptFormat;
baseSlug: string;
parts: number;
- /** Per-part import statuses (dry-run: 'planned'). */
- statuses: Array<'imported' | 'skipped' | 'error' | 'planned'>;
+ /** Per-part import statuses (dry-run: 'planned'; 'pending': accepted, not yet published). */
+ statuses: Array<'imported' | 'skipped' | 'error' | 'planned' | 'pending'>;
redactions: number;
imperatives: number;
error?: string;
+ /** The typed code of `error` (classifyItemFailure). */
+ code?: string;
+ /** Request ids of accepted writes still publishing: the session lands on a later run without a new admission. */
+ pending?: string[];
/** C-19: a session with no timestamps is skipped (never fabricated), not errored. */
skipped?: 'no_timestamp';
}
@@ -125,11 +141,13 @@ export interface IngestFileOutcome {
export interface TranscriptsIngestResult {
files: IngestFileOutcome[];
- pages: { imported: number; skipped: number; errored: number; planned: number };
+ pages: { imported: number; skipped: number; errored: number; planned: number; pending: number };
sessionsSeen: number;
sessionsImported: number;
sessionsFiltered: number;
sessionsErrored: number;
+ /** Sessions with an accepted write still publishing (not imported, not errored; the scan is not clean). */
+ sessionsPending: number;
/** Sessions with no timestamps at all: reported, not imported, not an error (C-19). */
sessionsSkippedNoTimestamp: number;
redactions: number;
@@ -169,25 +187,18 @@ function lastMessageTs(messages: Array<{ timestamp: string }>): string {
return '';
}
-const RUN_ABORT_MARKER = 'transcripts-ingest run abort';
-
-function isPerSessionImportError(err: unknown): boolean {
- // 'invalid byte sequence' is Postgres rejecting the DATA (e.g. a U+0000 a
- // sanitizer missed, #4392) — one bad session, never a DB-down signal.
- return err instanceof Error && /too large|invalid byte sequence/i.test(err.message);
-}
-
export async function runTranscriptsIngest(
engine: BrainEngine,
opts: TranscriptsIngestOpts,
): Promise<TranscriptsIngestResult> {
const result: TranscriptsIngestResult = {
files: [],
- pages: { imported: 0, skipped: 0, errored: 0, planned: 0 },
+ pages: { imported: 0, skipped: 0, errored: 0, planned: 0, pending: 0 },
sessionsSeen: 0,
sessionsImported: 0,
sessionsFiltered: 0,
sessionsErrored: 0,
+ sessionsPending: 0,
sessionsSkippedNoTimestamp: 0,
redactions: 0,
imperatives: 0,
@@ -207,6 +218,7 @@ export async function runTranscriptsIngest(
// otherwise repeat thousands of times.
const redactionPatterns = loadImportRedactionPatterns(opts.userPatternsPath);
const coordinator = !opts.dryRun && opts.context && await managedPersistenceEnabled(engine) ? opts.context : null;
+ const items = new ItemRun('transcripts.ingest_session');
const total = opts.paths.length;
let done = 0;
@@ -316,143 +328,29 @@ export async function runTranscriptsIngest(
// the first N eligible sessions — an upper bound on what the write
// path would import.
newWorkSessions++;
+ } else if (await importSession(engine, opts, { coordinator, items, path, session, redacted, rendered, outcome, result })) {
+ newWorkSessions++;
+ }
+ if (outcome.pending) {
+ result.sessionsPending++;
+ result.cleanScan = false;
} else {
- // The RESOLVED base slug: identity dedup can resolve part 1 to an
- // EXISTING page under a different slug (same session id, changed
- // title or corrected start date) — raw-data writes and stale-part
- // reconciliation must follow the page that actually exists, or
- // every re-run aborts on a nonexistent slug.
- await adoptExistingBaseSlug(engine, opts.sourceId ?? 'default', rendered);
- outcome.baseSlug = rendered.baseSlug;
- let resolvedBaseSlug = rendered.baseSlug;
- for (const part of rendered.parts) {
- try {
- await preserveForeignFrontmatter(engine, opts.sourceId ?? 'default', part);
- 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++;
- else result.pages.errored++;
- const actualSlug = r.slug || part.slug;
- if (part.part === 1 && actualSlug) resolvedBaseSlug = actualSlug;
- result.slugsTouched.push(actualSlug);
- } catch (err) {
- if (isPerSessionImportError(err)) throw err; // → per-session catch
- const e = new Error(
- `${RUN_ABORT_MARKER}: import integrity failure on ${part.slug}: ${
- err instanceof Error ? err.message : String(err)
- }`,
- );
- (e as { cause?: unknown }).cause = err;
- throw e;
- }
- }
-
- // importFromContent RETURNS status 'error' (it does not throw)
- // for e.g. frontmatter-parse failures. A page that never landed
- // is a session error and must freeze the watermark — otherwise
- // a since-last run permanently skips content that never imported.
- if (outcome.statuses.includes('error')) {
- throw new Error(
- `page import returned error status for session ${session.meta.sessionId}`,
- );
- }
-
- const allSkipped =
- outcome.statuses.length > 0 && outcome.statuses.every((s) => s === 'skipped');
- if (!allSkipped) newWorkSessions++;
-
- // Session metadata rides the base page's raw_data — the REDACTED
- // copy, never the original (secrets in titles/cwd would otherwise
- // bypass the page-body redaction). On all-skipped re-runs the
- // write is HEALED, not assumed: a prior run can have committed
- // the pages and then died before putRawData, and hash-skips
- // would otherwise make that hole permanent.
- if (redacted.session.meta.raw) {
- try {
- const rawSource = `transcript:${session.meta.harness}`;
- // Skipped re-runs COMPARE, never assume: existence alone is
- // not freshness — a private pattern added AFTER the first
- // import must refresh the stored copy, and a prior run can
- // have died before this write. Content-equal rows skip the
- // write so healthy re-runs stay write-free.
- let needsRaw = true;
- if (allSkipped) {
- // Active rows only: `allSkipped` means the import hash check
- // (which reads ACTIVE rows) just matched every page, so the
- // base page is alive here by construction — a tombstoned
- // page never reaches this branch (it reads as missing and is
- // re-imported, see the "resurrects the page" e2e). No
- // includeDeleted flag: the probe must never read through a
- // soft-delete the hash check did not.
- const existing = await engine.getRawData(resolvedBaseSlug, rawSource, {
- sourceId: opts.sourceId,
- });
- // Key-order-insensitive compare: JSONB hands keys back in
- // its own canonical order, so a plain JSON.stringify never
- // matched the freshly built object and every healthy re-run
- // rewrote the row.
- needsRaw =
- existing.length === 0 ||
- canonicalJson(existing[0].data) !==
- canonicalJson(JSON.parse(JSON.stringify(redacted.session.meta.raw)));
- }
- if (needsRaw) {
- await engine.putRawData(resolvedBaseSlug, rawSource, redacted.session.meta.raw, {
- sourceId: opts.sourceId,
- });
- }
- } catch (err) {
- const e = new Error(
- `${RUN_ABORT_MARKER}: putRawData failed for ${resolvedBaseSlug}: ${
- err instanceof Error ? err.message : String(err)
- }`,
- );
- (e as { cause?: unknown }).cause = err;
- throw e;
- }
- }
-
- // Stale-part reconciliation: a session that shrank or re-split
- // leaves higher-numbered part pages behind — delete them, or a
- // stale part stays searchable forever. ENUMERATED via one SQL
- // query (never a sequential probe: a crash mid-delete leaves
- // holes that a first-miss or bounded-miss probe walks past) and
- // run on EVERY pass including all-skipped re-runs, because a
- // prior run can have died between the page writes and this step.
- const partRows = await engine.executeRaw<{ slug: string }>(
- `SELECT slug FROM pages
- WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE $2`,
- [opts.sourceId, `${resolvedBaseSlug}-p%`],
- );
- for (const row of partRows) {
- const suffix = row.slug.slice(resolvedBaseSlug.length);
- const m = /^-p(\d+)$/.exec(suffix);
- const num = m ? Number(m[1]) : NaN;
- if (Number.isFinite(num) && num > rendered.parts.length) {
- // #5235: on a managed brain the stale part goes through the coordinator like the parts
- // themselves, bound to its revision; the direct delete is refused there.
- if (coordinator) await deleteStaleTranscriptPart(coordinator, engine, opts.sourceId, row.slug);
- else await engine.deletePage(row.slug, { sourceId: opts.sourceId });
- result.partsDeleted++;
- }
- }
+ items.succeed();
+ result.sessionsImported++;
+ result.redactions += outcome.redactions;
+ result.imperatives += outcome.imperatives;
}
- result.sessionsImported++;
- result.redactions += outcome.redactions;
- result.imperatives += outcome.imperatives;
} catch (err) {
- if (err instanceof Error && err.message.startsWith(RUN_ABORT_MARKER)) throw err;
- outcome.error = err instanceof Error ? err.message : String(err);
- result.sessionsErrored++;
+ // Run-scoped failures and a tripped breaker leave through here unchanged.
+ const failure = items.fail(session.meta.sessionId, err);
+ if (failure.scope === 'pending') {
+ (outcome.pending ??= []).push(failure.requestId!);
+ result.sessionsPending++;
+ } else {
+ outcome.error = failure.message;
+ outcome.code = failure.code;
+ result.sessionsErrored++;
+ }
result.cleanScan = false;
}
@@ -460,7 +358,7 @@ export async function runTranscriptsIngest(
}
if (step.done && step.value) applyFileDiagnostics(step.value, fileOutcome, result);
} catch (err) {
- if (err instanceof Error && err.message.startsWith(RUN_ABORT_MARKER)) throw err;
+ if (classifyItemFailure(err).scope === 'run') throw err;
fileOutcome.error = err instanceof Error ? err.message : String(err);
result.erroredFiles++;
result.cleanScan = false;
@@ -474,6 +372,138 @@ export async function runTranscriptsIngest(
return result;
}
+/**
+ * Writes one rendered session: every part (through the coordinator or the
+ * direct importer), then the session's raw metadata and its stale
+ * higher-numbered parts. A part the coordinator accepted but has not
+ * published leaves the session pending while its other parts still go; the
+ * metadata and the reconciliation wait for a run where every part landed.
+ * Returns whether the session was new work (a part that was not skipped).
+ */
+async function importSession(engine: BrainEngine, opts: TranscriptsIngestOpts, run: {
+ coordinator: OperationContext | null; items: ItemRun; path: string; session: ParsedSession; redacted: RedactedSession;
+ rendered: RenderSessionResult; outcome: IngestSessionOutcome; result: TranscriptsIngestResult;
+}): Promise<boolean> {
+ const { coordinator, items, path, session, redacted, rendered, outcome, result } = run;
+ // The RESOLVED base slug: identity dedup can resolve part 1 to an
+ // EXISTING page under a different slug (same session id, changed
+ // title or corrected start date) — raw-data writes and stale-part
+ // reconciliation must follow the page that actually exists, or
+ // every re-run aborts on a nonexistent slug.
+ await adoptExistingBaseSlug(engine, opts.sourceId ?? 'default', rendered);
+ outcome.baseSlug = rendered.baseSlug;
+ let resolvedBaseSlug = rendered.baseSlug;
+ for (const part of rendered.parts) {
+ let r: { slug: string; status: 'imported' | 'skipped' | 'error' };
+ try {
+ await preserveForeignFrontmatter(engine, opts.sourceId ?? 'default', part);
+ const provenance = { source_kind: `transcript:${session.meta.harness}`, source_uri: path, ingested_via: 'cli:transcripts-ingest' };
+ 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,
+ });
+ } catch (err) {
+ if (classifyItemFailure(err).scope !== 'pending') throw err;
+ (outcome.pending ??= []).push(items.fail(`${session.meta.sessionId}#p${part.part}`, err).requestId!);
+ outcome.statuses.push('pending');
+ result.pages.pending++;
+ continue;
+ }
+ outcome.statuses.push(r.status);
+ if (r.status === 'imported') result.pages.imported++;
+ else if (r.status === 'skipped') result.pages.skipped++;
+ else result.pages.errored++;
+ const actualSlug = r.slug || part.slug;
+ if (part.part === 1 && actualSlug) resolvedBaseSlug = actualSlug;
+ result.slugsTouched.push(actualSlug);
+ }
+ if (outcome.pending) return true;
+
+ // importFromContent RETURNS status 'error' (it does not throw)
+ // for e.g. frontmatter-parse failures. A page that never landed
+ // is a session error and must freeze the watermark — otherwise
+ // a since-last run permanently skips content that never imported.
+ if (outcome.statuses.includes('error')) {
+ throw new Error(
+ `page import returned error status for session ${session.meta.sessionId}`,
+ );
+ }
+
+ const allSkipped =
+ outcome.statuses.length > 0 && outcome.statuses.every((s) => s === 'skipped');
+
+ // Session metadata rides the base page's raw_data — the REDACTED
+ // copy, never the original (secrets in titles/cwd would otherwise
+ // bypass the page-body redaction). On all-skipped re-runs the
+ // write is HEALED, not assumed: a prior run can have committed
+ // the pages and then died before putRawData, and hash-skips
+ // would otherwise make that hole permanent.
+ if (redacted.session.meta.raw) {
+ const rawSource = `transcript:${session.meta.harness}`;
+ // Skipped re-runs COMPARE, never assume: existence alone is
+ // not freshness — a private pattern added AFTER the first
+ // import must refresh the stored copy, and a prior run can
+ // have died before this write. Content-equal rows skip the
+ // write so healthy re-runs stay write-free.
+ let needsRaw = true;
+ if (allSkipped) {
+ // Active rows only: `allSkipped` means the import hash check
+ // (which reads ACTIVE rows) just matched every page, so the
+ // base page is alive here by construction — a tombstoned
+ // page never reaches this branch (it reads as missing and is
+ // re-imported, see the "resurrects the page" e2e). No
+ // includeDeleted flag: the probe must never read through a
+ // soft-delete the hash check did not.
+ const existing = await engine.getRawData(resolvedBaseSlug, rawSource, {
+ sourceId: opts.sourceId,
+ });
+ // Key-order-insensitive compare: JSONB hands keys back in
+ // its own canonical order, so a plain JSON.stringify never
+ // matched the freshly built object and every healthy re-run
+ // rewrote the row.
+ needsRaw =
+ existing.length === 0 ||
+ canonicalJson(existing[0].data) !==
+ canonicalJson(JSON.parse(JSON.stringify(redacted.session.meta.raw)));
+ }
+ if (needsRaw) {
+ await engine.putRawData(resolvedBaseSlug, rawSource, redacted.session.meta.raw, {
+ sourceId: opts.sourceId,
+ });
+ }
+ }
+
+ // Stale-part reconciliation: a session that shrank or re-split
+ // leaves higher-numbered part pages behind — delete them, or a
+ // stale part stays searchable forever. ENUMERATED via one SQL
+ // query (never a sequential probe: a crash mid-delete leaves
+ // holes that a first-miss or bounded-miss probe walks past) and
+ // run on EVERY pass including all-skipped re-runs, because a
+ // prior run can have died between the page writes and this step.
+ const partRows = await engine.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages
+ WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE $2`,
+ [opts.sourceId, `${resolvedBaseSlug}-p%`],
+ );
+ for (const row of partRows) {
+ const suffix = row.slug.slice(resolvedBaseSlug.length);
+ const m = /^-p(\d+)$/.exec(suffix);
+ const num = m ? Number(m[1]) : NaN;
+ if (Number.isFinite(num) && num > rendered.parts.length) {
+ // #5235: on a managed brain the stale part goes through the coordinator like the parts
+ // themselves, bound to its revision; the direct delete is refused there.
+ if (coordinator) await deleteStaleTranscriptPart(coordinator, engine, opts.sourceId, row.slug);
+ else await engine.deletePage(row.slug, { sourceId: opts.sourceId });
+ result.partsDeleted++;
+ }
+ }
+ return !allSkipped;
+}
+
/**
* 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
@@ -481,7 +511,9 @@ export async function runTranscriptsIngest(
* overwrite (no revision means create-only). Embedding is deferred there, as
* for every coordinated page write. #6741 B: a part whose publication would
* change nothing takes no admission (put-page-screen.ts), so an unchanged
- * re-ingest burns no permanent request id.
+ * re-ingest burns no permanent request id. A part whose earlier write is
+ * still publishing waits on that write (transcriptPartRequest) instead of
+ * admitting a second one.
*/
async function submitTranscriptPart(
ctx: OperationContext,
@@ -494,21 +526,59 @@ async function submitTranscriptPart(
const params = { slug: part.slug, content: part.content, source_id: sourceId, ...provenance,
...(snapshot?.revision ? { expected_revision: snapshot.revision } : {}) };
if (await unchangedPutPage(ctx, params, snapshot)) return { slug: part.slug, status: 'skipped' };
- const receipt = await submitPageMutation(ctx, { operation: 'put_page', params });
+ const { requestId, prior } = await transcriptPartRequest(ctx, sourceId, part.slug, params);
+ const receipt = prior
+ ? pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prior, ctx.config, ctx.writeWaitMs))
+ : await submitPageMutation(ctx, { operation: 'put_page', params: { ...params, request_id: requestId } });
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' };
}
+/** Attempts read per journal lookup while finding a part's current request. */
+const PART_ATTEMPT_PAGE = 8;
+
+/**
+ * One part's write keeps one request identity across runs. The id is derived
+ * from the source, slug, expected revision and content, so a rerun while that
+ * write is still queued or publishing gets it back (`prior`) and waits on it;
+ * a committed one is replayed. A write that ended without committing
+ * (conflict, failed, cancelled) is retried under the next attempt's id, so a
+ * cleared cause re-queues the part instead of replaying its old refusal.
+ */
+async function transcriptPartRequest(ctx: OperationContext, sourceId: string, slug: string, params: Record<string, unknown>):
+ Promise<{ requestId: string; prior: WriteRequest | null }> {
+ await initializeLocalPersistence(ctx);
+ const principal = await requestPrincipalForContext(ctx);
+ const base = `transcript-${digest({ source_id: sourceId, slug, expected_revision: params.expected_revision ?? null, content: params.content }).slice(0, 40)}`;
+ for (let first = 0; ; first += PART_ATTEMPT_PAGE) {
+ const names = Array.from({ length: PART_ATTEMPT_PAGE }, (_, i) => `${base}-${first + i}`);
+ const rows = await ctx.engine.executeRaw<WriteRequest>(
+ 'SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
+ [principal.kind, principal.id, names.map(clientRequestUuid)]);
+ const byId = new Map(rows.map(row => [String(row.request_id).toLowerCase(), row]));
+ for (const requestId of names) {
+ const prior = byId.get(clientRequestUuid(requestId)) ?? null;
+ if (!prior || !isTerminal(prior) || prior.state === 'committed') return { requestId, prior };
+ }
+ }
+}
+
/**
* A stale higher-numbered part on a managed brain: a revision-bound `delete_page` write request (soft delete, recoverable).
* #6741 C: an internal reconciliation, so it is admitted as background work: against a worktree in recovery it is
* refused before any receipt (admission-origin.ts) and the session errors, instead of each run taking a new request id.
+ * That refusal (owner_unavailable) pauses background work only, so it is this session's error, never the run's:
+ * foreground parts of every other session are still admitted.
*/
async function deleteStaleTranscriptPart(ctx: OperationContext, engine: BrainEngine, sourceId: string, slug: string): Promise<void> {
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
if (!snapshot) return;
- const receipt = await submitPageMutation({ ...ctx, admissionOrigin: 'background' }, { operation: 'delete_page', params: { slug, source_id: sourceId, expected_revision: snapshot.revision, request_id: randomUUID() } });
+ const receipt = await submitPageMutation({ ...ctx, admissionOrigin: 'background' }, { operation: 'delete_page', params: { slug, source_id: sourceId, expected_revision: snapshot.revision, request_id: randomUUID() } })
+ .catch((err: unknown) => {
+ if (classifyItemFailure(err).code !== 'owner_unavailable') throw err;
+ throw new Error(`stale part ${slug} was not deleted: ${err instanceof Error ? err.message : String(err)}`);
+ });
if (receipt.state !== 'committed') {
throw new Error(`stale part ${slug} was not deleted: the coordinator returned ${String(receipt.state)}${receipt.error_code ? ` (${String(receipt.error_code)})` : ''}`);
}
diff --git a/test/pathological/a2-transcripts-ingest.test.ts b/test/pathological/a2-transcripts-ingest.test.ts
new file mode 100644
index 0000000000..5ce74086b1
--- /dev/null
+++ b/test/pathological/a2-transcripts-ingest.test.ts
@@ -0,0 +1,237 @@
+/**
+ * GBRA-130 A-2: one refused or still-pending transcript part never aborts the
+ * transcripts ingest, and through it the ChatGPT/Claude connector batch.
+ *
+ * 1. Protects: a session the coordinator refuses is reported per session with
+ * its typed code while the other sessions land; an accepted write that
+ * outlasts the wait is a pending session (never a failure, never synced);
+ * a rerun waits on that write instead of admitting a duplicate; a pending
+ * write that ends without committing is re-queued; the connector watermark
+ * never passes a pending or failed conversation.
+ * 2. Regression: the per-part catch treating anything but /too large|invalid
+ * byte sequence/ as a run abort, or a random request id per run.
+ * 3. Existing coverage stubs the ingest result (connectors-ingest-failure) or
+ * pins the regex seam (transcripts-nul); none drives a real coordinator
+ * refusal or a real accepted write that commits after the wait.
+ * 4. No production seam: the bad states are a canonical file edited outside
+ * coordination and a paused owner (worktree draining).
+ */
+import { describe, expect, test } from 'bun:test';
+import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { runTranscriptsIngest, type TranscriptsIngestResult } from '../../src/core/transcripts/ingest.ts';
+import { runConnectorSync } from '../../src/core/connectors/sync.ts';
+import { saveCredential } from '../../src/core/connectors/credentials.ts';
+import { connectorSourceKey } from '../../src/core/connectors/config-keys.ts';
+import { CHATGPT_BASE_URL } from '../../src/core/connectors/providers/chatgpt.ts';
+import { waitForWrites } from '../../src/core/persistence/service.ts';
+import type { WriteRequest } from '../../src/core/persistence/model.ts';
+import { chatgptHandler, newFixtureState, startFixture, type FixtureConversation, type FixtureState } from '../fixtures/connectors/fixture-server.ts';
+import { expectItemFailure, expectOthersUnchanged, expectUnitNotAborted, managedBrain, pathologicalArms, runScopedErrors, snapshotItems } from './harness.ts';
+
+const T0 = 1_786_080_000;
+const message = (role: string, t: number, text: string) => ({ author: { role }, create_time: t, content: { content_type: 'text', parts: [text] } });
+const exportConversation = (id: string, t: number, text: string) => ({ title: `Conversation ${id}`, create_time: t, update_time: t + 15,
+ conversation_id: id, current_node: 'n2', mapping: { root: { id: 'root', parent: null, children: ['n1'], message: null },
+ n1: { id: 'n1', parent: 'root', children: ['n2'], message: message('user', t + 5, text) },
+ n2: { id: 'n2', parent: 'n1', children: [], message: message('assistant', t + 15, `An answer to ${text}.`) } } });
+
+function exportFile(root: string, texts: Record<string, string>): string {
+ const path = join(root, '..', 'export.json');
+ writeFileSync(path, JSON.stringify(Object.entries(texts).map(([id, text], i) => exportConversation(id, T0 + i * 1000, text))));
+ return path;
+}
+
+const ingest = (engine: BrainEngine, ctx: OperationContext, path: string, writeWaitMs?: number) =>
+ runTranscriptsIngest(engine, { paths: [path], sourceId: 'default', format: 'chatgpt', context: writeWaitMs === undefined ? ctx : { ...ctx, writeWaitMs } });
+
+const sessions = (r: TranscriptsIngestResult) => new Map(r.files.flatMap(f => f.sessions).map(s => [s.sessionId, s]));
+const slugOf = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ slug: string; source_path: string }>(
+ "SELECT slug, source_path FROM pages WHERE source_id='default' AND frontmatter->'transcript_import'->>'session_id' = $1 AND deleted_at IS NULL ORDER BY slug", [id]))[0]!;
+const putPageRequests = async (engine: BrainEngine) => engine.executeRaw<WriteRequest>(
+ "SELECT * FROM persistence_requests WHERE source_id='default' AND operation='put_page' ORDER BY sequence");
+
+/** Pauses or resumes the canonical owner: a draining worktree admits writes and publishes none. */
+async function owner(engine: BrainEngine, state: 'draining' | 'active'): Promise<void> {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("UPDATE persistence_worktrees SET state=$1 WHERE id IN (SELECT worktree_id FROM persistence_source_bindings WHERE source_id='default')", [state]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+}
+
+async function settle(engine: BrainEngine): Promise<WriteRequest[]> {
+ const rows = await engine.executeRaw<WriteRequest>("SELECT * FROM persistence_requests WHERE source_id='default' ORDER BY sequence");
+ return waitForWrites(engine, rows, { engine: engine.kind }, 30_000);
+}
+
+/** The bad state: a conversation page whose canonical file carries an edit made outside coordinated publication. */
+async function editOutsideCoordination(engine: BrainEngine, root: string, id: string): Promise<() => void> {
+ const file = join(root, (await slugOf(engine, id)).source_path);
+ const original = readFileSync(file, 'utf8');
+ appendFileSync(file, '\nAn edit made outside coordinated publication.\n');
+ return () => writeFileSync(file, original);
+}
+
+for (const { backend, databaseUrl } of pathologicalArms()) {
+ describe(`A-2 transcripts ingest (${backend})`, () => {
+ test('item: a session the coordinator refuses is reported with its code and the other sessions land', async () => managedBrain(async ({ engine, ctx, root }) => {
+ await ingest(engine, ctx, exportFile(root, { 'c-1': 'one', 'c-2': 'two', 'c-3': 'three' }));
+ const restore = await editOutsideCoordination(engine, root, 'c-2');
+ const before = await snapshotItems(engine, 'default');
+ const path = exportFile(root, { 'c-1': 'one edited', 'c-2': 'two edited', 'c-3': 'three edited' });
+ const result = await expectUnitNotAborted(() => ingest(engine, ctx, path));
+ const c2 = sessions(result).get('c-2')!;
+ expectItemFailure({ key: c2.sessionId, code: c2.code }, { key: 'c-2', code: 'source_changed' });
+ expect(result).toMatchObject({ sessionsErrored: 1, sessionsImported: 2, cleanScan: false });
+ const [one, three] = [await slugOf(engine, 'c-1'), await slugOf(engine, 'c-3')];
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { expectProgress: [one.slug, three.slug], progressFields: ['content_hash'] });
+ // Recovery: once the canonical file is back to its committed bytes, the same rerun lands the session.
+ restore();
+ const again = await ingest(engine, ctx, path);
+ expect(again).toMatchObject({ sessionsErrored: 0, sessionsImported: 3, cleanScan: true });
+ }, { databaseUrl }), 180_000);
+
+ test('pending: an accepted write that outlasts the wait stays pending under one request id and lands later without a duplicate admission', async () => managedBrain(async ({ engine, ctx, root }) => {
+ const path = exportFile(root, { 'c-1': 'one', 'c-2': 'two', 'c-3': 'three' });
+ await owner(engine, 'draining');
+ const first = await expectUnitNotAborted(() => ingest(engine, ctx, path, 50));
+ expect(first).toMatchObject({ sessionsPending: 3, sessionsErrored: 0, sessionsImported: 0, cleanScan: false });
+ const ids = [...sessions(first).values()].map(s => s.pending);
+ expect(ids.every(id => id?.length === 1)).toBe(true);
+ const second = await expectUnitNotAborted(() => ingest(engine, ctx, path, 50));
+ expect([...sessions(second).values()].map(s => s.pending)).toEqual(ids);
+ expect((await putPageRequests(engine)).length).toBe(3);
+ await owner(engine, 'active');
+ expect((await settle(engine)).map(row => row.state)).toEqual(['committed', 'committed', 'committed']);
+ const third = await ingest(engine, ctx, path);
+ expect(third).toMatchObject({ sessionsPending: 0, sessionsImported: 3, cleanScan: true, pages: { imported: 0, skipped: 3 } });
+ expect((await putPageRequests(engine)).length).toBe(3);
+ }, { databaseUrl }), 180_000);
+
+ test('recovery: a pending write that ends without committing is re-queued under a new request and lands', async () => managedBrain(async ({ engine, ctx, root }) => {
+ await ingest(engine, ctx, exportFile(root, { 'c-1': 'one' }));
+ const path = exportFile(root, { 'c-1': 'one edited' });
+ await owner(engine, 'draining');
+ const pending = await ingest(engine, ctx, path, 50);
+ expect(pending.sessionsPending).toBe(1);
+ const restore = await editOutsideCoordination(engine, root, 'c-1');
+ await owner(engine, 'active');
+ expect((await settle(engine)).map(row => row.state)).toEqual(['committed', 'conflict']);
+ restore();
+ const retried = await expectUnitNotAborted(() => ingest(engine, ctx, path));
+ expect(retried).toMatchObject({ sessionsPending: 0, sessionsErrored: 0, sessionsImported: 1, cleanScan: true });
+ expect((await putPageRequests(engine)).map(row => row.state)).toEqual(['committed', 'conflict', 'committed']);
+ }, { databaseUrl }), 180_000);
+
+ for (const injected of runScopedErrors()) {
+ test(`run: a run-scoped failure inside a session stops the ingest (${injected.name})`, async () => managedBrain(async ({ engine, ctx, root }) => {
+ const path = exportFile(root, { 'c-1': 'one', 'c-2': 'two', 'c-3': 'three' });
+ const error = injected.error();
+ let calls = 0;
+ const failing = new Proxy(engine, { get(target, key) {
+ const value = (target as unknown as Record<string | symbol, unknown>)[key];
+ if (key === 'readPageSnapshot') return async (...args: unknown[]) => { if (++calls === 2) throw error; return (value as (...a: unknown[]) => unknown).apply(target, args); };
+ return typeof value === 'function' ? (value as (...a: unknown[]) => unknown).bind(target) : value;
+ } });
+ await expect(ingest(failing, ctx, path)).rejects.toBe(error);
+ }, { databaseUrl }), 120_000);
+ }
+
+ test('breaker: when most sessions are refused the ingest stops item_failures_systemic', async () => managedBrain(async ({ engine, ctx, root }) => {
+ const ids = ['c-1', 'c-2', 'c-3', 'c-4', 'c-5', 'c-6'];
+ await ingest(engine, ctx, exportFile(root, Object.fromEntries(ids.map(id => [id, id]))));
+ for (const id of ids.slice(0, 5)) await editOutsideCoordination(engine, root, id);
+ await expect(ingest(engine, ctx, exportFile(root, Object.fromEntries(ids.map(id => [id, `${id} edited`])))))
+ .rejects.toMatchObject({ code: 'item_failures_systemic' });
+ }, { databaseUrl }), 180_000);
+ });
+
+ describe(`A-2 connector sync (${backend})`, () => {
+ const NOW_MS = (T0 + 100_000) * 1000;
+ const conv = (id: string, updateTime: number, text = `question ${id}`): FixtureConversation => ({ id, title: `Title ${id}`,
+ createTime: updateTime - 100, updateTime, turns: [{ role: 'user', text }, { role: 'assistant', text: `answer ${id}` }] });
+ const sync = async (engine: BrainEngine, ctx: OperationContext, state: FixtureState, writeWaitMs?: number,
+ runIngest: typeof runTranscriptsIngest = (eng, opts) => runTranscriptsIngest(eng, { ...opts, context: writeWaitMs === undefined ? ctx : { ...ctx, writeWaitMs } })) => {
+ saveCredential({ provider: 'chatgpt', strategy: 'browser-session', cookie: 'sessionKey=fixture', savedAt: new Date(0).toISOString() });
+ 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, sleep: () => Promise.resolve(), runIngest } });
+ } finally { srv.stop(); }
+ };
+ const ledger = async (engine: BrainEngine, which: 'synced' | 'failed') => JSON.parse(await engine.getConfig(connectorSourceKey('chatgpt', 'default', which)) ?? '{}');
+
+ test('item: a conversation whose ingest is refused is counted toward quarantine and the batch siblings sync', async () => managedBrain(async ({ engine, ctx, root }) => {
+ const state = newFixtureState([conv('c-1', T0 + 10), conv('c-2', T0 + 20), conv('c-3', T0 + 30)]);
+ await sync(engine, ctx, state);
+ const restore = await editOutsideCoordination(engine, root, 'c-2');
+ state.conversations = [conv('c-1', T0 + 40, 'one edited'), conv('c-2', T0 + 50, 'two edited'), conv('c-3', T0 + 60, 'three edited')];
+ const before = await snapshotItems(engine, 'default');
+ const results = [];
+ for (let run = 0; run < 3; run++) results.push(await expectUnitNotAborted(() => sync(engine, ctx, state)));
+ const failed = await ledger(engine, 'failed');
+ expectItemFailure({ key: Object.keys(failed)[0], code: failed['c-2']?.code }, { key: 'c-2', code: 'source_changed' });
+ expect(results.map(r => r.watermarkAdvancedTo)).toEqual([undefined, undefined, new Date((T0 + 60) * 1000).toISOString()]);
+ expect(results[2].quarantined).toEqual(['c-2']);
+ const iso = (t: number) => new Date(t * 1000).toISOString();
+ expect(await ledger(engine, 'synced')).toEqual({ 'c-1': iso(T0 + 40), 'c-2': iso(T0 + 20), 'c-3': iso(T0 + 60) });
+ const [one, three] = [await slugOf(engine, 'c-1'), await slugOf(engine, 'c-3')];
+ expectOthersUnchanged(before, await snapshotItems(engine, 'default'), { expectProgress: [one.slug, three.slug], progressFields: ['content_hash'] });
+ restore();
+ state.conversations[1] = conv('c-2', T0 + 70, 'two edited again');
+ const recovered = await sync(engine, ctx, state);
+ expect(recovered.unresolved).toBe(0);
+ expect(await ledger(engine, 'failed')).toEqual({});
+ }, { databaseUrl }), 240_000);
+
+ test('pending: a conversation whose write is still pending holds the watermark, is never marked synced, and lands later without a duplicate admission', async () => managedBrain(async ({ engine, ctx }) => {
+ const state = newFixtureState([conv('c-1', T0 + 10), conv('c-2', T0 + 20)]);
+ await owner(engine, 'draining');
+ const first = await expectUnitNotAborted(() => sync(engine, ctx, state, 50));
+ expect(first.status).toBe('partial');
+ expect([...first.pending].sort()).toEqual(['c-1', 'c-2']);
+ expect(first.watermarkAdvancedTo).toBeUndefined();
+ expect(await ledger(engine, 'synced')).toEqual({});
+ expect(await ledger(engine, 'failed')).toEqual({});
+ const second = await expectUnitNotAborted(() => sync(engine, ctx, state, 50));
+ expect(second.watermarkAdvancedTo).toBeUndefined();
+ expect((await putPageRequests(engine)).length).toBe(2);
+ await owner(engine, 'active');
+ await settle(engine);
+ const third = await sync(engine, ctx, state);
+ expect(third.pending).toEqual([]);
+ expect(third.watermarkAdvancedTo).toBe(new Date((T0 + 20) * 1000).toISOString());
+ expect(Object.keys(await ledger(engine, 'synced')).sort()).toEqual(['c-1', 'c-2']);
+ expect((await putPageRequests(engine)).map(row => row.state)).toEqual(['committed', 'committed']);
+ }, { databaseUrl }), 240_000);
+
+ test('recovery: a pending conversation write that ends in conflict is re-queued, never marked synced, and lands on the next run', async () => managedBrain(async ({ engine, ctx, root }) => {
+ const state = newFixtureState([conv('c-1', T0 + 10)]);
+ await sync(engine, ctx, state);
+ state.conversations = [conv('c-1', T0 + 20, 'one edited')];
+ await owner(engine, 'draining');
+ expect((await sync(engine, ctx, state, 50)).pending).toEqual(['c-1']);
+ const restore = await editOutsideCoordination(engine, root, 'c-1');
+ await owner(engine, 'active');
+ await settle(engine);
+ expect((await ledger(engine, 'synced'))['c-1']).toBe(new Date((T0 + 10) * 1000).toISOString());
+ restore();
+ const retried = await sync(engine, ctx, state);
+ expect(retried.watermarkAdvancedTo).toBe(new Date((T0 + 20) * 1000).toISOString());
+ expect((await ledger(engine, 'synced'))['c-1']).toBe(new Date((T0 + 20) * 1000).toISOString());
+ expect((await putPageRequests(engine)).map(row => row.state)).toEqual(['committed', 'conflict', 'committed']);
+ }, { databaseUrl }), 240_000);
+
+ for (const injected of runScopedErrors()) {
+ test(`run: a run-scoped failure inside the connector ingest stops the sync and records no failure (${injected.name})`, async () => managedBrain(async ({ engine, ctx }) => {
+ const state = newFixtureState([conv('c-1', T0 + 10), conv('c-2', T0 + 20)]);
+ const error = injected.error();
+ await expect(sync(engine, ctx, state, undefined, async () => { throw error; })).rejects.toBe(error);
+ expect(await ledger(engine, 'failed')).toEqual({});
+ expect(await ledger(engine, 'synced')).toEqual({});
+ expect(await engine.getConfig(connectorSourceKey('chatgpt', 'default', 'watermark_iso'))).toBeNull();
+ }, { databaseUrl }), 120_000);
+ }
+ });
+}
diff --git a/test/pathological/catalogue.ts b/test/pathological/catalogue.ts
index 038e54eda2..8bf3bf761a 100644
--- a/test/pathological/catalogue.ts
+++ b/test/pathological/catalogue.ts
@@ -18,4 +18,7 @@ export interface SiteCases {
}
export const CATALOGUE: Record<IsolateSite, SiteCases> = {
+ 'transcripts.ingest_session': { file: 'test/pathological/a2-transcripts-ingest.test.ts',
+ item: 'item: a session the coordinator refuses is reported with its code and the other sessions land',
+ run: 'run: a run-scoped failure inside a session stops the ingest' },
};
diff --git a/test/transcripts-codex-subagent.test.ts b/test/transcripts-codex-subagent.test.ts
index 0527c7fd2b..4a2396d572 100644
--- a/test/transcripts-codex-subagent.test.ts
+++ b/test/transcripts-codex-subagent.test.ts
@@ -122,8 +122,8 @@ describe('#6741 A: Codex sub-agent rollouts are understood, not drift', () => {
}, 120_000);
test('the scan summary reports sub-agent rollouts separately from drift', () => {
- const summary = fmtSummary({ files: [], pages: { imported: 0, skipped: 2, errored: 0, planned: 0 }, sessionsSeen: 2, sessionsImported: 2,
- sessionsFiltered: 0, sessionsErrored: 0, sessionsSkippedNoTimestamp: 0, redactions: 0, imperatives: 0, partsDeleted: 0, driftFiles: 0,
+ const summary = fmtSummary({ files: [], pages: { imported: 0, skipped: 2, errored: 0, planned: 0, pending: 0 }, sessionsSeen: 2, sessionsImported: 2,
+ sessionsFiltered: 0, sessionsErrored: 0, sessionsPending: 0, sessionsSkippedNoTimestamp: 0, redactions: 0, imperatives: 0, partsDeleted: 0, driftFiles: 0,
subagentRollouts: 3, truncatedFiles: 0, erroredFiles: 0, slugsTouched: [], cleanScan: true, maxSessionTs: '' });
expect(summary).toContain('3 sub-agent rollouts (no user turns by design)');
expect(summary).not.toContain('DRIFT WARNING');