Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: one purged connector item no longer stops a whole sync, stopped connector sources say so (#6831); claude-cli usage-policy refusals are content blocks (#6816)
garrytanb665c41bca90
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 53acde2c0e..9d95270558 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,33 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).+## [0.60.261.0] - 2026-10-16++**One purged item no longer stops a whole Google sync, a source whose syncs keep dying now says so, and Claude refusals through `claude-cli` stop being retried forever.** If you purged a page that a connector keeps listing (a recurring calendar event whose future occurrences you deleted with `--purge`, while the series stays on the calendar), the next sync that reached it ended there. Every sync after it died the same way, so nothing more from that account was imported: no new mail, contacts or events. And every status surface said the source was fine. Now the purged item is skipped and recorded, as the purge intends, and the rest of the sync goes through. Separately, when Claude refused a prompt under its usage policy through the `claude-cli` model provider, atom extraction counted it as an ordinary error and sent the same page back to the model on every run; it now takes the same bounded give-up path as other providers' refusals.++### What you'd see++| Situation | Before | Now |+|---|---|---|+| A Google or GitHub connector lists an item whose content you purged | the whole sync job dies with `purged_content`, and so does every later one | the item is skipped and listed in `gbrain sources status` ("skipped as purged content"); everything else imports and the cursor moves on |+| A connector source's syncs keep ending on an error | `sync status`: `last_error: null`, `needs_human: false`; doctor `sync_freshness` ok until 24 h passed | `sources status` and `sync status` name the error, the item and a read-only next step; after 3 failed runs in a row the source reads STOPPED in both, and doctor `sync_freshness` warns (fails once the last good sync is past the fail age) |+| `claude-cli` answers "API Error: <model> can't help with this ... https://www.anthropic.com/legal/aup" during `extract_atoms` | counted as a generic error; the page is re-sent on every run and never given up on | treated as a content block (`claude_cli_usage_policy`); after the usual consecutive-failure limit the page is tombstoned and stops costing calls |++### If a Google source is stuck now++Upgrade to this release; the next sync skips the purged occurrence by itself and imports the backlog. Nothing to clear, no flags.++On an older release you can unblock it by hand: `gbrain pages purges list` names the purged slugs, and `gbrain pages unpurge <slug>` for the occurrence the failing job names lets that one occurrence back in so the sync can finish. Each week the next purged occurrence of the series enters the 60-day calendar window and stops the source again, so the lasting fix on an older release is ending the series (or deleting its future occurrences) in Google Calendar itself.++### 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.+- **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.+- No schema change.+## [0.60.260.0] - 2026-10-16**An approved `doctor --remediate --include-repairs` run no longer fails with `preview_changed` because autovacuum analyzed a table between the preview and the run.** Hotfix for LHF wave 2 item 6 (GBRA-107, reported by GBRA-101).diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.mdindex a826ed6ad5..44c6eceefa 100644--- a/docs/architecture/key-files/core-ai.md+++ b/docs/architecture/key-files/core-ai.md@@ -17,7 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/ai/embed-batch-plan.ts` — the embedding request plan shared by `embed()` and spend preflights: per-input truncation (`EMBED_MAX_CHARS`), the `max_batch_tokens` × safety-factor pre-split (`splitByTokenBudget`, re-exported by the gateway), the item cap (`capBatchItems`, `NO_BATCH_CAP_SUB_BATCH_ITEMS` for `no_batch_cap` recipes) and the per-request input ceiling a guard reserves (`embedRequestMaxInputTokens`: one token per UTF-8 byte, capped per text by a declared `max_input_tokens`, additive so any split or retry of the same texts stays inside it). `embedRequestCeilings(texts, model)` replays the plan for a model string without a gateway; `rerankRequestMaxInputTokens` is the rerank twin. Pinned by `test/embedding-migration-settle.serial.test.ts` and the adaptive-batch suites.- `src/core/ai/embedding-guard.ts` — the embedding refusal contract (#4616). `degenerateEmbeddingReason` flags zero-norm (L2 norm below `EMBEDDING_NORM_EPSILON`), NaN and ±Inf vectors; `sendableEmbeddingInputs` keeps empty and whitespace-only inputs away from the provider; `screenEmbeddings` / `screenAlignedEmbeddings` put vectors back at their input positions and throw `EmbeddingZeroNormError` (an `AIConfigError`, `code: embedding_zero_norm`, docs `docs/guides/write-refusals.md#embedding_zero_norm`) carrying per-item `failures` and the usable `vectors` aligned with the input (null where refused). `mergeZeroNormErrors` re-aligns per-slice refusals. `suggestionFor(slug, sourceId?)` fills the `gbrain embed <slug>` recovery command. `fitMatryoshkaPrefix(recipe, modelId, vector, expected)` (PR #5921, wave 14): when the recipe's embedding touchpoint declares the model in `matryoshka` (`{ native, prefixes }`, folded ids; `recipes/nvidia.ts` declares Nemotron-3-Embed-8B at 4096 with 1024/2048) and the provider answered at the native width for a listed target, the vector is sliced from the start and L2-normalized before `gateway.embedSubBatch`'s dim-mismatch check; every other vector returns untouched, an overflowing norm is refused, a zero or non-finite prefix falls to the per-item screen. Consumers: `gateway.embed()` and both multimodal embedders, `embedding.ts:embedBatch` (later 100-input slices still run), `embed-retry.ts` (never retried; `embedBatchKeepingUsable` returns the partial result), `embed.ts:embedPageTexts` and markdown/code imports (usable vectors stored, refused chunks stay NULL and the page signature is not stamped). Tests: `test/embedding-zero-norm-4616.serial.test.ts` (+ Postgres wrapper).-- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`). #5304: `normalizeAIError(err, context, redact, routeHint)` appends `routeHint` to a 404's fix only; `src/core/ai/model-not-found-hint.ts` renders it from the gateway's recorded provenance (`gatewayModelNotFoundHint(touchpoint, model)` → `modelRouteHint`: "Selected via models.tier.reasoning. Fix: gbrain config set models.tier.reasoning <provider>:<model>"; env and config.json pins say what to clear; a deprecated key names the `models.*` key to set instead; the built-in default names the touchpoint's tier key; unrecorded or stale provenance adds nothing) and `embeddingModelNotFoundHint()` names `embedding_model` with the doctor route, never a bare `config set`. `gateway.ts` passes it at its `embed`, `expand` and `chat` 404 sites (`test/ai/model-not-found-hint-5304.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`).+- `src/core/ai/errors.ts` — error normalization and classification. One private generator, `wrappedErrorLayers`, opens a thrown error's wrappers outermost first (`cause`, else RetryError's `lastError`; objects only, at most five layers, a repeated layer ends the walk). `isStructuredOutputRejection` and `readProviderFailureSignals` use it; the latter returns the first finite `status`/`statusCode`/`apiErrorStatus` plus every string `name` and `code` and never throws (a throwing getter ends the walk). `page-summary.ts` `classifyChatError` reads those signals, so a wrapped claude-cli 429, an AI SDK RetryError's 429/5xx or a `TimeoutError`/network code on `cause` classifies as rate_limit/provider_5xx/timeout/network instead of `malformed` (which drops the page to the title tier). `classifyGlobalLlmError` keeps its own depth-3 loop over `cause ?? lastError`, so a 404 there halts as `model_not_found`; the model-not-found phrases (`model_not_found`, `not_found_error`, "does not exist or you do not have access", "does not have access to [the] model") are tested before the status map, so a provider 403 that denies a project access to a model classifies `model_not_found` with the model fix, never `auth` (a plain 401/403 stays `auth`; `test/ai/model-not-found-class.test.ts`). #5304: `normalizeAIError(err, context, redact, routeHint)` appends `routeHint` to a 404's fix only; `src/core/ai/model-not-found-hint.ts` renders it from the gateway's recorded provenance (`gatewayModelNotFoundHint(touchpoint, model)` → `modelRouteHint`: "Selected via models.tier.reasoning. Fix: gbrain config set models.tier.reasoning <provider>:<model>"; env and config.json pins say what to clear; a deprecated key names the `models.*` key to set instead; the built-in default names the touchpoint's tier key; unrecorded or stale provenance adds nothing) and `embeddingModelNotFoundHint()` names `embedding_model` with the doctor route, never a bare `config set`. `gateway.ts` passes it at its `embed`, `expand` and `chat` 404 sites (`test/ai/model-not-found-hint-5304.test.ts`); the `--- raw ---` phrase barrier and billing-over-429 precedence hold (`test/synopsis-chat-failure-class.test.ts`, `test/ai/classify-global-llm-error.test.ts`). #6816: `providerContentBlockReason` also returns `claude_cli_usage_policy` for the claude-cli adapter's usage-policy refusal (`ClaudeCliProcessError`, no `apiErrorStatus`, `claude-cli reported error: API Error:` prefix, the AUP link and a refusal phrase: `CLAUDE_CLI_REFUSAL_RE`); `test/claude-cli-refusal-6816.test.ts`.- `src/core/ai/gateway.ts` — unified seam for every AI call. The `ai` SDK loads at the first provider call (lazy default transports), not on configure. `embedQuery(text, opts?)` and `isAvailable(touchpoint, modelOverride?)` accept a model override so the resolved-column path embeds via the column's provider (Voyage / OpenAI) instead of the global default; the hybrid path passes `{embeddingModel: resolved.provider, dimensions: resolved.dimensions}` and the gateway resolves the matching recipe via `instantiateEmbedding()`. `isAvailable('embedding', 'voyage:voyage-3-large')` checks the override's recipe (not the default) so hybrid skips vector search only when the active column's provider is actually down. `voyageCompatFetch` adapts Voyage embedding requests and responses; `openAICompatAsymmetricFetch` threads explicit query/document input types for other compatible recipes through the SDK boundary. `gateway.rerank()` native HTTP path (no AI-SDK reranking abstraction): resolves the EFFECTIVE reranker as `input.model ?? getRerankerModel() ?? DEFAULT_RERANKER_MODEL` (imported from `ai/defaults.ts`; `voyage:rerank-2.5`), posts to the recipe's reranker path (`touchpoints.reranker.path`, default `/rerank`; supported recipes declare their path explicitly) with bearer auth — the request's top-N key is recipe-pluggable via `touchpoints.reranker.top_param` (default `top_n`; Voyage `top_k`) — and returns `RerankResult[]` sorted by relevance. `no_key` preflight: after `requireConfig()`, a recipe without a custom `resolveAuth` whose `auth_env.required` key is absent from `cfg.env` throws `RerankError('no_key')` BEFORE any HTTP — `noKeyOnce()` writes ONE `no_key` audit row per process per model without a stderr line, avoiding per-query noise. `auth` therefore means "key present but rejected" (HTTP 401/403). `RerankError.reason` classifier: `auth | no_key | rate_limit | network | timeout | payload_too_large | unknown`. 5s default timeout (search hot path). Pre-flight payload guard rejects bodies over `recipe.touchpoints.reranker.max_payload_bytes` with `reason: 'payload_too_large'`. `_rerankTransport` test seam mirrors `_embedTransport`. `embedQuery(text)` threads `inputType: 'query'` through `dimsProviderOptions()` (4-arg). `getRerankerModel()` returns only the EXPLICITLY configured model (callers need not pre-check availability — `rerank()` fails `no_key` itself; the sync readiness predicate for dashboards is `reranker-readiness.ts`) + `isAvailable('reranker')` branch; `configureGateway` + `reconfigureGatewayWithEngine` thread `reranker_model`; `applyResolveAuth` + `defaultResolveAuth` widen touchpoint param to include `'reranker'`. `embedMultimodalOpenAICompat()` routes recipes with `implementation: 'openai-compatible'` (LiteLLM, Anyscale, vLLM, Gemini multimodal via proxy) through the standard `/embeddings` endpoint with content arrays carrying `image_url` entries; the Voyage `/multimodalembeddings` path is unchanged (gateway selects by recipe `implementation` tag). Runtime dimension validation throws `AIConfigError` (with model id + observed + expected) before the vector reaches storage when the provider returns a width that doesn't match the recipe's `default_dims` or the brain's `embedding_dimensions`. Pinned by `test/openai-compat-multimodal.test.ts`. Module-scoped `_embedTransport` defaults to AI SDK `embedMany`, with `__setEmbedTransportForTests(fn)` test seam so tests drive `embed()` with a stubbed transport. `splitByTokenBudget` and `isTokenLimitError` exported `@internal` (pure functions reused by the test file). Module-level `_shrinkState: Map<recipeId, {factor, consecutiveSuccesses}>` halves the recipe's effective `safety_factor` on token-limit miss (floor 0.05) and heals back ×1.5 after `SHRINK_HEAL_AFTER=10` consecutive successes. `configureGateway()` walks every registered recipe at construction and emits a once-per-process stderr warning for any embedding touchpoint missing `max_batch_tokens` (excluding the canonical OpenAI fast-path). `resetGateway()` clears `_shrinkState`, the warned-set, and restores the real transport. `embedMultimodal()` reads `cfg.embedding_multimodal_model` first (falls back to `cfg.embedding_model`); after the recipe-level `supports_multimodal` fast-fail, validates the resolved model against `touchpoint.multimodal_models` when declared (closes the Voyage-text-only-into-multimodal-endpoint footgun before any HTTP call). `getMultimodalModel()` accessor mirrors `getEmbeddingModel` / `getChatModel`. `src/core/ai/multimodal-model.ts:multimodalEmbeddingModel()` answers the model `embedMultimodal()` would use when it passes those same recipe and allow-list checks (null otherwise, or when the gateway is unconfigured); hybrid search routes an inferred image intent and the LLM modality tie-break to the image arm only when it is set (`test/cross-modal-hybrid-integration.serial.test.ts`). Exported `VoyageResponseTooLargeError` tagged class: `voyageCompatFetch`'s two OOM-defense caps (Layer 1 Content-Length, Layer 2 per-embedding base64) throw it; the inbound response-rewriter's try/catch (which swallows parse failures so misshaped responses fall through to the SDK parser) checks `instanceof VoyageResponseTooLargeError` and rethrows so the cap is actually effective (`test/ai/gateway.test.ts` drives both layers through `embed()`). AI SDK v6 toolLoop compat (`gbrain skillopt` rollouts AND production background `subagent` jobs both route through `chat()` / `toolLoop`): in `chat()`, tool defs wrap the raw JSON Schema with the SDK's `jsonSchema()` helper (`inputSchema: jsonSchema(t.inputSchema)`) — v6's `asSchema()` treats a bare `{jsonSchema: ...}` object as a thunk and throws "schema is not a function"; exported pure `toModelMessages(messages: ChatMessage[]): unknown[]` converts gbrain's provider-neutral `ChatMessage[]` into v6 `ModelMessage[]` — tool results (pushed by `toolLoop` as `role:'user'` with bare-value tool-result blocks) become a dedicated `role:'tool'` message with structured `output:{type:'json'|'text'|'error-text', value}` parts; `null` output preserved as `{type:'json', value:null}` (not dropped); text/tool-call blocks pass through with v6 field names (`toolCallId`/`toolName`/`input`); applied at the `generateText` call (`messages: toModelMessages(opts.messages)`). The converter is load-bearing for the production subagent path, not just skillopt. Pinned by `test/gateway-model-messages.test.ts`. Companion: `src/core/skillopt/rollout.ts` builds tool schemas through the shared `paramDefToSchema` from `src/mcp/tool-defs.ts` (single source of truth, recursive on items/enum/default), never an inline converter. Provider-agnostic plumbing: `resolveNativeBaseUrl(provider, cfg)` normalizes a configured `ANTHROPIC_BASE_URL` / `OPENAI_BASE_URL` to carry the `/v1` suffix and is passed explicitly at every native `createAnthropic` / `createOpenAI` site (chat/expansion/embedding), so an env-injected bare host doesn't 404; returns `undefined` when unset so the SDK default is preserved (Google too: `docs/ai-providers/google.md`). `diagnoseEmbedding` fails closed with `user_provided_dims_unset` when a user-provided / zero-default recipe (litellm/llama-server) has no configured `embedding_dimensions`. `configureGateway` does not backfill `embedding_dimensions` (readers default it themselves), keeping the "no dims set" signal honest for that guard and the multimodal skip. `withBudgetTracker`: gateway-layer enforcement via `AsyncLocalStorage<BudgetTracker>`. `withBudgetTracker(tracker, fn)` installs the tracker on the module-internal store; every `gateway.chat / embed / rerank` call inside the scope auto-composes (reserve before, record in try/finally). Outside-scope calls are budget no-ops. Nested scopes restore the outer tracker on exit. `getCurrentBudgetTracker()` is the test seam. The chat path uses the pessimistic fallback on error paths; the embed path estimates input tokens from char count × recipe's `chars_per_token` because the AI SDK doesn't surface per-batch embed token usage; the rerank path estimates char count of query+docs. Pinned by 6 unit cases. `reconfigureGatewayWithEngine(engine)` (async, called from `cli.ts` after `engine.connect()`, before every command except `CLI_ONLY` no-DB commands) re-resolves expansion + chat defaults through `resolveModel()` so `models.tier.*` and `models.default` overrides apply to both. `DEFAULT_CHAT_MODEL` is `anthropic:claude-sonnet-4-6`. `ChatOpts.timeoutMs` replaces the default chat backstop (`GBRAIN_AI_CHAT_TIMEOUT_MS`, 300 s) for one call and `ToolLoopOpts.turnTimeoutMs` forwards it to every turn (the subagent handler's per-turn cap, #4921); `ChatOpts.thinking: 'off'` maps per route through `thinking-off.ts` (#5331). `ChatOpts.temperature` is threaded verbatim to the AI SDK `generateText` call (unset → the provider's default; the LongMemEval judge pins `0`, the official `evaluate_qa.py` setting). `ChatResult.responseModel` carries the model id the PROVIDER reported (`response.modelId`, e.g. a dated snapshot) when the SDK surfaced one and is absent otherwise, while `model` stays the requested `provider:modelId`; eval receipts pin the two side by side (`reader_model_snapshot`, `judge_model_snapshot`). `__setChatTransportForTests` mirrors `__setEmbedTransportForTests` so tests drive `chat()` with a stubbed transport. `toolLoop` per-turn permit hook: optional `acquireTurnPermit()` acquires a provider permit before EVERY round-trip and releases in finally; a lease-full throw propagates without consuming the turn (the subagent path wires it to the rate leases with provider-derived keys — Anthropic models share `anthropic:messages`, others get `<recipeId>:chat`). `ToolLoopStopReason` includes `'length'`: a zero-tool-call turn that hit the output cap propagates 'length' instead of folding into 'end', so truncation is never reported as a clean finish; and `'empty_response'` (#6448): a zero-tool-call clean stop whose text is empty or whitespace-only, so a refusal body or thinking-only turn is never reported as a finished answer (the subagent handler maps it to `error`). Per-part provider state: `ChatBlock` variants carry optional `providerMetadata` captured from SDK parts in `chat()` and re-emitted as `providerOptions` on the rebuilt parts in `toModelMessages()` (attached only when present — metadata-free blocks stay byte-identical); this is the Gemini 3.x thoughtSignature echo. `isThinkingByDefaultModel(modelStr)` (exported) matches Claude 5-family ids behind any provider-prefix chain with a letters-only family segment (never `claude-3-5-*`); `isThinkingModel(modelStr)` (exported) is that regex OR the recipe's chat `thinking_by_default` capability (fail-closed: unknown/chat-less recipes are non-thinking) and drives `defaultMaxOutputTokens`'s 32k thinking headroom for chat()/toolLoop() callers that omit maxTokens (e.g. `gbrain skillopt` rollouts) and the subagent handler's `resolveMaxOutputTokens`; think/index.ts shares the regex and makes the same capability check. Pinned by `test/ai/gateway-thinking-headroom.test.ts`. `expand()` and `generateOcrText()` also record on the ambient tracker (they call generateObject/generateText directly and never pass through `chat()`'s `_recordBudget`): record-only, no reserve — a breach surfaces on the NEXT reserving call, matching `chat()`'s swallow of `BudgetExhausted` from `record()`. Successes record normalized SDK usage via `normalizeSdkUsage` (the ONE home for the v6/legacy usage shapes, used by chat's success path too; first FINITE field wins so a NaN v6 field can't shadow a real legacy value or poison the running total); failures record pessimistically under `gateway.expand.failed` / `gateway.ocr.failed` (a rejected attempt still billed provider tokens — one expand() can legitimately produce two records when the structured-output attempt fails and the text fallback runs). A recipe whose declared structured-output support is rejected at call time is remembered for the process lifetime (`_structuredOutputRejectedRecipes`) so the rejected attempt isn't re-paid on every call. OCR's input estimate is prompt text + a fixed per-image token constant, never base64 length (bytes are not tokens). `generateOcrText()` routes to `getImageOcrModel()` — `embedding_image_ocr_model` when set, else the expansion model — gated by `isAvailable('expansion', <ocr model>)` so a misconfigured OCR model (provider without an expansion touchpoint, or unkeyed) fails closed to `''` instead of silently OCRing with the expansion model; the accessor mirrors `getMultimodalModel()`, `configureGateway`/`buildGatewayConfig` thread the field, and an unconfigured gateway stays a silent `''` no-op. Pinned by `test/ai/ocr-model-routing.test.ts`. `__setGenerateObjectTransportForTests` mirrors the generateText seam. `ChatOpts.responseSchema` (`{ name, description?, schema }`) is honored ONLY when the resolved recipe is openai-compatible AND declares `supports_structured_outputs`: `chat()` attaches a tolerant `Output` spec (`jsonSchemaOutput` — carries the `{ type: 'json', schema, name }` responseFormat the provider turns into `response_format: json_schema`, and `parseCompleteOutput` hands the raw text back instead of throwing `NoObjectGeneratedError` the way `Output.object` does on unparseable text) to the generateText call, so `result.text`, stopReason mapping, budget recording and the caller's own parse + retry lane run unchanged; native / claude-cli lanes and undeclared openai-compatible recipes never see the field. A declared recipe whose backend REJECTS the schema at call time (`isStructuredOutputRejection` in `errors.ts`: a request-shaped 4xx naming `response_format` / `json_schema` / structured output — never a 5xx or an unrelated 400) gets ONE schemaless retry plus one warn line, and lands in `_structuredOutputRejectedRecipes` so later `chat()` and `expand()` calls skip the schema for the process lifetime instead of re-paying the rejection on every retry lane. + `test/core/budget/expand-records-budget.test.ts` + `test/ai/gateway-ocr-budget.test.ts` + `test/facts-extract-structured-output.test.ts` Tracker recording goes through `src/core/ai/budget-record.ts:recordOnTracker` (fail-open: a cap breach on `record()` surfaces on the next `reserve()`); every chat/toolLoop/expand/embed/rerank/OCR record site passes the requested model, `purpose` (optional on `ChatOpts` + toolLoop opts; skillopt sets `skillopt.optimizer|target|judge`, engine-internal calls leave it null), `failed` on failure paths, `countsAsCall: false` for expand's structured-output fallback attempt and `estimated` when tokens are char-estimated. `reconfigureGatewayWithEngine` records the expansion/chat `ResolveSource` (`file_config` for the servable config.json pin) in `src/core/ai/gateway-model-sources.ts`; its getters answer only while the gateway still routes to the recorded model, so a later reconfigure reads as unknown instead of stale provenance. `embedQuery` caches query vectors per process (`src/core/ai/query-embed-cache.ts`: 512-entry LRU, 10-min TTL), keyed by recipe, model id, `base_urls` override, effective dims and the exact provider input (prefix + text). It stores only resolved vectors, as copies; the cache clears with `_modelCache` (configure, env refresh, engine re-stamp, reset, `__setEmbedTransportForTests`) and a generation counter drops an embed straddling a clear. Document-side `embed()` is never cached; a caller under an AI invocation guard skips the cache read. **Prompt-cache breakpoints:** `cacheSystem: true` on a prompt-cache-capable route derives ONE `cacheControlValue` (config TTL override honoured) that marks the system block, the last tool def, the call-level auto marker and, since PR #6341, any user text `ChatBlock` flagged `cache: true` (`toModelMessages(messages, cacheControlValue)` merges `providerOptions.anthropic.cacheControl` onto that block); without a value the flag is dropped and the block is plain text, so non-caching routes and the claude-cli adapter (which joins text parts with `\n`) see the same prompt text. Pinned by `test/page-summary-prompt-cache.test.ts`.- `src/core/ai/chat-fallback.ts`: the `chat_fallback_chain` consumer. `gateway.chat()` hands a call to `chatWithFallback` when a chain is configured and the caller did not pass `allowFallback: false`; `configureGateway` normalizes the chain with `normalizeChatFallbackChain` (a comma-separated string, the env and DB form, is split). Attempts run the call's own model, then each chain entry not already tried (`chatFallbackAttempts`), each as a complete single-model `chat()`, so budget, usage ledger, guardrails and `ChatResult.model` follow the model that ran; an answer from a chain entry also carries `ChatResult.fallbackFrom` (the call's own model). A provider error (a claude-cli subscription limit arrives as `apiErrorStatus` 429) or a structural refusal (`stopReason` `refusal`/`content_filter`) moves to the next model with one `[ai.gateway]` stderr line, and the first hop of a process queues one `chat_fallback_hop` safety notice in `fallback-hop-queue.ts`; with `chat_fallback_on_refusal: false` (`ChatFallbackOptions.onRefusal`, passed by `chat()` from the gateway config) a structural refusal is returned and a provider content block (`providerContentBlockReason`: a Gemini prompt block, or an HTTP 400 content-policy body such as OpenAI `invalid_prompt`, Azure `content_filter` or DeepSeek "Content Exists Risk") is thrown instead of being sent on, while provider errors still fall back; a policy refusal (`isAIInvocationPolicyError` or a BudgetTracker `BudgetExhausted`, including an unpriced chain entry under an explicit cap) or the caller's own abort stops the chain, and a cancel that lands while an attempt refuses returns that refusal instead of forwarding it; an earlier refusal is returned in preference to a later error, otherwise the call's own model's error is thrown (the last failure logged), so retry and halt classification follow the configured model. `toolLoop` forwards `allowFallback` to every turn. Judge, critic and eval call sites pin their model: brainstorm judges, grade_takes, drift, the edge_contradictions judge (apply mode defaults from a per-model certification), voice-gate, eval-contradictions, notability-eval, takes-quality-eval, cross-modal eval, skillopt (judge, optimizer, rollouts), the LongMemEval reader and judge, the functional-area-resolver harness, the `models doctor` / `providers test` probes, `decide()` (its egress gate cleared one provider), `auto_think` (its BudgetMeter priced one model), and `think` with an explicit `--model`; the synthesize triage and concept synthesis fall back. Pinned by `test/ai/gateway-chat-fallback.test.ts` and `test/ai/chat-fallback-on-refusal.test.ts` (refusal switch through the real loader on every plane, the once-per-process hop notice).diff --git a/docs/architecture/key-files/core-persistence-continued.md b/docs/architecture/key-files/core-persistence-continued.mdindex 5322f4625b..4cf4f2b5a7 100644--- a/docs/architecture/key-files/core-persistence-continued.md+++ b/docs/architecture/key-files/core-persistence-continued.md@@ -26,9 +26,9 @@ 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.+- `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-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.+- `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.- `src/core/connectors/item-holds-store.ts` + `connector-hold-session.ts` — reads holds from the cursor state (managed checkpoint row or the unmanaged state file) for `sources status`, doctor `connector_held_items` and `open_loops` completeness; the `connector-hold-retry` request rows and the pending `managed-connector-retry` pointers `sources retry-held` writes; the per-run session that skips held items, publishes holds on a managed abort (`publishHolds`), releases held items' terminal receipts from the automatic retry set and consumes retry-held keys. Git-source holds are not read here: only `sources status` (`persistence/connector-status.ts` `readGitHoldStatuses`, `sources status <id>` filters to one source) and `sources retry-held` (a Git source records a `sync-hold-retry` re-screen request for its held paths; `gbrain sync --retry-held` refuses with that pointer) show them beside connector holds. Writer deactivation and activation never read or block on them.- `src/core/connectors/connector-text.ts` — #5752 render boundary: prose sanitized with `sanitizeForJsonb` before the no-op screen; identity fields refuse with `invalid_connector_text`.diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 9620aa4296..30c9893533 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -196,7 +196,7 @@ with each file and fix the ones that need no guessing."*| <a id="file_too_large"></a>`file_too_large` | Over the page size limit: 24 MiB for a Markdown page, 5 MB for a code file ([limits per entry point](memory-boundaries.md#large-page-limits)). Every page under the limit is stored, chunked and searchable whatever its size, so this hold only fires above it, and the same bytes are held on every retry. A smaller page refused by an MCP or HTTP transport limit is a different refusal: send it by file. | Leave the file out of the source: read `gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,<path>'`; or, if it must be in the brain, split it into files under the limit and commit. The next `gbrain sync --source <source> --no-pull` clears the hold. || <a id="managed_image_sync_unsupported"></a>`managed_image_sync_unsupported` | Managed sync imports image files only while multimodal embedding is on (`GBRAIN_EMBEDDING_MULTIMODAL=true`): the image page, its OCR text and its image vector are built by the coordinated image importer at preparation, and `source_path` is recorded. While multimodal embedding is off, each image import is held with this code instead of refusing the whole sync (#5493); deleting or renaming an image still reconciles its page. These holds count as missing coverage (the image is not searchable) but never escalate, because they are not a content fault. | Nothing is broken. To import the images, set `GBRAIN_EMBEDDING_MULTIMODAL=true` on the owner and run `gbrain sync --source <source> --no-pull`: the next discovery re-screens every image hold and imports the files (#6529). To stop holding them instead, leave them out of the source (`gbrain config get sync.exclude`, then `gbrain config set sync.exclude '<current list>,**/*.png'`); that clears the holds on the next sync. A held image is also re-screened when it changes and on `gbrain sources retry-held <source>`. || <a id="content_rejected"></a>`content_rejected` | The content-sanity gate matched junk and the operator set `content_sanity.junk_disposition` to `reject`, so the file is never imported and always visible. | Remove the matched junk from the file, or ask the user whether `junk_disposition` should go back to `quarantine`; that setting is the user's decision. |-| <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host. See [expire versus purge](memory-boundaries.md#purge). |+| <a id="purged_content"></a>`purged_content` | The file (or written content) has the content hash of a page the owner purged with `gbrain delete <slug> --purge`, under any slug, or carries a purged claim the database refuses. Purge leaves a text-free tombstone so a stale file, re-sync or revert cannot bring the content back. | Delete or edit the file and commit; an edited file imports normally. Only if the purge was a mistake, the owner lists tombstones with `gbrain pages purges list` and clears one with `gbrain pages unpurge <slug>` on the brain host. A Google or GitHub connector item refused this way is skipped and the sync continues; `gbrain sources status` lists it ("skipped as purged content"). See [expire versus purge](memory-boundaries.md#purge). || <a id="write_gate_rejected"></a>`write_gate_rejected` | The source is untrusted, the file reads like an instruction to an agent (an override, a standing rule, an exfiltration or credential request), and the operator set `write_gate.external_mode` to `reject`, so the file is never imported and always visible. | Tell the user; whether to edit the file or switch `write_gate.external_mode` back to `quarantine` is their decision. || <a id="rename_held"></a><a id="rename_held-rename_source_changed"></a>`rename_held` (`rename_source_changed`) | A renamed file's hold cleared, but the page it was renamed from changed after the rename was recorded, so the page did not move. | `gbrain repair frontmatter --source <source> --include-ambiguous` proposes re-binding the rename to the old page's current revision; apply after the user agrees. Or restore the old file name. || <a id="concurrent_write"></a>`concurrent_write` | Managed sync was importing a newer Git version of the file while a database-only write (write-through off, a sandboxed or derived write) committed a different version of the same page, so the two diverge (#6194). The proof is the page's revision itself: it was written by a committed non-sync request for that page. Neither version was overwritten: the page keeps the database version, the file is held and the rest of the source syncs. Since #6340 a page that moved with no such request to name is held the same way (the hold records `page_revision` and `expected_revision` instead of a competing request), and so is a page that changed, was deleted or was re-bound in the database between the manifest freeze and the entry's turn; a page that still holds exactly what the file would import is re-bound to its new revision and passed. | `gbrain sources status <source>` names the page and the competing request. Preview with `gbrain sources reconcile <source> <slug> --preview`, decide with the user which content wins, apply the resolved preview, then `gbrain sources retry-held <source>` and `gbrain sync --source <source> --no-pull` re-screen the file. A new commit of the file re-screens it too. |diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.tsindex f16e74a374..2e9a0d6fa2 100644--- a/src/commands/doctor/checks/extraction-sync.ts+++ b/src/commands/doctor/checks/extraction-sync.ts@@ -35,7 +35,7 @@ import { readOnlyCatalogPackSourceIds } from '../../../core/shared-skills/adopteimport { connectorAuthorities } from '../../../core/persistence/connector-authority.ts';import { parseSourceConfig } from '../../../core/sources-load.ts';import { checkError } from '../check-fix.ts';-import { firstSyncRunning, noSuccessfulSync, type SyncOutcomeEntry } from '../sync-outcome.ts';+import { firstSyncRunning, noSuccessfulSync, stoppedConnectorIssues, type SyncOutcomeEntry } from '../sync-outcome.ts';import { haltReasonsWithUnknown, readRecordedHaltReasons7d, topHaltReason } from '../../../core/extract/rollup-writer.ts';/** Local aliases; the shared warn-once memo lives in core so it can't fork per module. */@@ -1259,8 +1259,7 @@ export async function checkSyncFreshness(catch (error) { if (!isOwnedContentSchemaMissing(error)) throw error; }// #6076: an adopted read-only catalog pack (no commit history) has nothing to sync.const catalogPacks = await readOnlyCatalogPackSourceIds(engine, sources, localOnly);- let writer_owned_count = 0;- let read_only_pack_count = 0;+ let writer_owned_count = 0, read_only_pack_count = 0;// v0.41.27.0: D6 count math. Every source falls into// EXACTLY ONE bucket per iteration. Invariant pinned by unit test:// unchanged + synced_recently + stale + writer_owned + read_only_pack counts === sources.length@@ -1269,8 +1268,7 @@ export async function checkSyncFreshness(let unchanged_count = 0;let synced_recently_count = 0;let stale_count = 0;- let hasWarnings = false;- let hasFailures = false;+ let hasWarnings = false, hasFailures = false;// BUG 4 (v0.42.x): a source with a LIVE, non-expired per-source sync lock is// actively syncing RIGHT NOW — it must not read as stale or never-synced.@@ -1312,8 +1310,8 @@ export async function checkSyncFreshness(const stalenessCeilingSeconds = resolveStalenessCeilingSeconds();let managed = false;try { managed = await persistenceEnabledForHealth(engine); } catch { /* pre-persistence brain */ }- let upstream_unknown_count = 0;- let upstream_behind_count = 0;+ let upstream_unknown_count = 0, upstream_behind_count = 0;+ const stoppedConnectors = await stoppedConnectorIssues(engine, sources, now - failMs).catch(() => new Map());for (const source of sources) {if (ownedContent.has(source.id)) { writer_owned_count++; continue; }if (catalogPacks.ids.has(source.id)) { read_only_pack_count++; continue; }@@ -1370,6 +1368,8 @@ export async function checkSyncFreshness(continue;}+ const stopped = stoppedConnectors.get(source.id);+ if (stopped) { issues.push(stopped.issue); stale_count++; hasFailures ||= stopped.fail; hasWarnings ||= !stopped.fail; continue; }if (!source.last_sync_at) {const never = await noSuccessfulSync(engine, source.id, display, managed);issues.push(never.issue); outcomes.push(never.entry);diff --git a/src/commands/doctor/sync-outcome.ts b/src/commands/doctor/sync-outcome.tsindex d44ad3c968..4d238e4ad2 100644--- a/src/commands/doctor/sync-outcome.ts+++ b/src/commands/doctor/sync-outcome.ts@@ -61,3 +61,23 @@ export async function noSuccessfulSync(engine: BrainEngine, sourceId: string, diheld: attempt.held, job_id: attempt.job_id, fix },};}++/**+ * #6831: sync_freshness's verdict for each Google or GitHub connector source whose last CONNECTOR_STOPPED_RUNS or more+ * runs ended on an error. Such a source imports nothing, but its last_sync_at can still look recent, so freshness alone+ * reads it as healthy. The line names the error, the item and the read-only next step; it is a failure once the source's+ * last successful sync is older than `failBeforeMs` (sync_freshness's fail age), a warning before that.+ */+export async function stoppedConnectorIssues(engine: BrainEngine, sources: Array<{ id: string; last_sync_at: string | Date | null }>,+ failBeforeMs: number): Promise<Map<string, { issue: string; fail: boolean }>> {+ const { readConnectorLastError } = await import('../../core/persistence/connector-status.ts');+ const issues = new Map<string, { issue: string; fail: boolean }>();+ for (const source of sources) {+ const failure = await readConnectorLastError(engine, source.id);+ if (!failure?.stopped) continue;+ issues.set(source.id, { fail: !source.last_sync_at || new Date(source.last_sync_at).getTime() < failBeforeMs,+ issue: `Source '${source.id}' is STOPPED: its last ${failure.consecutive} connector syncs ended on ${failure.code}${failure.slug ? ` at ${failure.slug}` : ''} `+ + `(last ${failure.at.slice(0, 16).replace('T', ' ')}), so nothing from it is imported; inspect with \`${failure.fix.argv!.join(' ')}\`` });+ }+ return issues;+}diff --git a/src/commands/sync/operator.ts b/src/commands/sync/operator.tsindex d090801d9d..fa1987cc95 100644--- a/src/commands/sync/operator.ts+++ b/src/commands/sync/operator.ts@@ -108,6 +108,8 @@ export async function runSyncStatus(engine: BrainEngine, args: string[]): Promisfor (const b of t.active_blockers) console.log(` BLOCKING ${b.kind}: request ${b.request_id}${b.slug ? ` (${b.slug})` : ''} [${b.category}]`);if (t.active_blockers.length || t.unresolved.rows) console.log(` drill down: ${t.drill_down.join(' ')}`);}+ const connector = status.connector_last_error;+ if (connector) console.log(` connector: ${connector.stopped ? 'STOPPED, ' : ''}the last ${connector.consecutive} run(s) ended on ${connector.code}${connector.slug ? ` at ${connector.slug}` : ''}: ${connector.message}`);for (const notice of notices) console.log(` [gbrain notice ${notice.code}] ${notice.why}`);if (rendered.next) console.log(` Next: ${rendered.next.command ?? rendered.next.argv?.join(' ')}\n Why: ${rendered.next.why}`);else console.log(' Next: nothing; the source is synced and holds nothing.');diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.tsindex 7443145224..85d3fb28cd 100644--- a/src/core/ai/errors.ts+++ b/src/core/ai/errors.ts@@ -172,12 +172,28 @@ function contentPolicy400Reason(responseBody: string): string | undefined {return error?.message === 'Content Exists Risk' ? 'content_exists_risk' : undefined;}+/**+ * #6816: Claude Code reports a usage-policy refusal as an error envelope with no API status, which the claude-cli+ * adapter surfaces as `claude-cli reported error: API Error: ...`. The wordings it has used all link the policy:+ * "<model> can't help with this. Start a new session to continue. ... https://www.anthropic.com/legal/aup",+ * "<model>'s safeguards flagged this message (https://www.anthropic.com/legal/aup)" and, before 2.1.219,+ * "Claude Code is unable to respond to this request, which appears to violate our Usage Policy (https://www.anthropic.com/legal/aup)".+ * Only that adapter error counts: the anchored prefix, no API status, the policy link and one of the refusal phrases.+ */+const CLAUDE_CLI_REFUSAL_RE = /^claude-cli reported error: API Error: (?=[\s\S]*https:\/\/www\.anthropic\.com\/legal\/aup)[\s\S]*(?:can['\u2019]t help with this|violate our Usage Policy|safeguards flagged this)/;++function claudeCliRefusal(value: { name?: unknown; message?: unknown; apiErrorStatus?: unknown }): boolean {+ return value.name === 'ClaudeCliProcessError' && value.apiErrorStatus === undefined+ && typeof value.message === 'string' && CLAUDE_CLI_REFUSAL_RE.test(value.message);+}+/** A provider refusal tied to the prompt, even when the SDK wraps its response. */export function providerContentBlockReason(err: unknown): string | undefined {for (let depth = 0; depth < 8 && err != null; depth++) {try {if (typeof err !== 'object') break;- const value = err as { responseBody?: unknown; statusCode?: unknown; status?: unknown; cause?: unknown };+ const value = err as { responseBody?: unknown; statusCode?: unknown; status?: unknown; cause?: unknown; name?: unknown; message?: unknown; apiErrorStatus?: unknown };+ if (claudeCliRefusal(value)) return 'claude_cli_usage_policy';if (typeof value.responseBody === 'string' && (value.statusCode === 400 || value.status === 400)) {const reason = contentPolicy400Reason(value.responseBody);if (reason) return reason;diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c923743538..5784a6c8e3 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -692,6 +692,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.258.0', text: 'A connector source\'s autopilot cycle now extracts facts and recomputes emotional weight only for that source\'s pages changed since its last completed cycle. Before, both phases walked every page in the brain on every connector cycle, which on a large brain ran past the 30-minute job deadline, so the cycle never finished and repeated the full walk.' },// LHF wave 2 item 0 (GBRA-94): tokenmax `query` no longer expands by default.{ since: '0.60.259.0', text: '`gbrain query` no longer runs LLM query expansion by default on `tokenmax`, so no search mode expands by default. On 300 LongMemEval-S questions with the reranker, `query` without expansion kept retrieval within noise (298 vs 299 of 300) and its p50 fell from about 2 s to about 230 ms (gbrain-evals expansion-latency report, 2026-10-14). To keep expanding: `gbrain config set search.expansion true` for the brain, or pass `--expand` / `expand: true` per call.' },+ // #6831 + #6816 hotfix. `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.+ { since: '0.60.260.0', text: 'A managed Google or GitHub connector item whose content matches a page purge tombstone is now skipped, and the rest of the sync continues (#6831). Before, the pages guard\'s `purged_content` refusal of that one item ended the whole sync job, and every later sync of the source died the same way. Skipped items are listed in `gbrain sources status` ("skipped as purged content"), and `gbrain pages unpurge <slug>` lets one back in. Every other failed connector write still ends the run.' },+ { since: '0.60.260.0', text: 'A connector source whose syncs keep ending on an error now says so (#6831): `gbrain sources status` names the error, the item and a read-only next step, and reads STOPPED after 3 failed runs in a row; `gbrain sync status --json` adds `connector_last_error` and, when nothing else applies, a `next` naming its read-only fix; doctor `sync_freshness` warns about a STOPPED source even when its last good sync was recent (fails past the fail age). `last_error` is unchanged for connector sources.' },+ { since: '0.60.260.0', text: 'A `claude-cli` usage-policy refusal ("API Error: <model> can\'t help with this ... https://www.anthropic.com/legal/aup", and the older "violate our Usage Policy" and "safeguards flagged this" wordings) is now a provider content block (`claude_cli_usage_policy`, #6816): `extract_atoms` tombstones the item after its consecutive-failure limit instead of re-sending it every run, and with `chat_fallback_on_refusal: false` the prompt is not sent on to the next model in `chat_fallback_chain`. Other `claude-cli` errors are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/persistence/connector-state.ts b/src/core/persistence/connector-state.tsindex b6f0a469c6..0850d56805 100644--- a/src/core/persistence/connector-state.ts+++ b/src/core/persistence/connector-state.ts@@ -40,6 +40,29 @@ export interface ConnectorRunCounts {stopped_on_wait_budget: boolean;dropped_upstream: number;finished_at: string;+ /** #6831: items the pages guard refused as purged content this run; each was skipped and the run went on. */+ purged_skipped?: number;+}++/** #6831: one connector item whose content matches a page purge tombstone, skipped instead of written. */+export interface ConnectorPurgedItem {+ slug: string;+ /** The refused receipt, or null when the item was screened out before admission. */+ request_id: string | null;+ at: string;+}++/**+ * #6831: the last connector run that ended on an error instead of finishing.+ * `consecutive` counts runs in a row that ended this way; a run that finishes clears it.+ */+export interface ConnectorRunFailure {+ code: string;+ message: string;+ slug: string | null;+ request_id: string | null;+ at: string;+ consecutive: number;}export type UpgradeRecovery = 'resumed' | 'rewalking_once' | 'none';@@ -67,8 +90,17 @@ export interface ConnectorState {* still digests to `config_digest`; a sync that passes the check clears it.*/account_mismatch?: ConnectorAccountMismatch | null;+ /** #6831: the most recent purged items connector runs skipped (newest first, at most CONNECTOR_PURGED_LIMIT). */+ purged_items?: ConnectorPurgedItem[];+ /** #6831: set while the source's connector runs keep ending on an error; cleared by a run that finishes. */+ last_failure?: ConnectorRunFailure | null;}+/** #6831: how many skipped purged items the state row keeps. */+export const CONNECTOR_PURGED_LIMIT = 20;+/** #6831: this many connector runs in a row that ended on an error read as a stopped source in `sources status` and doctor. */+export const CONNECTOR_STOPPED_RUNS = 3;+export interface ConnectorAccountMismatch {at: string;detail: 'account_changed' | 'account_unresolved';@@ -77,7 +109,7 @@ export interface ConnectorAccountMismatch {}export const emptyConnectorState = (): ConnectorState => ({ version: 1, account: null, pinned_at: null, continuity_unverified: false,- pending: [], upgrade_recovery: 'none', resumed_from: null, last_run: null, first_attempt_at: null, account_mismatch: null });+ pending: [], upgrade_recovery: 'none', resumed_from: null, last_run: null, first_attempt_at: null, account_mismatch: null, purged_items: [], last_failure: null });export function connectorStateKey(sourceId: string, incarnation: string): string {return digest({ sourceId, incarnation });diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.tsindex 9bcaa23d00..fb9ef7a79f 100644--- a/src/core/persistence/connector-status.ts+++ b/src/core/persistence/connector-status.ts@@ -12,7 +12,9 @@import type { BrainEngine } from '../engine.ts';import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';-import { readManagedConnectorState, type ConnectorRunCounts, type UpgradeRecovery } from './connector-state.ts';+import { CONNECTOR_STOPPED_RUNS, readManagedConnectorState, type ConnectorPurgedItem, type ConnectorRunCounts, type ConnectorRunFailure, type UpgradeRecovery } from './connector-state.ts';+import { classifySyncFault, type SyncFaultVerdict } from './sync-fault-class.ts';+import type { Action } from '../agent-output.ts';import { managedBrain, readAllSourceHolds } from '../connectors/item-holds-store.ts';import type { ItemHoldRecord } from '../connectors/item-holds.ts';import { fenceAutoRepairFor, gitHoldItem, readGitHoldListing, readSyncConversions, readSyncHoldPolicy, type GitHoldItem, type SyncConversion } from './sync-holds.ts';@@ -32,6 +34,37 @@ export interface ConnectorSourceStatus {held: ItemHoldRecord[];/** Set when this source's hold state could not be read: coverage is unknown, not hold-free. */held_error?: string;+ /** #6831: recent items skipped because their content matches a page purge tombstone (newest first). */+ purged_items: ConnectorPurgedItem[];+ /** #6831: the error the source's connector runs keep ending on, or null when the last run finished. */+ last_failure: ConnectorRunFailure | null;+ /** #6831: `last_failure.consecutive` reached CONNECTOR_STOPPED_RUNS: nothing from this source is being imported. */+ stopped: boolean;+}++/** #6831: `sync status`'s view of a connector source's recorded run failure (`connector_last_error`). */+export interface ConnectorLastError extends ConnectorRunFailure, SyncFaultVerdict {+ stopped: boolean;+ fix: Action;+}++/** #6831: the read-only next step for a recorded connector run failure: its receipt when it names one, else the source's status. */+function connectorFailureFix(sourceId: string, failure: ConnectorRunFailure): Action {+ return failure.request_id+ ? { argv: ['gbrain', 'write-request', '--', failure.request_id], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Read-only: the receipt of ${failure.slug ?? 'the item'} the last connector run of ${sourceId} ended on, with its error and fix.` }+ : { argv: ['gbrain', 'sources', 'status', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,+ why: `Read-only: the connector state of ${sourceId}, including the error its last run ended on.` };+}++/** #6831: the connector run failure recorded for a source (null for a non-connector source or a last run that finished). */+export async function readConnectorLastError(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<ConnectorLastError | null> {+ const [source] = await engine.executeRaw<{ incarnation: string }>(+ "SELECT incarnation::text FROM sources WHERE id=$1 AND NOT archived AND config->>'kind' IN ('google','github')", [sourceId]);+ const failure = source ? (await readManagedConnectorState(engine, sourceId, source.incarnation)).last_failure : null;+ if (!failure) return null;+ return { ...failure, stopped: failure.consecutive >= CONNECTOR_STOPPED_RUNS, ...classifySyncFault({ code: failure.code, message: failure.message }),+ fix: connectorFailureFix(sourceId, failure) };}export async function readConnectorSourceStatuses(engine: Pick<BrainEngine, 'executeRaw'>, sourceIds?: string[]): Promise<Map<string, ConnectorSourceStatus>> {@@ -50,7 +83,8 @@ export async function readConnectorSourceStatuses(engine: Pick<BrainEngine, 'exe}statuses.set(source.id, { upgrade_recovery: state.upgrade_recovery, resumed_from: state.resumed_from, account_pinned: state.account !== null,continuity_unverified: state.continuity_unverified, pending: state.pending.length, last_run: state.last_run, held,- ...(heldError ? { held_error: heldError } : {}) });+ ...(heldError ? { held_error: heldError } : {}), purged_items: state.purged_items ?? [], last_failure: state.last_failure ?? null,+ stopped: (state.last_failure?.consecutive ?? 0) >= CONNECTOR_STOPPED_RUNS });}return statuses;}@@ -60,7 +94,21 @@ export function connectorStatusLines(sourceId: string, status: ConnectorSourceStconst run = status.last_run;lines.push(` ${sourceId}: connector ${run ? `last run ${run.finished_at.slice(0, 19).replace('T', ' ')}: ${run.page_admissions} page admission(s), `+ `${run.skipped_unchanged} skipped unchanged, ${run.pending} pending, ${run.checkpoint_admissions} checkpoint admission(s)`- + `${run.stopped_on_wait_budget ? ', stopped on wait budget' : ''}${run.dropped_upstream ? `, ${run.dropped_upstream} dropped (deleted upstream)` : ''}` : 'has not run since the upgrade'}`);+ + `${run.stopped_on_wait_budget ? ', stopped on wait budget' : ''}${run.dropped_upstream ? `, ${run.dropped_upstream} dropped (deleted upstream)` : ''}`+ + `${run.purged_skipped ? `, ${run.purged_skipped} skipped as purged content` : ''}` : 'has not run since the upgrade'}`);+ const failure = status.last_failure;+ if (failure) {+ const where = failure.slug ? ` on ${failure.slug}${failure.request_id ? ` (request ${failure.request_id})` : ''}` : '';+ lines.push(` ${status.stopped ? `STOPPED: the last ${failure.consecutive} connector syncs` : `the last ${failure.consecutive === 1 ? 'connector sync' : `${failure.consecutive} connector syncs`}`} ended on ${failure.code}${where} `+ + `at ${failure.at.slice(0, 19).replace('T', ' ')}: ${failure.message}`);+ lines.push(` nothing after that point of the run was imported; next: ${connectorFailureFix(sourceId, failure).argv!.join(' ')}`);+ }+ if (status.purged_items.length) {+ lines.push(` ${status.purged_items.length} item(s) recently skipped as purged content (the purge tombstone working; they do not stop the sync): `+ + status.purged_items.slice(0, HELD_STATUS_LIMIT).map(item => `${item.slug} (${day(item.at)})`).join(', ')+ + `${status.purged_items.length > HELD_STATUS_LIMIT ? `, +${status.purged_items.length - HELD_STATUS_LIMIT} more` : ''}`);+ lines.push(' to let one back in, the owner clears its tombstone on the brain host: gbrain pages unpurge <slug>');+ }if (status.upgrade_recovery === 'resumed') {lines.push(` resumed from pre-upgrade checkpoint of ${status.resumed_from}; content selection since then is unverified; to re-walk: gbrain sync --source ${sourceId} --reset-checkpoint`);} else if (status.upgrade_recovery === 'rewalking_once') {diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.tsindex 0a901cca62..7459d59b9d 100644--- a/src/core/persistence/connector-sync.ts+++ b/src/core/persistence/connector-sync.ts@@ -33,7 +33,7 @@ import type { PageSnapshot } from '../page-state/types.ts';import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } from '../db-lock.ts';import { ownedGoogleReceipts, prepareGoogleReceiptPatch, type GoogleReceipts } from './connector-google-receipts.ts';import { connectorCheckpointKeys, connectorIdentity, connectorIdentityMatches, type ConnectorIdentity, type ConnectorKind } from './connector-identity.ts';-import { readManagedConnectorState, recordConnectorSyncAttempt, sameConnectorAccount, writeManagedConnectorState, type ConnectorAccount, type ConnectorPendingEntry, type ConnectorRunCounts, type ConnectorState } from './connector-state.ts';+import { CONNECTOR_PURGED_LIMIT, readManagedConnectorState, recordConnectorSyncAttempt, sameConnectorAccount, writeManagedConnectorState, type ConnectorAccount, type ConnectorPendingEntry, type ConnectorPurgedItem, type ConnectorRunCounts, type ConnectorState } from './connector-state.ts';import { connectorConfigDigest } from './connector-account-mismatch.ts';import { connectorAccountChanged, connectorFenceHint, docsAnchor, receiptDeliveredHint, CONNECTOR_INTENT_OUTDATED_OLD_HOST, CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE } from './connector-errors.ts';import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';@@ -45,6 +45,7 @@ import { withCoordinatedWrite } from './context.ts';import { maintenanceAttribution } from './attribution.ts';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 type { GoogleSourceConfig } from '../google/types.ts';@@ -64,6 +65,13 @@ export const connectorWaitBudget = { ms: CONNECTOR_WAIT_BUDGET_MS };const WAIT_RESERVE_MS = 1_000;const COMMIT_GRACE_MS = 1_000;const ITEM_WAIT_MS = 5_000;++/**+ * #6831: the pages guard refused this connector item because its content matches a page purge tombstone. That is the+ * tombstone doing its job (the owner purged this content), so the item is skipped and recorded, never retried, and the+ * rest of the run goes on. Every other failed receipt still fails the run or joins the retry set.+ */+const purgedRefusal = (row: WriteRequest) => row.state === 'failed' && row.error_code === 'purged_content';/*** Accepted-pending writes stop the sweep: the run ends partial with its pending* set recorded. A `write_pending` error, so direct session callers and@@ -305,7 +313,7 @@ export async function withConnectorSync<T>(engine: BrainEngine, sourceId: stringresult = await work(session, options);} catch (error) {if (!(error instanceof ConnectorWaitBudgetStop)) {- if (error instanceof OperationError) await session.finish().catch(() => {});+ if (error instanceof OperationError) await session.finish(error).catch(() => {});throw error;}await session.finish();@@ -352,10 +360,16 @@ export class ManagedConnectorSync {private pendingCheckpoint: ConnectorPendingEntry | null = null;/** Page slugs of held connector items: their terminal, recovery-free failed receipts leave the automatic retry set. */private heldSlugs = new Set<string>();+ /** #6831: items this run skipped because their content matches a page purge tombstone. */+ private purged: ConnectorPurgedItem[] = [];+ /** #6831: whether the source holds any page purge tombstone (read once per run); only then are imports screened against them. */+ private hasPagePurges = false;+ /** #6831: the item whose failed receipt this run last reported, so a run that ends on it can name the item. */+ private lastFailedItem: { slug: string; requestId: string } | null = null;/** True when this run ended with accepted writes pending, so its checkpoint did not advance. */deferred = false;- readonly counts: Omit<ConnectorRunCounts, 'finished_at' | 'pending' | 'stopped_on_wait_budget'> & { created: number; updated: number; deleted: number } = {- page_admissions: 0, skipped_unchanged: 0, checkpoint_admissions: 0, dropped_upstream: 0, created: 0, updated: 0, deleted: 0 };+ readonly counts: Omit<ConnectorRunCounts, 'finished_at' | 'pending' | 'stopped_on_wait_budget'> & { created: number; updated: number; deleted: number; purged_skipped: number } = {+ page_admissions: 0, skipped_unchanged: 0, checkpoint_admissions: 0, dropped_upstream: 0, created: 0, updated: 0, deleted: 0, purged_skipped: 0 };readonly checkpointKey: string;/** The stable key plus its #6561 alias keys: retry approvals recorded under an alias still apply. */private readonly checkpointKeys: string[];@@ -395,6 +409,7 @@ export class ManagedConnectorSync {this.outstandingCap = Math.max(1, Math.min(90, limits.principalOutstanding - 10));this.intentByteCap = Math.max(1024 ** 2, Math.floor(Math.min(limits.principalIntentBytes, PERSISTENCE_IPC_MAX_BYTES) / 2));this.connectorState = await readManagedConnectorState(this.engine, this.sourceId, this.source.incarnation);+ this.hasPagePurges = (await this.engine.executeRaw('SELECT 1 FROM page_purges WHERE source_id=$1 LIMIT 1', [this.sourceId])).length > 0;await this.resolvePendingSet();const rows = await this.engine.executeRaw<StoredCheckpoint>(`SELECT fingerprint,completed_keys,extract(epoch from updated_at)::float8 AS atFROM op_checkpoints WHERE op='managed-connector' AND fingerprint=ANY($1::text[])`, [this.checkpointKeys]);@@ -424,6 +439,7 @@ export class ManagedConnectorSync {if (row.state === 'committed') continue;if (entry.itemRef === CHECKPOINT_SLUG && !isTerminal(row)) { this.pendingCheckpoint = entry; this.blockedByCheckpoint = true; continue; }if (!isTerminal(row)) { this.pendingRows.set(row.id, { entry, row, bytes: 0 }); continue; }+ if (purgedRefusal(row)) { this.skipPurged(entry.itemRef, row); continue; }this.autoRetry.add(entry.baseRequestId);this.carried.push(entry);}@@ -669,7 +685,11 @@ export class ManagedConnectorSync {for (const [id, pending] of this.pendingRows) {const row = found.get(id);if (!row || row.state === 'committed') { this.pendingRows.delete(id); continue; }- if (isTerminal(row)) { this.pendingRows.delete(id); this.failedPending.push(pending.entry); continue; }+ if (isTerminal(row)) {+ this.pendingRows.delete(id);+ if (purgedRefusal(row)) this.skipPurged(pending.entry.itemRef, row); else this.failedPending.push(pending.entry);+ continue;+ }pending.row = row;}}@@ -723,8 +743,12 @@ export class ManagedConnectorSync {await this.refreshPending();}}- /** Records the run's pending set, counts and upgrade state; written only while the lease is held. */- async finish(): Promise<void> {+ /**+ * Records the run's pending set, counts and upgrade state; written only while the lease is held. `failure` is the+ * 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> {await this.refreshPending().catch(() => {});const now = new Date().toISOString();const outstanding = [...this.pendingRows.values()].map(pending => pending.entry);@@ -741,11 +765,39 @@ export class ManagedConnectorSync {.map(entry => [entry.requestId, entry])).values()];if (outstanding.length || this.failedPending.length || this.pendingCheckpoint || this.stopped) this.deferred = true;const recovery = this.connectorState.upgrade_recovery === 'rewalking_once' && complete ? 'none' : this.connectorState.upgrade_recovery;- this.connectorState = { ...this.connectorState, pending, upgrade_recovery: recovery, last_run: {+ 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,+ 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,- checkpoint_admissions: this.counts.checkpoint_admissions, stopped_on_wait_budget: this.stopped, dropped_upstream: this.counts.dropped_upstream, finished_at: now } };+ checkpoint_admissions: this.counts.checkpoint_admissions, stopped_on_wait_budget: this.stopped, dropped_upstream: this.counts.dropped_upstream,+ ...(this.counts.purged_skipped ? { purged_skipped: this.counts.purged_skipped } : {}), finished_at: now } };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>`).+ */+ private skipPurged(slug: string, row: WriteRequest | null): void {+ if (row) this.receipts = this.receipts.filter(id => id !== row.id);+ this.counts.purged_skipped++;+ this.purged.push({ slug, request_id: row?.request_id ?? null, at: new Date().toISOString() });+ process.stderr.write(`[connector] ${this.sourceId}: skipped ${slug}: its content matches a page purge tombstone${row ? ` (request ${row.request_id})` : ''}; `+ + `the rest of the sync continues. To let it back in: gbrain pages unpurge ${slug}\n`);+ }+ /**+ * #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.+ */+ private async carriesPurgedPage(slug: string, content: string | undefined): Promise<boolean> {+ if (!this.hasPagePurges || !content) return false;+ return intentCarriesPurgedContent(this.engine, { source_id: this.sourceId, slug, intent: { content } }, { facts: false, pages: true });+ }/*** Fix wave 4: marks connector items held by this run. Only their terminal,* recovery-free failed receipts leave the automatic retry set; a queued,@@ -935,6 +987,10 @@ export class ManagedConnectorSync {this.counts.skipped_unchanged++;return { row: null, pending: false, created: false };}+ if (kind === 'connector_v2_import' && await this.carriesPurgedPage(slug, extra.content)) {+ this.skipPurged(slug, null);+ return { row: null, pending: false, created: false };+ }row = await this.engine.transaction(async tx => {await this.assertLease(tx);const accepted = await admitWriteInTransaction(tx, prior.input);@@ -966,6 +1022,8 @@ export class ManagedConnectorSync {return { row, pending: false, created: false };}if (isTerminal(row)) {+ if (page && purgedRefusal(row)) { this.skipPurged(slug, row); return { row: null, pending: false, created: false }; }+ if (row.state !== 'committed') this.lastFailedItem = { slug, requestId: row.request_id };writeResponse(row);this.receipts.push(row.id);if (row.outcome?.noop !== true) {diff --git a/src/core/persistence/sync-status.ts b/src/core/persistence/sync-status.tsindex d7942a6c28..0483f2676a 100644--- a/src/core/persistence/sync-status.ts+++ b/src/core/persistence/sync-status.ts@@ -95,6 +95,11 @@ export interface SyncStatus {cursors: SyncStatusCursor[];/** #6650: the source's terminal write receipts that did not commit, summarized (`terminal-failures.ts`); `unknown` when the bounded read timed out. */terminal_failures: SyncTerminalSummary;+ /**+ * #6831: for a Google or GitHub connector source, the error its connector runs keep ending on (null once a run+ * finishes). Connector runs keep no managed-sync cursor, so this never sets `last_error`, the cursor's `next` or `needs_human`.+ */+ connector_last_error: import('./connector-status.ts').ConnectorLastError | null;next: Action | null;}@@ -235,11 +240,12 @@ export async function readSyncStatus(engine: BrainEngine, sourceId: string): Proconst blockers = await checkpointBlockers(engine, header);// #6650: a receipt still holding a recovery record holds its root, so a source with nothing else to do names it as `next`.const { recovery_next, ...terminal } = await terminalSummary(engine, sourceId, blockers.checkpoint_blockers);+ const connectorLastError = await (await import('./connector-status.ts')).readConnectorLastError(engine, sourceId);return { source_id: sourceId, run_id: header?.runId ?? null,cursor: header ? { index: Number(header.index), total: Number(header.total), pinned_target: header.target ?? null, last_advance_at: p ? new Date(p.lastAt).toISOString() : null, done: !!header.done } : null,committed_last_10m: Number(committed?.n ?? 0), ...estimate, live_job_id: liveJob, holds, last_error: lastError, needs_human: !!human, ...(human ? { human_reason: human.human_reason } : {}),resume_argv: resume, ...blockers, cursors: await liveCursors(engine, sourceId, source.incarnation, selected?.key ?? null, failures),- terminal_failures: terminal, next: next ?? recovery_next ?? null };+ terminal_failures: terminal, connector_last_error: connectorLastError, next: next ?? recovery_next ?? connectorLastError?.fix ?? null };}/**diff --git a/test/claude-cli-refusal-6816.test.ts b/test/claude-cli-refusal-6816.test.tsnew file mode 100644index 0000000000..41078d6937--- /dev/null+++ b/test/claude-cli-refusal-6816.test.ts@@ -0,0 +1,121 @@+/**+ * #6816: Claude Code reports a usage-policy refusal as an error envelope with no API status+ * ("API Error: <model> can't help with this. Start a new session to continue. ... https://www.anthropic.com/legal/aup").+ * `providerContentBlockReason` knew only the OpenAI, Azure, DeepSeek and Gemini shapes, so extract_atoms treated the+ * refusal as a generic error: it counted the item but never took the bounded content-block tombstone, and the same item+ * went back to the model on every run.+ *+ * A POSIX shell stub at GBRAIN_CLAUDE_CLI_BIN plays the CLI; the extract_atoms case runs the real gateway `chat()` with+ * the claude-cli recipe, so the error is built by the real adapter and normalized by the real gateway.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { LanguageModelV2CallOptions } from '@ai-sdk/provider';+import { ClaudeCliLanguageModel, ClaudeCliProcessError } from '../src/core/ai/providers/claude-cli-language-model.ts';+import { chat, configureGateway, resetGateway, type ChatOpts } from '../src/core/ai/gateway.ts';+import { normalizeAIError, providerContentBlockReason } from '../src/core/ai/errors.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { discoverExtractablePages, EXTRACT_ATOMS_MODEL_KEY, MAX_DETERMINISTIC_FAILURES } from '../src/core/cycle/extract-atoms.ts';+import { runPhaseWithStoredPageFixtures as runPhaseExtractAtoms } from './helpers/extract-atoms-page-fixtures.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';++const AUP = 'https://www.anthropic.com/legal/aup';+const refusals: Array<[string, string]> = [+ ['current wording (-p)', `API Error: Claude can't help with this. Start a new session to continue.\n\nLearn more: ${AUP}`],+ ['model name, feedback line, details and request id', `API Error: Sonnet 5 can't help with this. Start a new session to continue. Send feedback with /feedback or learn more: ${AUP} Details: \`[bio]\` Request ID: req_000000000000000000000000`],+ ['curly apostrophe', `API Error: Claude can\u2019t help with this. Start a new session to continue.\n\nLearn more: ${AUP}`],+ ['safeguards flagged (a fallback model exists)', `API Error: Sonnet 5's safeguards flagged this message (${AUP}). This sometimes happens with safe, normal conversations. Claude Code can't respond to this message with Sonnet 5.`],+ ['pre-2.1.219 wording', `API Error: Claude Code is unable to respond to this request, which appears to violate our Usage Policy (${AUP}). Please double press esc to edit your last message or start a new session for Claude Code to assist with a different task.`],+];+const ordinary: Array<[string, Record<string, unknown>]> = [+ ['an API status on the refusal text', { result: refusals[0]![1], api_error_status: 400 }],+ ['insufficient credits', { result: 'API Error: insufficient credits', api_error_status: 402 }],+ ['a connection error', { result: 'API Error: Connection error.' }],+ ['the policy link without a refusal phrase', { result: `API Error: request rejected; see ${AUP}` }],+ ['a refusal phrase without the policy link', { result: "API Error: Claude can't help with this. Start a new session to continue." }],+ ['refusal text quoted after another message', { result: `Tool output: ${refusals[0]![1]}` }],+ ['an execution error with no result', { result: '', subtype: 'error_during_execution' }],+];+const envelope = (extra: Record<string, unknown>) => ({ type: 'result', subtype: 'success', is_error: true, stop_reason: null,+ session_id: 'synthetic-session', num_turns: 1, usage: { input_tokens: 10, output_tokens: 0 }, ...extra });++async function withCli<T>(body: unknown, run: () => Promise<T>): Promise<T> {+ const dir = mkdtempSync(join(tmpdir(), 'claude-refusal-'));+ const response = join(dir, 'response.json');+ writeFileSync(response, JSON.stringify(body));+ const bin = join(dir, 'claude');+ writeFileSync(bin, `#!/bin/sh\ncat > /dev/null\ncat "${response}"\nexit 1\n`);+ chmodSync(bin, 0o755);+ try { return await withEnv({ GBRAIN_CLAUDE_CLI_BIN: bin, CLAUDE_CODE_MAX_OUTPUT_TOKENS: undefined }, run); }+ finally { rmSync(dir, { recursive: true, force: true }); }+}++async function cliError(body: unknown): Promise<unknown> {+ return withCli(body, async () => {+ try {+ await new ClaudeCliLanguageModel('claude-sonnet-4-6').doGenerate({ prompt: [{ role: 'user', content: [{ type: 'text', text: 'Synthetic page' }] }] } as LanguageModelV2CallOptions);+ } catch (error) { return error; }+ throw new Error('expected the CLI call to reject');+ });+}++describe('providerContentBlockReason: claude-cli usage-policy refusals (#6816)', () => {+ for (const [label, result] of refusals) {+ test(`${label} is a content block, raw and normalized`, async () => {+ const error = await cliError(envelope({ result }));+ expect(error).toBeInstanceOf(ClaudeCliProcessError);+ expect(providerContentBlockReason(error)).toBe('claude_cli_usage_policy');+ expect(providerContentBlockReason(normalizeAIError(error, 'chat(claude-cli:claude-sonnet-4-6)'))).toBe('claude_cli_usage_policy');+ });+ }+ for (const [label, extra] of ordinary) {+ test(`${label} stays an ordinary claude-cli error`, async () => {+ const error = await cliError(envelope(extra));+ expect(error).toBeInstanceOf(ClaudeCliProcessError);+ expect(providerContentBlockReason(error)).toBeUndefined();+ expect(providerContentBlockReason(normalizeAIError(error, 'chat(claude-cli:claude-sonnet-4-6)'))).toBeUndefined();+ });+ }+ test('the same text from anything but the claude-cli adapter is not a claude-cli refusal', () => {+ expect(providerContentBlockReason(new Error(`claude-cli reported error: ${refusals[0]![1]}`))).toBeUndefined();+ });+});++describe('extract_atoms on claude-cli (#6816)', () => {+ let engine: PGLiteEngine;+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);+ afterAll(async () => { await engine.disconnect(); });+ beforeEach(async () => { await resetPgliteState(engine); await engine.setConfig(EXTRACT_ATOMS_MODEL_KEY, 'claude-cli:claude-sonnet-4-6'); resetGateway(); configureGateway({ chat_model: 'claude-cli:claude-sonnet-4-6', env: {} }); });+ afterEach(resetGateway);++ const seed = async (slug: string) => engine.putPage(slug, { title: slug, type: 'note', compiled_truth: 'refused prose '.repeat(40) } as never, { sourceId: 'default' });+ const run = (slug: string) => runPhaseExtractAtoms(engine, { sourceId: 'default', _transcripts: [],+ _pages: [{ slug, content: 'refused prose '.repeat(40), contentHash: 'c'.repeat(16) }], _chat: (opts: ChatOpts) => chat(opts) });+ const state = async (slug: string) => (await engine.executeRaw<{ fail_count: number; tombstoned: boolean }>(+ 'SELECT scan.fail_count, scan.tombstoned FROM extract_atoms_page_state scan JOIN pages p ON p.id=scan.page_id WHERE p.slug=$1', [slug]))[0];++ test('a usage-policy refusal takes the bounded content-block tombstone instead of being retried on every run', async () => {+ await seed('note/refused');+ await withCli(envelope({ result: refusals[0]![1] }), async () => {+ for (let n = 1; n <= MAX_DETERMINISTIC_FAILURES; n++) {+ const result = await run('note/refused');+ expect(result.details.aborted_global_error).toBeUndefined();+ expect((result.details.failures as Array<{ error: string }>)[0]!.error).toContain(`provider blocked content: claude_cli_usage_policy (consecutive failure ${n}`);+ expect((await state('note/refused'))).toMatchObject({ fail_count: n, tombstoned: n === MAX_DETERMINISTIC_FAILURES });+ }+ });+ expect((await discoverExtractablePages(engine, 'default')).map(p => p.slug)).not.toContain('note/refused');+ });++ test('an ordinary claude-cli error is not treated as a content block', async () => {+ await seed('note/ordinary');+ await withCli(envelope({ result: 'API Error: request rejected for an unexpected reason' }), async () => {+ const result = await run('note/ordinary');+ expect(JSON.stringify(result.details.failures)).not.toContain('provider blocked content');+ });+ expect((await state('note/ordinary'))?.tombstoned ?? false).toBe(false);+ });+});diff --git a/test/connector-purged-item-6831.test.ts b/test/connector-purged-item-6831.test.tsnew file mode 100644index 0000000000..17b5c5fb16--- /dev/null+++ b/test/connector-purged-item-6831.test.ts@@ -0,0 +1,192 @@+/**+ * #6831: a purged connector item is skipped per item, and a source whose runs keep dying says so.+ *+ * A weekly calendar series keeps listing an occurrence the owner purged (the series is still on the+ * calendar). Before the fix the pages guard's `purged_content` refusal of that one occurrence ended+ * the whole managed sync, every later sync died the same way, and nothing else from the account+ * (contacts, the series' other occurrences, Gmail) was imported. `sync status`, `sources status` and+ * doctor all read the source as healthy.+ *+ * PGLite here; PostgreSQL through test/e2e/connector-purged-item-6831.test.ts.+ */+import { afterAll, beforeAll, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { parseGoogleSourceConfig, runGoogleSync } from '../src/core/google/google-source.ts';+import { calendarRelPath } from '../src/core/google/google-render.ts';+import { slugifyPath } from '../src/core/sync.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { withConnectorSync } from '../src/core/persistence/connector-sync.ts';+import { CONNECTOR_STOPPED_RUNS, readManagedConnectorState } from '../src/core/persistence/connector-state.ts';+import { connectorStatusLines, readConnectorSourceStatuses } from '../src/core/persistence/connector-status.ts';+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 { contact, createConnectorFixture, json, options, settleConnectorWrites, withGoogleAccount } from './helpers/connector-fixture.ts';+import { withEnv } from './helpers/with-env.ts';++const { engines, env, source, setup, teardown } = createConnectorFixture();+beforeAll(setup, 120_000);+afterAll(teardown);++const account = '[email protected]';+const config = { kind: 'google', g_account: account, g_services: 'calendar,contacts', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };+const ctx = (engine: BrainEngine, sourceId: string) => ({ engine, sourceId, config: { engine: engine.kind }, remote: false, dryRun: false,+ logger: { info() {}, warn() {}, error() {} } });+const DAY = 86_400_000;+/** Occurrence `n` of a synthetic weekly series, `n` weeks from a fixed start inside the 60-day horizon. */+const base = Math.floor(Date.now() / DAY) * DAY + 2 * DAY + 17 * 3_600_000;+const occurrence = (n: number) => {+ const start = new Date(base + 7 * n * DAY).toISOString();+ return { id: `weeklyseries0001_${start.slice(0, 10).replace(/-/g, '')}`, recurringEventId: 'weeklyseries0001', status: 'confirmed',+ summary: 'Synthetic weekly review', start: { dateTime: start }, end: { dateTime: new Date(base + 7 * n * DAY + 3_600_000).toISOString() },+ organizer: { email: account }, attendees: [{ email: account, self: true, responseStatus: 'accepted' }] };+};+const occurrenceSlug = (n: number) => {+ const ev = occurrence(n);+ return slugifyPath(calendarRelPath({ id: ev.id, startIso: ev.start.dateTime, summary: ev.summary } as never));+};++async function liveSlugs(engine: BrainEngine, sourceId: string): Promise<string[]> {+ return (await engine.executeRaw<{ slug: string }>('SELECT slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL ORDER BY slug', [sourceId])).map(r => r.slug);+}+async function connectorState(engine: BrainEngine, sourceId: string) {+ const [row] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text FROM sources WHERE id=$1', [sourceId]);+ return readManagedConnectorState(engine, sourceId, row.incarnation);+}++test('#6831: a purged recurring occurrence is skipped per item; the rest of the run imports, later runs keep going, and it stays purged', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, config);+ const cfg = parseGoogleSourceConfig(config, f.dir);+ const fx = { events: [occurrence(0), occurrence(1)], contacts: [contact('first', 'First Example')] };+ const fetcher = async (url: string) => {+ if (url.includes('/calendars/')) return json({ items: fx.events, nextSyncToken: `calendar-${fx.events.length}` });+ if (url.includes('/people/me/connections')) return json({ connections: fx.contacts, nextSyncToken: `contacts-${fx.contacts.length}` });+ throw new Error(`Unexpected fixture route ${url}`);+ };+ const run = () => runGoogleSync(engine, f.id, cfg, options, withGoogleAccount(fetcher, account));+ expect((await run()).added).toBe(3);+ await settleConnectorWrites(engine, f.id);+ await disposePersistenceConsumer(engine);++ // The owner purges occurrence 1; the series stays on the calendar, so the next listing names it again.+ const purged = (await engine.readPageSnapshot(occurrenceSlug(1), { sourceId: f.id }))!;+ await submitPageMutation(ctx(engine, f.id), { operation: 'delete_page', params: { slug: occurrenceSlug(1), purge: true, expected_revision: purged.revision } });+ await settleConnectorWrites(engine, f.id);+ expect(await liveSlugs(engine, f.id)).not.toContain(occurrenceSlug(1));++ fx.events = [occurrence(0), occurrence(1), occurrence(2)];+ fx.contacts = [contact('first', 'First Example'), contact('second', 'Second Example')];+ const stderr = spyOn(process.stderr, 'write').mockImplementation(() => true);+ let second;+ try { second = await run(); } finally { stderr.mockRestore(); }+ expect(second.status).not.toBe('partial');+ await settleConnectorWrites(engine, f.id).catch(() => {});+ const slugs = await liveSlugs(engine, f.id);+ expect(slugs).toContain(occurrenceSlug(2));+ expect(slugs).toContain('people/second-example');+ expect(slugs).not.toContain(occurrenceSlug(1));+ const state = await connectorState(engine, f.id);+ expect(state.last_failure).toBeNull();+ expect(state.last_run).toMatchObject({ purged_skipped: 1 });+ expect(state.purged_items?.map(item => item.slug)).toEqual([occurrenceSlug(1)]);+ expect(state.pending).toEqual([]);+ // The cursor advanced past the skipped item: the run saved its new calendar and contacts tokens.+ const [checkpoint] = await engine.executeRaw<{ state: { calendar_sync_token?: string; contacts_sync_token?: string } }>(+ "SELECT completed_keys->0->'state' AS state FROM op_checkpoints WHERE op='managed-connector' AND fingerprint IN (SELECT intent->>'checkpointKey' FROM persistence_requests WHERE source_id=$1)", [f.id]);+ expect(checkpoint.state.calendar_sync_token).toBe('calendar-3');+ const status = (await readConnectorSourceStatuses(engine, [f.id])).get(f.id)!;+ expect(status.stopped).toBe(false);+ const lines = connectorStatusLines(f.id, status).join('\n');+ expect(lines).toContain('1 skipped as purged content');+ expect(lines).toContain(`1 item(s) recently skipped as purged content`);+ expect(lines).toContain(occurrenceSlug(1));+ await disposePersistenceConsumer(engine);++ // Every later run keeps going and keeps the purge: the refused receipt is replayed, never re-admitted.+ fx.events = [occurrence(0), occurrence(1), occurrence(2), occurrence(3)];+ const admissions = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE source_id=$1 AND slug=$2", [f.id, occurrenceSlug(1)]))[0].n;+ const before = await admissions();+ const stderr2 = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try { expect((await run()).status).not.toBe('partial'); } finally { stderr2.mockRestore(); }+ await settleConnectorWrites(engine, f.id).catch(() => {});+ expect(await admissions()).toBe(before);+ expect(await liveSlugs(engine, f.id)).toContain(occurrenceSlug(3));+ expect(await liveSlugs(engine, f.id)).not.toContain(occurrenceSlug(1));+ expect((await connectorState(engine, f.id)).last_failure).toBeNull();+ await disposePersistenceConsumer(engine);+ }+}), 240_000);++test('#6831: a purge that lands after the run started is refused by the pages guard at publication, and that refusal is skipped per item too', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, config);+ const cfg = parseGoogleSourceConfig(config, f.dir);+ const page = (n: number) => `---\ntype: note\ntitle: Synthetic connector item ${n}\n---\n# Synthetic connector item ${n}\n\nBody ${n}.\n`;+ // The first run also saves a cursor, so the second run's import of the same bytes is a new request, not a replay.+ await withConnectorSync(engine, f.id, 'google', cfg, options, async managed => { await managed!.importMarkdown('notes/item-1.md', page(1)); await managed!.saveState({ first: true }); });+ await settleConnectorWrites(engine, f.id);+ await disposePersistenceConsumer(engine);+ const stderr = spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ const results = await withConnectorSync(engine, f.id, 'google', cfg, options, async managed => {+ // The session read "no tombstones" at load, so only the guard can refuse item 1 now.+ const before = (await engine.readPageSnapshot('notes/item-1', { sourceId: f.id }))!;+ await submitPageMutation(ctx(engine, f.id), { operation: 'delete_page', params: { slug: 'notes/item-1', purge: true, expected_revision: before.revision } });+ await settleConnectorWrites(engine, f.id);+ return [await managed!.importMarkdown('notes/item-1.md', page(1)), await managed!.importMarkdown('notes/item-2.md', page(2))];+ });+ expect(results.map(r => r.status)).toEqual(['skipped', 'imported']);+ } finally { stderr.mockRestore(); }+ await settleConnectorWrites(engine, f.id).catch(() => {});+ expect(await liveSlugs(engine, f.id)).toEqual(['notes/item-2']);+ const state = await connectorState(engine, f.id);+ expect(state.last_failure).toBeNull();+ expect(state.last_run).toMatchObject({ purged_skipped: 1 });+ expect(state.purged_items).toEqual([expect.objectContaining({ slug: 'notes/item-1', request_id: expect.any(String) })]);+ const [refused] = await engine.executeRaw<{ state: string; error_code: string }>('SELECT state,error_code FROM persistence_requests WHERE request_id=$1::uuid', [state.purged_items?.[0]?.request_id]);+ expect(refused).toEqual({ state: 'failed', error_code: 'purged_content' });+ expect(state.pending).toEqual([]);+ await disposePersistenceConsumer(engine);+ }+}), 120_000);++test('#6831: a connector source whose runs keep ending on an error reads as stopped in sources status, sync status and doctor; a clean run clears it', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const f = await source(engine, config);+ const cfg = parseGoogleSourceConfig(config, f.dir);+ const failing = () => withConnectorSync(engine, f.id, 'google', cfg, options, async () => {+ throw opError('invalid_fence', 'synthetic refusal of one connector item', 'Read the receipt.');+ });+ for (let n = 1; n <= CONNECTOR_STOPPED_RUNS; n++) {+ await expect(failing()).rejects.toMatchObject({ code: 'invalid_fence' });+ const status = (await readConnectorSourceStatuses(engine, [f.id])).get(f.id)!;+ expect(status.last_failure).toMatchObject({ code: 'invalid_fence', consecutive: n, message: 'synthetic refusal of one connector item' });+ expect(status.stopped).toBe(n >= CONNECTOR_STOPPED_RUNS);+ }+ const lines = connectorStatusLines(f.id, (await readConnectorSourceStatuses(engine, [f.id])).get(f.id)!).join('\n');+ expect(lines).toContain(`STOPPED: the last ${CONNECTOR_STOPPED_RUNS} connector syncs ended on invalid_fence`);+ const sync = await readSyncStatus(engine, f.id);+ expect(sync.connector_last_error).toMatchObject({ code: 'invalid_fence', consecutive: CONNECTOR_STOPPED_RUNS, stopped: true });+ expect(sync.last_error).toBeNull();+ expect(sync.next?.argv).toEqual(['gbrain', 'sources', 'status', f.id, '--json']);+ // A recent last_sync_at no longer hides the stop.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1', [f.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const doctor = await checkSyncFreshness(engine);+ 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 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();+ expect((await readSyncStatus(engine, f.id)).connector_last_error).toBeNull();+ expect((await checkSyncFreshness(engine)).message).not.toContain(`Source '${f.id}' is STOPPED`);+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw('UPDATE sources SET archived=true WHERE id=$1', [f.id]);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ }+}), 120_000);diff --git a/test/e2e/connector-purged-item-6831.test.ts b/test/e2e/connector-purged-item-6831.test.tsnew file mode 100644index 0000000000..5b983a29a6--- /dev/null+++ b/test/e2e/connector-purged-item-6831.test.ts@@ -0,0 +1,4 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++// #6831: the PostgreSQL arm of the per-item purged skip and the stopped-source status suite.+await registerPostgresTests(() => import('../connector-purged-item-6831.test.ts'));