Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(#6831): record credential failures that end a connector run; clarify purged-skip comments

garrytan466b30dd351e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d95270558..20f4014628 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -31,7 +31,7 @@ On an older release you can unblock it by hand: `gbrain pages purges list` names
### Itemized changes
- **Per-item purged skip (#6831).** A managed connector page import whose content matches one of the source's page purge tombstones is skipped before admission (`ManagedConnectorSync.carriesPurgedPage`, same content hash the pages guard compares). If the guard still refuses at publication (`failed` / `purged_content`, for example a purge that landed mid-run), that refusal is skipped the same way, wherever it surfaces: the item's own wait, the pending set at the end of the run, or the pending set a previous run left. A skipped item is not a receipt the checkpoint waits on and never joins the automatic retry set. Every other failed receipt still fails the run, as before. Covers every connector on this path: Google contacts, calendar and Gmail, and GitHub.
-- **Run failures recorded (#6831).** The connector state row records the error a run ended on (`last_failure`: code, message, item slug and request when the run ended on an item's receipt, time, and the count of runs in a row that ended that way); a run that finishes clears it. It also keeps the 20 most recent purged skips (`purged_items`) and the run's `last_run.purged_skipped` count.
+- **Run failures recorded (#6831).** The connector state row records the write refusal or credential error a run ended on (`last_failure`: code, message, item slug and request when the run ended on an item's receipt, time, and the count of runs in a row that ended that way); a run that finishes clears it. It also keeps the 20 most recent purged skips (`purged_items`) and the run's `last_run.purged_skipped` count.
- **Status surfaces (#6831).** `gbrain sources status` (human and `--json` `connector.last_failure`, `connector.stopped`, `connector.purged_items`); `gbrain sync status --json` gains `connector_last_error` (with `class`, `safe_actions`, `needs_human` and a read-only `fix`), and its `next` names that fix when nothing else applies. `last_error`, the managed-sync cursor and its resume command are unchanged for connector sources. Doctor `sync_freshness` reports a connector source with 3 or more failed runs in a row as STOPPED.
- **`claude-cli` refusals (#6816).** `providerContentBlockReason` recognizes the `claude-cli` adapter's usage-policy refusal: the `claude-cli reported error: API Error:` prefix with no API status, the usage-policy link, and one of the refusal phrases Claude Code has used ("can't help with this", "safeguards flagged this", "violate our Usage Policy"). Any other `claude-cli` error is unchanged. With `chat_fallback_on_refusal: false`, such a refusal is no longer sent on to the next model in `chat_fallback_chain`.
- Tests: `test/connector-purged-item-6831.test.ts` (PGLite) and `test/e2e/connector-purged-item-6831.test.ts` (Postgres) fail on v0.60.260.0 with `purged_content` ending the run and pass here; `test/claude-cli-refusal-6816.test.ts` runs the real adapter and gateway against a stub CLI.
diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.md
index 4cf4f2b5a7..93ed193f13 100644
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@ -26,7 +26,7 @@ Managed connector ingestion, connector item holds and the no-op kernel (checkpoi
- `src/core/persistence/purge-deleted.ts` — `purgeDeletedPagesCoordinated` backs the cycle `purge` phase, the purge job, `purge_deleted_pages` and `gbrain pages purge-deleted`. Unmanaged brains keep the engine bulk delete; a managed brain purges each tombstone older than the window (skipping archived sources, which the source lifecycle purges) through `delete_page` with `purge: true` bound to its revision. Revision races are deferred to the next run; any other failure is listed in `blocked` and sets `error`, which fails the purge phase. Tests: `test/managed-writers-w3.test.ts`.
- `src/core/persistence/loop-fact-retirement.ts` — #5869 commitment-fact retirement for closed loops, one coordinator mutation on every brain (operation `loops_close`, intent `retire_loop_fact`, dispatched from `service.ts`): expires the fact and strikes its `## Facts` fence row (context `loop closed: <status>`) through the entity page publication in one transaction; no withdrawal tombstone. The shared rule (also `loopFactDrift`, used by doctor `loop_facts_drift` and `gbrain repair loop-facts`): only a fact in the loop's source that no other open loop references, re-checked under row locks at publication (`shared_with_open_loop`, `source_mismatch` otherwise). `retireLoopFact(ctx, loopId)` submits with the caller's grant and maps a refusal or pending write to `fact_expired: false, retryable: true, reason`. Tests: `test/loops-close-fact.serial.test.ts` (+ Postgres twin).
- `src/core/persistence/connector-authority.ts` -- classifies each Google/GitHub source as `connector_database` (managed, unbound), `bound` or `unmanaged` from `persistence_brain.enabled` and the source binding row. File-lane audits (doctor `undeclared_db_only_pages`, backup coverage) read it so a leftover cache directory at `local_path` is never taken for canonical files. Tests: `test/doctor-silent-death-checks.test.ts`, `test/backup-coverage.serial.test.ts`.
-- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres. #6831: a page import whose content matches a source page purge tombstone is skipped per item instead of ending the run: screened before admission (`carriesPurgedPage`, the guard's content hash, read only when the source has a tombstone), and a `failed`/`purged_content` receipt the guard still produces (a purge that landed mid-run) is skipped wherever it surfaces (the item's wait, `refreshPending`, `resolvePendingSet`): it is dropped from `receipts`, never joins the automatic retry set, and is counted in `last_run.purged_skipped` and `purged_items`. A run that ends on an `OperationError` records `last_failure` (code, message, the item and request when the run ended on that item's receipt, `consecutive`); `finish()` without an error clears it. Tests: `test/connector-purged-item-6831.test.ts` (+ `test/e2e/` twin).
+- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres. #6831: a page import whose content matches a source page purge tombstone is skipped per item instead of ending the run: screened before admission (`carriesPurgedPage`, the guard's content hash, read only when the source has a tombstone), and a `failed`/`purged_content` receipt the guard still produces (a purge that landed mid-run) is skipped wherever it surfaces (the item's wait, `refreshPending`, `resolvePendingSet`): it is dropped from `receipts`, never joins the automatic retry set, and is counted in `last_run.purged_skipped` and `purged_items`. A run that ends on an `OperationError` or a `CredentialError` records `last_failure` (code, message, the item and request when the run ended on that item's receipt, `consecutive`); `finish()` without an error clears it. Tests: `test/connector-purged-item-6831.test.ts` (+ `test/e2e/` twin).
- `src/core/persistence/connector-identity.ts` — `connectorIdentity(kind, rawConfig, localPath)` returns the parsed connector config and a digest over every parsed leaf except credential-delivery fields (Google `access`/`tokenCommand`/`tokenEnv`; GitHub `tokenEnv` and `app` under `scope: repos`, `app.pemPath` always; under `scope: auto` the token env without an App and the App ids are identity). `services`/`repos` are sorted and de-duplicated; a parser leaf missing from `CONNECTOR_LEAF_RULES` joins the identity. #6561: a leaf a parser starts emitting with a behavior-preserving default declares it as `elideWhen` (Google `contactsDir: 'people'`) and is left out of the digest while it holds it, so unchanged sources keep the pre-field key; the non-elided digest is kept as `aliasDigests` (`connectorCheckpointKeys` returns the stable key then its alias keys; `connectorIdentityMatches` accepts an admitted write's frozen `configHash` under either). Also `connectorCheckpointKey` and `isConnectorIntentKind`/`connectorIntentSql`, the one predicate for both intent namespaces. Test: `test/connector-identity.test.ts` enumerates every parser leaf.
- `src/core/persistence/connector-state.ts` — (fix wave 4: also `first_attempt_at`, the autopilot connector dispatch gate, recorded before the first provider call of a validated, non-preview sync and seeded by migration v181) the per-source-incarnation `op='managed-connector-state'` row (fingerprint `digest({sourceId, incarnation})`, independent of the identity digest): account pin, pending set `{itemRef, requestId, baseRequestId, admittedAt}`, `upgrade_recovery` (`resumed`/`rewalking_once`/`none`) with `resumed_from`, `continuity_unverified` and last-run counts. `writeManagedConnectorState` checks the connector sync lease in the same statement. `connector-status.ts` renders it for `gbrain sources status` without the account. #6831: `purged_items` (newest `CONNECTOR_PURGED_LIMIT` purged skips) and `last_failure` (`ConnectorRunFailure`); `CONNECTOR_STOPPED_RUNS` (3) consecutive failed runs read as stopped in `connector-status.ts` (`sources status` lines, `readConnectorLastError` for `sync status`'s `connector_last_error` and its fallback `next`) and doctor `sync_freshness` (`stoppedConnectorIssues` in `doctor/sync-outcome.ts`).
- `src/core/connectors/item-holds.ts` — fix wave 4 connector item holds, shared by Gmail and GitHub on managed and unmanaged brains: `classifyConnectorError` (the one table: source-scoped, rate-limit and item-scoped codes, content vs transient class) and `ItemHoldsRun` (hold after 3 consecutive attempted runs at one upstream version; circuit breaker at 5 attempted items with half transient or 5 and half one code; backoff 1 h/6 h/24 h/daily for 7 days; cap 100, `connector_holds_exhausted`). A run's changes merge only in `finish()`, so mid-run checkpoints carry the holds the run began with and a cursor never passes an item that is not already held. `carryLegacyFailCounts` reads the retired Gmail ledger once.
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 7459d59b9d..60343df06c 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -47,6 +47,7 @@ import { readConnectorV2Cutoff } from './connector-checkpoint-migration.ts';
import { declarePersistenceProtocol } from './protocol.ts';
import { intentCarriesPurgedContent } from './purged-intent.ts';
import { PERSISTENCE_IPC_MAX_BYTES } from './ipc.ts';
+import { isCredentialError, type CredentialError } from '../creds/errors.ts';
import type { GoogleSourceConfig } from '../google/types.ts';
interface ConnectorLease { handle: DbLockHandle; signal: AbortSignal; }
@@ -313,7 +314,7 @@ export async function withConnectorSync<T>(engine: BrainEngine, sourceId: string
result = await work(session, options);
} catch (error) {
if (!(error instanceof ConnectorWaitBudgetStop)) {
- if (error instanceof OperationError) await session.finish(error).catch(() => {});
+ if (error instanceof OperationError || isCredentialError(error)) await session.finish(error).catch(() => {});
throw error;
}
await session.finish();
@@ -748,7 +749,7 @@ export class ManagedConnectorSync {
* error the run ended on (#6831): it is recorded with a count of runs in a row that ended that way, and a run that
* ends without one clears it.
*/
- async finish(failure?: OperationError): Promise<void> {
+ async finish(failure?: OperationError | CredentialError): Promise<void> {
await this.refreshPending().catch(() => {});
const now = new Date().toISOString();
const outstanding = [...this.pendingRows.values()].map(pending => pending.entry);
@@ -768,8 +769,9 @@ export class ManagedConnectorSync {
const listed = new Set<string>();
const purgedItems = [...this.purged].reverse().concat(this.connectorState.purged_items ?? [])
.filter(entry => !listed.has(entry.slug) && !!listed.add(entry.slug)).slice(0, CONNECTOR_PURGED_LIMIT);
- const item = failure?.writeRequest?.request_id === this.lastFailedItem?.requestId ? this.lastFailedItem : null;
- const lastFailure = failure ? { code: failure.writeError ?? failure.code, message: failure.message, slug: item?.slug ?? null, request_id: item?.requestId ?? null,
+ const receipt = failure instanceof OperationError ? failure.writeRequest : undefined;
+ const item = receipt && receipt.request_id === this.lastFailedItem?.requestId ? this.lastFailedItem : null;
+ const lastFailure = failure ? { code: (failure instanceof OperationError ? failure.writeError : undefined) ?? failure.code, message: failure.message, slug: item?.slug ?? null, request_id: item?.requestId ?? null,
at: now, consecutive: (this.connectorState.last_failure?.consecutive ?? 0) + 1 } : null;
this.connectorState = { ...this.connectorState, pending, upgrade_recovery: recovery, purged_items: purgedItems, last_failure: lastFailure, last_run: {
page_admissions: this.counts.page_admissions, skipped_unchanged: this.counts.skipped_unchanged, pending: pending.length,
@@ -778,9 +780,10 @@ export class ManagedConnectorSync {
await this.writeState();
}
/**
- * #6831: records a connector item the pages guard refused as purged content. Its receipt is not one the checkpoint
- * waits on, and it never joins the automatic retry set; the next run that lists the same content replays the same
- * refused receipt and skips it again, until the owner clears the tombstone (`gbrain pages unpurge <slug>`).
+ * #6831: records a connector item skipped because its content matches a page purge tombstone, either screened out
+ * before admission (`row` null) or refused by the pages guard at publication. A refused receipt is not one the
+ * checkpoint waits on, and it never joins the automatic retry set. The item stays skipped on every run that lists the
+ * same content until the owner clears the tombstone (`gbrain pages unpurge <slug>`).
*/
private skipPurged(slug: string, row: WriteRequest | null): void {
if (row) this.receipts = this.receipts.filter(id => id !== row.id);
@@ -791,8 +794,9 @@ export class ManagedConnectorSync {
}
/**
* #6831: screens a page import against the source's page purge tombstones before admission, with the content hash
- * the pages guard compares (`intentCarriesPurgedContent`), so a purged item that keeps being listed costs no refused receipt per run. A miss here
- * (the publication renders different bytes) still ends in the guard's refusal, which `submit` skips the same way.
+ * the pages guard compares (`intentCarriesPurgedContent`), so a purged item that keeps being listed costs no refused
+ * receipt per run. A miss here (the publication renders different bytes, or a purge lands mid-run) still ends in the
+ * guard's refusal, which `submit` and the pending-set paths skip the same way.
*/
private async carriesPurgedPage(slug: string, content: string | undefined): Promise<boolean> {
if (!this.hasPagePurges || !content) return false;
diff --git a/test/connector-purged-item-6831.test.ts b/test/connector-purged-item-6831.test.ts
index 17b5c5fb16..3ccd20eaa0 100644
--- a/test/connector-purged-item-6831.test.ts
+++ b/test/connector-purged-item-6831.test.ts
@@ -22,6 +22,7 @@ import { connectorStatusLines, readConnectorSourceStatuses } from '../src/core/p
import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
import { checkSyncFreshness } from '../src/commands/doctor/checks/extraction-sync.ts';
import { opError } from '../src/core/ops/contract.ts';
+import { CredentialError } from '../src/core/creds/errors.ts';
import { contact, createConnectorFixture, json, options, settleConnectorWrites, withGoogleAccount } from './helpers/connector-fixture.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -179,6 +180,11 @@ test('#6831: a connector source whose runs keep ending on an error reads as stop
expect(doctor.status).not.toBe('ok');
expect(doctor.message).toContain(`Source '${f.id}' is STOPPED: its last ${CONNECTOR_STOPPED_RUNS} connector syncs ended on invalid_fence`);
+ // A credential failure that ends the run counts too.
+ await expect(withConnectorSync(engine, f.id, 'google', cfg, options, async () => { throw new CredentialError('scope_missing', undefined, 'services without grant: calendar'); }))
+ .rejects.toMatchObject({ code: 'scope_missing' });
+ expect((await connectorState(engine, f.id)).last_failure).toMatchObject({ code: 'scope_missing', consecutive: CONNECTOR_STOPPED_RUNS + 1 });
+
// A run that finishes clears the record.
await withConnectorSync(engine, f.id, 'google', cfg, options, async () => undefined);
expect((await connectorState(engine, f.id)).last_failure).toBeNull();