Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(connectors): a 403 is terminal, ChatGPT refresh goes through the shared client, auto_sync holds for queued jobs and --all, and every run is bounded (#7515)
garrytan65dc7116ac16
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.mdindex cb748ca53a..1cdd9f3cfc 100644--- a/docs/architecture/key-files/core-services-1.md+++ b/docs/architecture/key-files/core-services-1.md@@ -46,4 +46,4 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/chunkers/symbol-resolver.ts` — resolves and stamps each bounded chunk batch in one transaction. It takes ordered source/page guards before edge reads, revalidates current chunk/page/slug identity under those guards, and commits edge metadata with its backfill watermark. Concurrent projection replacement cannot certify new edges using an old resolver read; rollback leaves both metadata and watermark unchanged. Pinned by `test/symbol-resolver-projection-race.test.ts` with PGLite serialization and a real PostgreSQL lock-wait receipt. A `calls` edge the extractor flagged `memberCall` (an untyped receiver, `obj.m()` emitted as bare `m`; persisted as `edge_metadata.member_call`) is never resolved within the file, since a member call cannot invoke a same-file top-level function (gbrain-evals N13-8, `test/code-intel/n13-edge-resolution.test.ts`); existing code pages pick this up when they re-import (`gbrain reindex-code`).- `src/core/code-intel/recursive-walk.ts` (`code_blast` / `code_flow`) + the `chunkId` arm of `getCallersOf` / `getCalleesOf` in `src/core/engine-sql/code-edges.ts` (#5439 item 3, wave 15 P7.8) — the BFS keys its frontier and visited set by source-scoped chunk identity where the hop that reached a node was resolved (a `code_edges_chunk` row's `to_chunk_id`, or `readEdgeResolution(edge_metadata).kind === 'resolved'`), and by qualified name only for unresolved edges; the start is always a name. The next hop from a chunk node reads edges by that chunk (`opts.chunkId`: callees = both tables' `from_chunk_id`; callers = `code_edges_chunk.to_chunk_id` plus `code_edges_symbol` rows whose `edge_metadata.resolved_chunk_id` matches), under the same source filter and current-projection read policy, so two files whose top-level `helper` share the qualified name no longer fan into each other's callers or callees two hops out. `WalkNode.chunk_id` is directional: the caller's chunk on a callers hop, the resolved callee's chunk on a callees hop, absent for an unresolved callee (it used to be the edge's `from_chunk_id` on every hop). SQL lives once in the code-edges domain (SQL-text golden `sql-text/code-edges.json` `chunkId` variants). Pinned on both backends by `test/code-intel/recursive-walk-resolved-ids-5439.test.ts` (`test/e2e/code-intel-walk-resolved-ids-postgres.test.ts`).-- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; `synced` entries older than the next list window are pruned, `failed` entries never are: #6387) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `failed-ledger.ts` (#6387): the `failed` ledger entry (`attempts`, `updatedAt`, `lastAttemptAt`, `nextRetryAt`, Claude `orgId`) kept until the conversation imports, and the pure `planConnectorFetch` — listed work plus due retained failures retried by id (`RETRY_BUDGET` 10 per run, oldest-due first, slots reserved under `--limit`, quarantine backoff from `item-holds.ts` `HOLD_BACKOFF_MS`/`HOLD_DAILY_MS`); on a `routesByOrg` provider an entry without `orgId` is `held` for `--full`. A sync with any entry left reports `partial` + `unresolved`; aborts and auth stops are never strikes; a complete `--full` listing drops entries it no longer contains (`gone`); `connectors status --json` lists `unresolved` and the doctor check warns "archive incomplete" (ask-first `--full` fix for held entries). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state; `portOverride: 0` plus `onListen` binds an OS-assigned port for tests while the authorize and token URLs keep `redirectPort`) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir; `connectors sync` usage errors, a missing `--source` value or a missing/unknown provider, are `invalid_params` exit 2 with the envelope under `--json` and a `fix` whose `<SOURCE_ID>`/`<PROVIDER>` input it names, and `connectors sync --help` prints the usage; `test/connectors-sync-cli.test.ts`), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle, #6387 retained retries and the `--full` upgrade-state recovery, #6388 long-message tails) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.+- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, `redirect: 'manual'` with any 3xx a terminal `auth_required`, browser UA, refresh-once-on-401 that is handed the client itself and never runs on a 403 (terminal, #7515), Retry-After backoff, a per-run ceiling `MAX_CONNECTOR_REQUESTS_PER_RUN` (10,000, lowered by `maxRequests`) and a `deadlineAt` checked before each request and retry wait (`ConnectorRunLimitError`), and `probeFailure`, the one error-to-`ProbeResult` table; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, list pages truncated to the requested size (a truncated page that also ignores offset is drift), Claude's `CLAUDE_MAX_ORGS` (10; more makes the listing incomplete) and `CLAUDE_MAX_REQUESTS_PER_ORG` (5,000) caps, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session` through the shared client and throws its terminal errors; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; `synced` entries older than the next list window are pruned, `failed` entries never are: #6387) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `failed-ledger.ts` (#6387): the `failed` ledger entry (`attempts`, `updatedAt`, `lastAttemptAt`, `nextRetryAt`, Claude `orgId`) kept until the conversation imports, and the pure `planConnectorFetch` — listed work plus due retained failures retried by id (`RETRY_BUDGET` 10 per run, oldest-due first, slots reserved under `--limit`, quarantine backoff from `item-holds.ts` `HOLD_BACKOFF_MS`/`HOLD_DAILY_MS`); on a `routesByOrg` provider an entry without `orgId` is `held` for `--full`. A sync with any entry left reports `partial` + `unresolved`; aborts and auth stops are never strikes; a complete `--full` listing drops entries it no longer contains (`gone`); `connectors status --json` lists `unresolved` and the doctor check warns "archive incomplete" (ask-first `--full` fix for held entries). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state; `portOverride: 0` plus `onListen` binds an OS-assigned port for tests while the authorize and token URLs keep `redirectPort`) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir; `connectors sync` usage errors, a missing `--source` value or a missing/unknown provider, are `invalid_params` exit 2 with the envelope under `--json` and a `fix` whose `<SOURCE_ID>`/`<PROVIDER>` input it names, and `connectors sync --help` prints the usage; `test/connectors-sync-cli.test.ts`), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock; rechecks `auto_sync` and returns `skipped` unless the job is `explicit`, #7515), `connectors sync --all` (only `auto_sync` providers; `--max-requests`/`--deadline` bound the invocation), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle, #6387 retained retries and the `--full` upgrade-state recovery, #6388 long-message tails) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.diff --git a/docs/guides/chat-connectors.md b/docs/guides/chat-connectors.mdindex 980f356971..23d7cf7316 100644--- a/docs/guides/chat-connectors.md+++ b/docs/guides/chat-connectors.md@@ -203,6 +203,13 @@ off until you enable it.Tune the floor with `gbrain config set connectors.sync_floor_min <minutes>`(default 1440).+`connectors.<p>.auto_sync` is the owner's switch for every unattended run:+`connectors sync --all` syncs only providers whose `auto_sync` is on (it names+each one it skips on stderr), and a queued `connector-sync` job rechecks it when+it starts and returns `skipped` (`reason: auto_sync_off`) if it was turned off+while the job waited. Only an explicit `gbrain connectors sync <provider>`+(inline or `--background`) syncs a provider with `auto_sync` off.+On PGLite (the default engine, no worker daemon) sync runs inline; on Postgres,`--background` submits a `connector-sync` minion job (single-flight per provider).@@ -236,6 +243,31 @@ Env override for a credential (incident escape hatch):data the provider's official export contains. Keep the cadence polite (dailydefault) so automated polling doesn't risk your account.+## Request bounds++Every run has a hard ceiling, whatever the flags say:++| Bound | Value | When reached |+|---|---|---|+| Requests per run (every request: probe, list pages, conversations, token refreshes, retries) | 10,000 (`MAX_CONNECTOR_REQUESTS_PER_RUN`, about 2 hours at the 700 ms spacing) | `partial`, `stopReason: max_requests` |+| Requests per Claude organization per run | 5,000 (`CLAUDE_MAX_REQUESTS_PER_ORG`) | `partial`, `stopReason: max_requests` |+| Claude organizations listed per run | 10 (`CLAUDE_MAX_ORGS`) | the first 10 are synced; the listing counts as incomplete, so the run is `partial` and the watermark holds |+| List pages per pass (per organization for Claude) | 500 | the listing counts as incomplete (`partial`) |+| Items taken from one list page | the page size asked for (ChatGPT 28, Claude 100) | the rest of an over-long page is fetched on the next page; a page that also ignores `offset` is drift (`partial`), never a silently shortened list |++Lower the bound for one invocation with `--max-requests N` (1 to 10,000) or+`--deadline <duration>` (`90s`, `30m`, `2h`; with `--all` it covers every+provider together). Both are checked before each request and before each retry+wait, so a run never starts a request after its deadline. ChatGPT's token refresh+goes through the same client: it is paced and counted like any other request.++A run that stops at a bound keeps what it imported, leaves the watermark where it+was and records no failure against the conversations it did not reach. Continue+with `gbrain connectors sync <provider>` without `--full`: conversations already+imported are skipped, so each run gets further. (`--full` fetches every listed+conversation again, so a history larger than the ceiling never completes in one+`--full` run.)+## Feasibility caveat (Cloudflare)`chatgpt.com` / `claude.ai` sit behind bot-management that fingerprints the@@ -243,7 +275,12 @@ TLS/HTTP2 handshake, and `cf_clearance` is bound to a real browser. A server-sid`fetch` with a valid cookie may still draw a challenge, on a 403 or on any other status(the `cf-mitigated: challenge` header, a challenge page, or a redirect to one). When thathappens the connector reports `forbidden` and points you at the official export lane; it-never loop-retries. Sustained rate limiting ends the run as `rate_limited` instead of+never loop-retries. Any other 403 (a JSON error body or a `www-authenticate` header)+ends the run as `auth_required` without a token refresh, and a redirect is never+followed (the cookie is only ever sent to the provider's own origin): it ends the run as+`auth_required` too. ChatGPT's token refresh obeys the same rules, so a refused refresh+reports `forbidden`, `rate_limited` or `auth_required`, and `connectors auth` reports+it without probing further. Sustained rate limiting ends the run as `rate_limited` instead ofworking through the rest of the history, and five conversation fetches in a row that failwith a server error or no response stop it as `partial` (`stopReason:consecutive_fetch_failures`). If server-side fetch is reliably blocked in your environment, prefer@@ -256,6 +293,8 @@ the export-file lane (`conversation-archive`) — it always works.| Symptom | Cause | Fix | Who acts | Consent | Verify ||---|---|---|---|---|---|| `forbidden` | Cloudflare/bot challenge on server-side fetch | Use the official export + `gbrain transcripts ingest` | user (downloads the export); agent ingests it | none | `gbrain connectors status --json` |+| `partial` with `stopReason: max_requests` or `deadline` | the run reached its request ceiling, `--max-requests` or `--deadline` ([request bounds](#request-bounds)) | Run `gbrain connectors sync <provider>` again, without `--full`; imported conversations are skipped | agent | `credentials` | `gbrain connectors status --json` |+| `connectors sync --all` prints `Skipped <p>: connectors.<p>.auto_sync is off` | that provider's owner has not opted in to unattended sync | Nothing, or sync it once explicitly with `gbrain connectors sync <p>`; `gbrain config set connectors.<p>.auto_sync true` opts in | user (decides on unattended sync) | `credentials` | `gbrain config get connectors.<p>.auto_sync` || `rate_limited` | the provider kept answering 429 after four retries, or asked for a wait over two minutes | Wait, then re-run; the next sync resumes where this one stopped. Don't loop it | agent | `credentials` | `gbrain connectors status --json` || `auth_required` with "cannot carry" in the hint | the saved cookie or token holds a line break, control or non-ASCII character (`invalid_header_value`); nothing was sent | Re-copy the Cookie header on one line, `gbrain connectors auth` | user (copies the cookie) | `credentials` | `gbrain connectors status --json` || `auth_required` | cookie expired/invalid | Re-copy a fresh Cookie header, `gbrain connectors auth` | user (copies a fresh Cookie header) | `credentials` | `gbrain connectors status --json` |diff --git a/src/commands/connectors/auth.ts b/src/commands/connectors/auth.tsindex ba255d0886..4fded38f62 100644--- a/src/commands/connectors/auth.ts+++ b/src/commands/connectors/auth.ts@@ -5,7 +5,9 @@* from stdin so the secret never lands in argv/`ps`. `--try-oauth` (chatgpt)* attempts the best-effort OAuth PKCE loopback first, then probes and falls back* to cookie guidance. Every path ends with a probe + a one-line verdict; nothing- * is saved on a failed probe unless `--force`.+ * is saved on a failed probe unless `--force`. A ChatGPT cookie first mints a+ * token through the same client; a failed mint is the verdict and no probe+ * follows it (#7515).*/import type { BrainEngine } from '../../core/engine.ts';@@ -14,11 +16,10 @@ import { shellQuote } from '../../core/agent-output.ts';import { agentBlock } from '../../core/agent-markers.ts';import { isInteractive } from '../../core/interaction.ts';import { readStdinPayload } from '../../core/stdin-read.ts';-import { ConnectorClient } from '../../core/connectors/client.ts';-import type { ConnectorFetch } from '../../core/connectors/client.ts';+import { ConnectorClient, probeFailure } from '../../core/connectors/client.ts';import { deleteCredential, saveCredential } from '../../core/connectors/credentials.ts';import { getConnectorProvider, isConnectorProviderName } from '../../core/connectors/registry.ts';-import type { ChatHistoryProvider, ConnectorCredential } from '../../core/connectors/types.ts';+import type { ChatHistoryProvider, ConnectorCredential, ProbeResult } from '../../core/connectors/types.ts';interface AuthFlags {cookie?: string;@@ -80,15 +81,25 @@ function makeProbeClient(provider: ChatHistoryProvider, cred: ConnectorCredentiareturn new ConnectorClient({baseUrl: provider.baseUrl,headers: () => provider.authHeaders(cred),- refresh: provider.refreshAccessToken- ? () => provider.refreshAccessToken!(cred, fetch as unknown as ConnectorFetch)- : undefined,+ refresh: provider.refreshAccessToken ? (client) => provider.refreshAccessToken!(cred, client) : undefined,});}+/** chatgpt: mint an accessToken from the cookie up front, so the first sync doesn't start with a 401→refresh round-trip. */+async function mintToken(provider: ChatHistoryProvider, cred: ConnectorCredential, client: ConnectorClient): Promise<ProbeResult> {+ if (!cred.cookie || !provider.refreshAccessToken) return { ok: true };+ try {+ if (await provider.refreshAccessToken(cred, client)) return { ok: true };+ return { ok: false, kind: 'unauthorized', detail: 'the session endpoint returned no access token' };+ } catch (e) {+ return probeFailure(e);+ }+}+async function probeAndReport(provider: ChatHistoryProvider, cred: ConnectorCredential): Promise<boolean> {const client = makeProbeClient(provider, cred);- const r = await provider.probe(client);+ const minted = await mintToken(provider, cred, client);+ const r = minted.ok ? await provider.probe(client) : minted;if (r.ok) {console.log(`✓ ${provider.name}: credential verified — conversation history is reachable.`);return true;@@ -188,12 +199,6 @@ export async function runConnectorAuth(_engine: BrainEngine, args: string[]): PraccessToken: token || undefined,savedAt: new Date().toISOString(),};- // chatgpt: mint an accessToken from the cookie up front so the first sync- // doesn't start with a guaranteed 401→refresh round-trip.- if (cred.cookie && prov.refreshAccessToken) {- await prov.refreshAccessToken(cred, fetch as unknown as ConnectorFetch);- }-const ok = await probeAndReport(prov, cred);if (!ok && !flags.force) {console.error('Credential NOT saved (probe failed). Re-run with --force to save anyway.');diff --git a/src/commands/connectors/index.ts b/src/commands/connectors/index.tsindex f99c615d11..0bf03bea10 100644--- a/src/commands/connectors/index.ts+++ b/src/commands/connectors/index.ts@@ -6,7 +6,7 @@** gbrain connectors auth <provider> [--cookie V|--token V] [--no-browser] [--try-oauth] [--force]* gbrain connectors status [provider] [--json]- * gbrain connectors sync <provider>|--all [--full] [--dry-run] [--limit N] [--window-days N] [--source id] [--embed] [--background]+ * gbrain connectors sync <provider>|--all [--full] [--dry-run] [--limit N] [--window-days N] [--max-requests N] [--deadline D] [--source id] [--embed] [--background]* gbrain connectors logout <provider>* gbrain connectors providers*/@@ -32,8 +32,9 @@ function printHelp(): void {' --no-browser print the authorize URL instead of opening',' --force save even if the probe fails',' status [provider] Show credential/sync state (never prints secrets). --json',- ' sync <provider>|--all Fetch new conversations and ingest them.',+ ' sync <provider>|--all Fetch new conversations and ingest them (--all: providers with auto_sync on).',' --full --dry-run --limit N --window-days N --source <id>',+ ' --max-requests N (at most 10000) --deadline <90s|30m|2h>',' --embed --background',' logout <provider> Delete a stored credential.',' providers List available connector providers.',diff --git a/src/commands/connectors/sync.ts b/src/commands/connectors/sync.tsindex c1e70e239d..25465249ac 100644--- a/src/commands/connectors/sync.ts+++ b/src/commands/connectors/sync.ts@@ -4,6 +4,11 @@* Inline by default (PGLite-safe: it's the same runConnectorSync the handler* wraps). `--background` submits the `connector-sync` minion job on Postgres;* on PGLite (no worker daemon) it falls back to inline with a note.+ *+ * #7515: `--all` (the scheduled form) syncs only providers whose+ * `connectors.<p>.auto_sync` is on; an explicit provider overrides it.+ * `--max-requests` and `--deadline` bound the whole invocation under the hard+ * MAX_CONNECTOR_REQUESTS_PER_RUN ceiling every run has.*/import type { BrainEngine } from '../../core/engine.ts';@@ -14,7 +19,9 @@ import { runConnectorSync } from '../../core/connectors/sync.ts';import type { ConnectorSyncResult } from '../../core/connectors/sync.ts';import { connectorProviderNames, isConnectorProviderName } from '../../core/connectors/registry.ts';import { loadCredential } from '../../core/connectors/credentials.ts';-import { sourceIdKey } from '../../core/connectors/config-keys.ts';+import { autoSyncKey, isTruthy, sourceIdKey } from '../../core/connectors/config-keys.ts';+import { MAX_CONNECTOR_REQUESTS_PER_RUN } from '../../core/connectors/client.ts';+import { parseDurationSeconds } from '../../core/sync-concurrency.ts';import type { ConnectorProviderName } from '../../core/connectors/types.ts';import { flagValueError, intFlagValue } from '../../cli/flag-values.ts';import { usageError } from '../../cli/cli-error.ts';@@ -29,6 +36,19 @@ interface SyncFlags {background: boolean;json: boolean;all: boolean;+ maxRequests?: number;+ deadlineSec?: number;+}++function deadlineFlagValue(raw: string | undefined): number {+ const accepts = 'a duration such as 90s, 30m or 2h';+ try {+ const seconds = raw === undefined || raw.startsWith('-') ? undefined : parseDurationSeconds(raw, '--deadline');+ if (seconds !== undefined) return seconds;+ } catch {+ // falls through to the usage error below+ }+ throw flagValueError('--deadline', raw, accepts, '30m');}function parseFlags(args: string[]): { provider: string; providerIndex: number; flags: SyncFlags } {@@ -46,13 +66,15 @@ function parseFlags(args: string[]): { provider: string; providerIndex: number;// #5930 (D4): decimals, zero limits and unsafe integers are usage errors (exit 2), not Number() coercions.else if (a === '--limit') flags.limit = intFlagValue(args[++i], '--limit', { min: 1, example: 50 });else if (a === '--window-days') flags.windowDays = intFlagValue(args[++i], '--window-days', { min: 0, example: 30 });+ else if (a === '--max-requests') flags.maxRequests = intFlagValue(args[++i], '--max-requests', { min: 1, max: MAX_CONNECTOR_REQUESTS_PER_RUN, example: 500 });+ else if (a === '--deadline') flags.deadlineSec = deadlineFlagValue(args[++i]);else if (a === '--source') flags.source = args[++i];else if (!a.startsWith('-')) { provider = a; providerIndex = i; }}return { provider, providerIndex, flags };}-const SYNC_USAGE = 'gbrain connectors sync <chatgpt|claude>|--all [--full] [--dry-run] [--limit N] [--window-days N] [--source id] [--embed] [--background] [--json]';+const SYNC_USAGE = 'gbrain connectors sync <chatgpt|claude>|--all [--full] [--dry-run] [--limit N] [--window-days N] [--max-requests N] [--deadline 30m] [--source id] [--embed] [--background] [--json]';/** Agent contract v1: usage errors are `invalid_params` (exit 2, one `--json` envelope) naming the usage and the fix. */function syncUsageError(message: string, fix: { argv: string[]; inputs: Array<{ name: string; how: string }> }) {@@ -81,12 +103,18 @@ export async function runConnectorSyncCmd(engine: BrainEngine, args: string[]):let providers: ConnectorProviderName[];if (flags.all) {// Only providers that have a credential (env or file) are worth syncing.- providers = connectorProviderNames().filter((p) => loadCredential(p) !== null);- if (providers.length === 0) {+ const credentialed = connectorProviderNames().filter((p) => loadCredential(p) !== null);+ if (credentialed.length === 0) {console.error('No connector credentials found. Run `gbrain connectors auth <provider>` first.');setCliExitVerdict(1);return;}+ // #7515: --all is the scheduled form, so a provider whose owner turned auto_sync off is left alone.+ providers = [];+ for (const p of credentialed) {+ if (isTruthy(await engine.getConfig(autoSyncKey(p)))) providers.push(p);+ else console.error(`Skipped ${p}: connectors.${p}.auto_sync is off (\`gbrain connectors sync ${p}\` syncs it explicitly).`);+ }} else if (isConnectorProviderName(provider)) {providers = [provider];} else {@@ -99,6 +127,7 @@ export async function runConnectorSyncCmd(engine: BrainEngine, args: string[]):const sourceId = flags.source ?? (await engine.getConfig(sourceIdKey())) ?? 'default';const results: ConnectorSyncResult[] = [];+ const deadlineAt = flags.deadlineSec !== undefined ? Date.now() + flags.deadlineSec * 1000 : undefined;for (const p of providers) {if (flags.background && !flags.dryRun) {@@ -116,6 +145,8 @@ export async function runConnectorSyncCmd(engine: BrainEngine, args: string[]):limit: flags.limit,windowDays: flags.windowDays,embed: flags.embed,+ maxRequests: flags.maxRequests,+ deadlineAt,onProgress: (pr) => reporter.heartbeat(`${pr.phase}: listed ${pr.listed}, fetched ${pr.fetched}, imported ${pr.imported}`),});results.push(r);@@ -146,7 +177,10 @@ async function submitBackground(const slot = new Date().toISOString().slice(0, 13); // hour bucketconst job = await queue.add('connector-sync',- { provider, sourceId, full: flags.full, limit: flags.limit },+ {+ provider, sourceId, full: flags.full, limit: flags.limit, maxRequests: flags.maxRequests,+ deadlineSec: flags.deadlineSec, explicit: !flags.all,+ },{ idempotency_key: `connector-sync:${provider}:${slot}`, max_attempts: 2 },);console.log(`Queued connector-sync for ${provider} (job ${job.id}). Track with \`gbrain jobs get ${job.id}\`.`);diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 63bc53cc6a..97351e30ff 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1246,6 +1246,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.437.0', text: 'A chat-connector cookie or token holding a line break, NUL, another control character or a non-ASCII character is refused before any request (`invalid_header_value`): `connectors auth` reports it and `connectors sync` returns `auth_required` with that hint and stamps the auth error. A request that fails before a response is reported by its error code (`ECONNREFUSED`, `TypeError`), never by the runtime\'s message, so a header value can never be echoed into probe output, sync hints or logs (#7483).' },// GBRA-133 G2 (superseded remote blobs). `since` is stamped at the merge slot.{ since: '0.60.438.0', text: '`gbrain git commit-push` now keeps this machine\'s version of a file the remote changed back to a version this checkout already had at that path and later replaced (a stale clone or writer pushing an old copy, often inside a merge), instead of stopping with `integrate_conflict`. It reads the last 200 commits that changed the file. The push lists those files in `superseded_remote_paths` and the merge message names them. A version this checkout never had, a remote deletion and a file named with `--resolve` still conflict; when both kinds meet, `integrate_conflict` lists only the real conflicts and `detail.superseded` names the others.' },+ // GBRA-197 (#7515 chat-connector hardening). `since` is stamped at the merge slot.+ { since: 'TBD', text: 'Chat-connector syncs no longer refresh and retry after a 403: a 403 with a JSON error body or a `www-authenticate` header ends the run as `auth_required` at once, and a redirect is never followed (the session cookie only goes to the provider\'s own origin) and ends it as `auth_required` too. ChatGPT\'s token refresh now goes through the same client, so it is paced, counted and refused the same way: a refused refresh reports `forbidden`, `rate_limited` or `auth_required` instead of being ignored, and `gbrain connectors auth` stops there instead of probing. Re-copy the cookie when a sync reports `auth_required`.' },+ { since: 'TBD', text: '`gbrain connectors sync --all` now syncs only providers whose `connectors.<p>.auto_sync` is on and names each one it skips; a queued `connector-sync` job rechecks `auto_sync` when it starts and returns `skipped` if it was turned off. A host cron running `connectors sync --all` for a provider without `auto_sync` stops syncing it: turn `auto_sync` on, or run `gbrain connectors sync <provider>`, which still syncs either way.' },+ { since: 'TBD', text: 'Every chat-connector sync is bounded: at most 10,000 requests per run (5,000 per Claude organization, and at most 10 Claude organizations listed), list pages cut to the page size asked for, and new `--max-requests N` and `--deadline <90s|30m|2h>` flags on `gbrain connectors sync`. A run that reaches a bound ends `partial` with `stopReason` `max_requests` or `deadline`, keeps what it imported and holds the watermark; run `gbrain connectors sync <provider>` again (without `--full`) to continue.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 8a53771a80..f06f8eb5a7 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -43,7 +43,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'compile-context': ['--brain', '--budget', '--check', '--error-unmatch', '--git-path', '--help', '--include', '--include-core', '--json', '--out', '--remove-core', '--revision', '--show-toplevel', '--source', '--stdout', '--target'],'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--background', '--brain', '--budget-ms', '--call-site', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--limit', '--markdown', '--min', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--target', '--threshold', '--tier', '--timeout', '--timings', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],- 'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--token', '--try-oauth', '--wait', '--window-days', '--yes'],+ 'connectors': ['--accept-pending', '--all', '--background', '--brain', '--cookie', '--deadline', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--max-requests', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--token', '--try-oauth', '--wait', '--window-days', '--workers', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],'core': ['--apply', '--brain', '--fail-fast', '--help', '--include-core', '--json', '--priority', '--revision', '--slug', '--source', '--tools-json'],'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],diff --git a/src/core/connectors/client.ts b/src/core/connectors/client.tsindex a4f0a99b5d..39a5aba810 100644--- a/src/core/connectors/client.ts+++ b/src/core/connectors/client.ts@@ -3,8 +3,9 @@** Modeled on `GitHubClient` (`../github-source.ts`): plain `fetch` against a* hardcoded base ORIGIN with an off-origin guard so the cookie/bearer never- * leaks, a browser User-Agent, refresh-once-on-401, and Retry-After backoff via- * the shared `parseRetryAfterMs`. NOT routed through `fetchWithSSRFGuard` — that+ * leaks, redirects never followed, a browser User-Agent, refresh-once-on-401+ * (never on a 403: #7515), Retry-After backoff via the shared+ * `parseRetryAfterMs`, and a per-run request ceiling and deadline. NOT routed through `fetchWithSSRFGuard` — that* rewrites the URL to a resolved IP and breaks SNI on Cloudflare-fronted hosts;* SSRF guards are for user-controlled URLs, and these base origins are* compile-time constants.@@ -16,6 +17,7 @@*/import { classifyResponse } from './classify.ts';+import type { ProbeResult } from './types.ts';/** Same shape as github-source's FetchImpl, re-declared to avoid a value import. */export type ConnectorFetch = (url: string, init: RequestInit) => Promise<Response>;@@ -71,6 +73,18 @@ export class ConnectorNetworkError extends Error {}}+/** Requests one run may make, whatever --max-requests asks for (#7515). At the 700 ms spacing this is about 2 hours. */+export const MAX_CONNECTOR_REQUESTS_PER_RUN = 10_000;++/** #7515: the run reached its request ceiling or its deadline; it stops before the next request. */+export class ConnectorRunLimitError extends Error {+ readonly code = 'run_limit';+ constructor(readonly reason: 'max_requests' | 'deadline', message: string) {+ super(message);+ this.name = 'ConnectorRunLimitError';+ }+}+/** A response that stayed non-OK after the client's bounded retries. `status` tells a provider outage (5xx) from an item error (4xx). */export class ConnectorHttpError extends Error {constructor(message: string, readonly status: number) {@@ -79,6 +93,16 @@ export class ConnectorHttpError extends Error {}}+/** A probe's verdict for an error this client threw: one table for both providers and `connectors auth`. */+export function probeFailure(e: unknown): Exclude<ProbeResult, { ok: true }> {+ const detail = e instanceof Error ? e.message : String(e);+ if (e instanceof ConnectorAuthError) return { ok: false, kind: 'unauthorized', detail };+ if (e instanceof ConnectorForbiddenError) return { ok: false, kind: 'forbidden_fingerprint', detail };+ if (e instanceof ConnectorRateLimitedError) return { ok: false, kind: 'rate_limited', detail };+ if (e instanceof ConnectorCredentialFormatError) return { ok: false, kind: 'invalid_credential', detail };+ return { ok: false, kind: 'network', detail };+}+/** Printable ASCII only: a cookie or token never needs more, and Bun's fetch throws on anything else. */const HEADER_VALUE_RE = /^[\x20-\x7e]*$/;@@ -92,8 +116,15 @@ export interface ConnectorClientOpts {baseUrl: string;/** Auth headers (bearer and/or Cookie), re-read per request. */headers: () => Promise<Record<string, string>>;- /** 401 → this refreshes the credential (re-mint accessToken from cookie / oauth grant) → retry once. */- refresh?: () => Promise<boolean>;+ /**+ * 401 → this refreshes the credential (re-mint accessToken from cookie / oauth grant) → retry once. It is handed+ * this client so the refresh request gets the same origin guard, redirect refusal, pacing and request budget.+ */+ refresh?: (client: ConnectorClient) => Promise<boolean>;+ /** Requests this client may make; capped at MAX_CONNECTOR_REQUESTS_PER_RUN. */+ maxRequests?: number;+ /** Epoch ms after which no request (or retry wait) starts. */+ deadlineAt?: number;/** Polite spacing between requests, ms. Default 700. */minDelayMs?: number;/** Test seam. Default global fetch. */@@ -130,7 +161,10 @@ export class ConnectorClient {private readonly baseUrl: string;private readonly origin: string;private readonly headers: () => Promise<Record<string, string>>;- private readonly refresh?: () => Promise<boolean>;+ private readonly refresh?: (client: ConnectorClient) => Promise<boolean>;+ private readonly maxRequests: number;+ private readonly deadlineAt?: number;+ private requests = 0;private readonly minDelayMs: number;private readonly fetchImpl: ConnectorFetch;private readonly sleep: (ms: number, signal?: AbortSignal) => Promise<void>;@@ -143,6 +177,8 @@ export class ConnectorClient {this.origin = new URL(this.baseUrl).origin;this.headers = opts.headers;this.refresh = opts.refresh;+ this.maxRequests = Math.min(opts.maxRequests ?? MAX_CONNECTOR_REQUESTS_PER_RUN, MAX_CONNECTOR_REQUESTS_PER_RUN);+ this.deadlineAt = opts.deadlineAt;this.minDelayMs = opts.minDelayMs ?? 700;this.fetchImpl = opts.fetchImpl ?? (fetch as unknown as ConnectorFetch);this.sleep = opts.sleep ?? defaultSleep;@@ -161,6 +197,16 @@ export class ConnectorClient {return url;}+ /** Stop before a request (or a retry wait of `waitMs`) that the run's ceiling or deadline does not allow. */+ private checkLimits(pathOrUrl: string, waitMs = 0): void {+ if (this.deadlineAt !== undefined && this.now() + waitMs >= this.deadlineAt) {+ throw new ConnectorRunLimitError('deadline', `connector: run deadline reached before ${pathOrUrl}`);+ }+ if (waitMs === 0 && this.requests >= this.maxRequests) {+ throw new ConnectorRunLimitError('max_requests', `connector: run stopped at its ${this.maxRequests}-request limit before ${pathOrUrl}`);+ }+ }+/** Cooperative pacing so we stay a polite client. */private async pace(signal?: AbortSignal): Promise<void> {const since = this.now() - this.lastRequestAt;@@ -174,18 +220,26 @@ export class ConnectorClient {* GET a URL and parse JSON. Handles pacing, 401→refresh→retry-once,* 429/Retry-After backoff, and the §2A 403 disambiguation. Throws* `ConnectorAuthError` / `ConnectorForbiddenError` on terminal states.+ * A 403 or a redirect is terminal without a refresh (#7515). `headers`+ * replaces the auth headers for this request; `refresh: false` (the+ * refresh request itself) never refreshes.*/- async fetchJSON<T>(pathOrUrl: string, opts: { signal?: AbortSignal } = {}): Promise<T> {+ async fetchJSON<T>(+ pathOrUrl: string,+ opts: { signal?: AbortSignal; headers?: Record<string, string>; refresh?: boolean } = {},+ ): Promise<T> {const url = this.resolve(pathOrUrl);let refreshed = false;let rateRetries = 0;for (;;) {- const auth = await this.headers();+ const auth = opts.headers ?? await this.headers();for (const [name, value] of Object.entries(auth)) {if (!HEADER_VALUE_RE.test(value)) throw new ConnectorCredentialFormatError(name);}+ this.checkLimits(pathOrUrl);await this.pace(opts.signal);+ this.requests++;let res: Response;try {res = await this.fetchImpl(url, {@@ -209,10 +263,11 @@ export class ConnectorClient {}if (c.kind === 'auth_required') {- if (this.refresh && !refreshed) {+ // A session-cookie 403 is a refusal a re-minted token cannot fix: stop instead of refreshing (#7515).+ if (this.refresh && !refreshed && res.status !== 403 && opts.refresh !== false) {this.log(`[connector] ${c.detail}; refreshing credential and retrying once`);refreshed = true;- const ok = await this.refresh();+ const ok = await this.refresh(this);if (ok) continue;}throw new ConnectorAuthError(`${c.detail} (${pathOrUrl})`);@@ -230,6 +285,7 @@ export class ConnectorClient {);}if (rateRetries < MAX_RATE_RETRIES) {+ this.checkLimits(pathOrUrl, waitMs);rateRetries++;this.log(`[connector] ${c.detail}; retry ${rateRetries}/${MAX_RATE_RETRIES} in ${Math.round(waitMs / 1000)}s`);await this.sleep(waitMs, opts.signal);@@ -238,8 +294,14 @@ export class ConnectorClient {throw new ConnectorRateLimitedError(`connector: rate limited on ${pathOrUrl} after ${MAX_RATE_RETRIES} retries`);}+ // redirect: (fetch runs with redirect 'manual') never followed, so the cookie never leaves the origin; an API+ // that redirects is sending the session to a login page (#7515).+ if (res.status >= 300 && res.status < 400) {+ throw new ConnectorAuthError(`HTTP ${res.status} redirect not followed (${pathOrUrl}); the session likely expired`);+ }// server_error or drift: one bounded retry for transient 5xx, else throw.if (c.kind === 'server_error' && rateRetries < MAX_RATE_RETRIES) {+ this.checkLimits(pathOrUrl, 1000 * (rateRetries + 1));rateRetries++;await this.sleep(1000 * rateRetries, opts.signal);continue;diff --git a/src/core/connectors/providers/chatgpt.ts b/src/core/connectors/providers/chatgpt.tsindex 18ff0c69e6..61a7dc6228 100644--- a/src/core/connectors/providers/chatgpt.ts+++ b/src/core/connectors/providers/chatgpt.ts@@ -13,11 +13,13 @@* GET /backend-api/conversation/{id} → export-shaped conversation** The durable credential is the raw Cookie header; the accessToken is a- * ~week-lived bearer re-minted from the cookie on 401 (refreshAccessToken).+ * ~week-lived bearer re-minted from the cookie on 401 (refreshAccessToken),+ * through the shared client (#7515).*/import type { HostSpecTarget } from '../../bootstrap/host-specs.ts';-import type { ConnectorClient, ConnectorFetch } from '../client.ts';+import { probeFailure } from '../client.ts';+import type { ConnectorClient } from '../client.ts';import type {ChatHistoryProvider,ConnectorCredential,@@ -59,7 +61,7 @@ export const CHATGPT_OAUTH: OAuthPkceConfig = {redirectPort: 1455,};-const LIST_PAGE_LIMIT = 28; // the UI's max page size+const LIST_PAGE_LIMIT = 28; // the UI's max page size; a longer page is truncated to it (#7515)const MAX_LIST_PAGES = 500; // safety cap PER PASS; never treat a truncated list as completeinterface SessionResponse {@@ -128,7 +130,11 @@ async function* listPass(`chatgpt: conversations list${archived ? ' (archived)' : ''} returned no items array (shape drift)`,);}- const total = typeof res.total === 'number' ? res.total : offset + res.items.length;+ // #7515: a page longer than asked for is cut to the page size and the walk continues from there. One that also+ // brings nothing new is ignoring offset, and truncating it would silently drop the rest.+ const items = res.items.slice(0, LIST_PAGE_LIMIT);+ const overLong = res.items.length > LIST_PAGE_LIMIT;+ const total = typeof res.total === 'number' ? res.total : offset + items.length;if (lastTotal !== undefined && total < lastTotal && offset > 0) {offset = Math.max(0, offset - (lastTotal - total));lastTotal = total;@@ -138,13 +144,15 @@ async function* listPass(continue;}lastTotal = total;- for (const it of res.items) {+ let fresh = 0;+ for (const it of items) {const id = typeof it.id === 'string' ? it.id : '';if (!id) continue;const updatedAt = toIso(it.update_time) || toIso(it.create_time);if (stopBefore && updatedAt && updatedAt <= stopBefore) return; // rest are olderif (seen.has(id)) continue;seen.add(id);+ fresh++;yield {id,title: typeof it.title === 'string' ? it.title : undefined,@@ -152,8 +160,11 @@ async function* listPass(createdAt: toIso(it.create_time) || undefined,};}- offset += res.items.length;- if (res.items.length === 0 || offset >= total) break;+ if (overLong && fresh === 0 && offset > 0) {+ throw new Error(`chatgpt: conversations list${archived ? ' (archived)' : ''} ignores offset and returns over-long pages; refusing to treat a truncated list as complete`);+ }+ offset += items.length;+ if (items.length === 0 || offset >= total) break;pages++;if (pages >= MAX_LIST_PAGES) {throw new Error(@@ -178,24 +189,21 @@ export const chatgptProvider: ChatHistoryProvider = {return h;},- async refreshAccessToken(cred: ConnectorCredential, fetchImpl: ConnectorFetch): Promise<boolean> {+ /**+ * #7515: the session request goes through the shared client (same origin only, redirects refused, paced, counted)+ * with the cookie alone, and never refreshes itself. A refusal throws the client's terminal error (forbidden,+ * rate limited, auth) instead of being swallowed; a session with no token returns false.+ */+ async refreshAccessToken(cred: ConnectorCredential, client: ConnectorClient): Promise<boolean> {if (!cred.cookie) return false; // nothing durable to re-mint from- try {- const res = await fetchImpl(`${CHATGPT_BASE_URL}/api/auth/session`, {- headers: { cookie: cred.cookie, accept: 'application/json' },- });- if (!res.ok) return false;- const body = (await res.json()) as SessionResponse;- if (!body.accessToken) return false;- cred.accessToken = body.accessToken;- if (body.expires) {- const ms = Date.parse(body.expires);- if (Number.isFinite(ms)) cred.expiresAt = ms;- }- return true;- } catch {- return false;+ const body = await client.fetchJSON<SessionResponse>('/api/auth/session', { headers: { cookie: cred.cookie }, refresh: false });+ if (!body?.accessToken) return false;+ cred.accessToken = body.accessToken;+ if (body.expires) {+ const ms = Date.parse(body.expires);+ if (Number.isFinite(ms)) cred.expiresAt = ms;}+ return true;},async probe(client: ConnectorClient, signal?: AbortSignal): Promise<ProbeResult> {@@ -209,13 +217,7 @@ export const chatgptProvider: ChatHistoryProvider = {}return { ok: true };} catch (e) {- const name = (e as { name?: string }).name;- const msg = e instanceof Error ? e.message : String(e);- if (name === 'ConnectorAuthError') return { ok: false, kind: 'unauthorized', detail: msg };- if (name === 'ConnectorForbiddenError') return { ok: false, kind: 'forbidden_fingerprint', detail: msg };- if (name === 'ConnectorRateLimitedError') return { ok: false, kind: 'rate_limited', detail: msg };- if (name === 'ConnectorCredentialFormatError') return { ok: false, kind: 'invalid_credential', detail: msg };- return { ok: false, kind: 'network', detail: msg };+ return probeFailure(e);}},diff --git a/src/core/connectors/providers/claude.ts b/src/core/connectors/providers/claude.tsindex fb36bdea5a..6faa5df01b 100644--- a/src/core/connectors/providers/claude.ts+++ b/src/core/connectors/providers/claude.ts@@ -17,10 +17,14 @@* account-safe); every one is listed, and each conversation is fetched from* the org that listed it: stubs carry `orgId`, which the sync records with a* failed conversation so a later retry by id reaches the same org (#6387).- * The list is paged with limit/offset (C-17).+ * The list is paged with limit/offset (C-17). #7515 bounds: at most+ * CLAUDE_MAX_ORGS organizations are listed (a listing cut there is never+ * complete), at most CLAUDE_MAX_REQUESTS_PER_ORG requests go to one+ * organization per run, and a page longer than LIST_PAGE_LIMIT is truncated.*/import type { HostSpecTarget } from '../../bootstrap/host-specs.ts';+import { ConnectorRunLimitError, probeFailure } from '../client.ts';import type { ConnectorClient } from '../client.ts';import { toIso } from './chatgpt.ts';import type {@@ -52,12 +56,18 @@ export const CLAUDE_WEB_API_SPEC_TARGET: HostSpecTarget = {'not probed live in this repo; drift alarm (no array / no chat_messages) is the backstop.',};-const memoOrgs = new WeakMap<ConnectorClient, string[]>();+const memoOrgs = new WeakMap<ConnectorClient, { ids: string[]; dropped: number }>();+/** Requests sent to each organization, per client (one run). */+const memoOrgRequests = new WeakMap<ConnectorClient, Map<string, number>>();/** Conversation id → the org that listed it, per client. */const memoConversationOrg = new WeakMap<ConnectorClient, Map<string, string>>();const LIST_PAGE_LIMIT = 100;const MAX_LIST_PAGES = 500; // per org; never treat a truncated list as complete+/** #7515: organizations listed per run; more makes the listing incomplete (partial run). */+export const CLAUDE_MAX_ORGS = 10;+/** #7515: requests (list pages and conversation fetches) sent to one organization per run. */+export const CLAUDE_MAX_REQUESTS_PER_ORG = 5_000;interface OrgRow {uuid?: string;@@ -77,19 +87,32 @@ interface MsgRow {content?: Array<{ type?: string; text?: string }>;}-/** Every chat-capable org (an org that declares no capabilities counts). */-async function resolveOrgs(client: ConnectorClient, signal?: AbortSignal): Promise<string[]> {+/** Every chat-capable org (an org that declares no capabilities counts), the first CLAUDE_MAX_ORGS of them. */+async function resolveOrgs(client: ConnectorClient, signal?: AbortSignal): Promise<{ ids: string[]; dropped: number }> {const cached = memoOrgs.get(client);if (cached) return cached;const orgs = await client.fetchJSON<OrgRow[]>('/api/organizations', { signal });- const ids = Array.isArray(orgs)+ const all = Array.isArray(orgs)? orgs.filter((o) => typeof o?.uuid === 'string' && (!Array.isArray(o.capabilities) || o.capabilities.includes('chat'))).map((o) => o.uuid as string): [];- if (!ids.length) throw new Error('claude: /api/organizations returned no chat-capable org (shape drift)');- memoOrgs.set(client, ids);- return ids;+ if (!all.length) throw new Error('claude: /api/organizations returned no chat-capable org (shape drift)');+ const resolved = { ids: all.slice(0, CLAUDE_MAX_ORGS), dropped: Math.max(0, all.length - CLAUDE_MAX_ORGS) };+ memoOrgs.set(client, resolved);+ return resolved;+}++/** A request to one organization, counted against CLAUDE_MAX_REQUESTS_PER_ORG. */+async function orgFetch<T>(client: ConnectorClient, org: string, path: string, signal?: AbortSignal): Promise<T> {+ const counts = memoOrgRequests.get(client) ?? new Map<string, number>();+ memoOrgRequests.set(client, counts);+ const sent = counts.get(org) ?? 0;+ if (sent >= CLAUDE_MAX_REQUESTS_PER_ORG) {+ throw new ConnectorRunLimitError('max_requests', `claude: run stopped at the ${CLAUDE_MAX_REQUESTS_PER_ORG}-request limit for one organization`);+ }+ counts.set(org, sent + 1);+ return client.fetchJSON<T>(`/api/organizations/${encodeURIComponent(org)}${path}`, { signal });}/** Assemble message text: prefer flat `text`, else join text-type content blocks. */@@ -125,23 +148,14 @@ export const claudeProvider: ChatHistoryProvider = {async probe(client: ConnectorClient, signal?: AbortSignal): Promise<ProbeResult> {try {- const [org] = await resolveOrgs(client, signal);- const list = await client.fetchJSON<ConvRow[]>(- `/api/organizations/${encodeURIComponent(org)}/chat_conversations?limit=1`,- { signal },- );+ const [org] = (await resolveOrgs(client, signal)).ids;+ const list = await orgFetch<ConvRow[]>(client, org, '/chat_conversations?limit=1', signal);if (!Array.isArray(list)) {return { ok: false, kind: 'drift', detail: 'chat_conversations probe returned a non-array' };}return { ok: true };} catch (e) {- const name = (e as { name?: string }).name;- const msg = e instanceof Error ? e.message : String(e);- if (name === 'ConnectorAuthError') return { ok: false, kind: 'unauthorized', detail: msg };- if (name === 'ConnectorForbiddenError') return { ok: false, kind: 'forbidden_fingerprint', detail: msg };- if (name === 'ConnectorRateLimitedError') return { ok: false, kind: 'rate_limited', detail: msg };- if (name === 'ConnectorCredentialFormatError') return { ok: false, kind: 'invalid_credential', detail: msg };- return { ok: false, kind: 'network', detail: msg };+ return probeFailure(e);}},@@ -149,7 +163,7 @@ export const claudeProvider: ChatHistoryProvider = {client: ConnectorClient,opts: { signal?: AbortSignal; stopBefore?: string } = {},): AsyncGenerator<ConversationStub> {- const orgs = await resolveOrgs(client, opts.signal);+ const { ids: orgs, dropped } = await resolveOrgs(client, opts.signal);const conversationOrg = new Map<string, string>();memoConversationOrg.set(client, conversationOrg);const stubs: ConversationStub[] = [];@@ -162,13 +176,11 @@ export const claudeProvider: ChatHistoryProvider = {if (page >= MAX_LIST_PAGES) {throw new Error(`claude: list hit the ${MAX_LIST_PAGES}-page cap; refusing to treat a truncated list as complete`);}- const rows = await client.fetchJSON<ConvRow[]>(- `/api/organizations/${encodeURIComponent(org)}/chat_conversations?limit=${LIST_PAGE_LIMIT}&offset=${offset}`,- { signal: opts.signal },- );- if (!Array.isArray(rows)) {+ const res = await orgFetch<ConvRow[]>(client, org, `/chat_conversations?limit=${LIST_PAGE_LIMIT}&offset=${offset}`, opts.signal);+ if (!Array.isArray(res)) {throw new Error('claude: chat_conversations returned a non-array (shape drift)');}+ const rows = res.slice(0, LIST_PAGE_LIMIT);let fresh = 0;let allOlder = rows.length > 0;for (const r of rows) {@@ -185,6 +197,9 @@ export const claudeProvider: ChatHistoryProvider = {orgId: org,});}+ if (fresh === 0 && res.length > LIST_PAGE_LIMIT) {+ throw new Error('claude: chat_conversations ignores offset and returns over-long pages; refusing to treat a truncated list as complete');+ }if (fresh === 0 || allOlder) break;offset += rows.length;}@@ -192,9 +207,12 @@ export const claudeProvider: ChatHistoryProvider = {// Sort newest-first by updated_at (the API order is not guaranteed).stubs.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0));for (const s of stubs) {- if (opts.stopBefore && s.updatedAt && s.updatedAt <= opts.stopBefore) return; // rest are older+ if (opts.stopBefore && s.updatedAt && s.updatedAt <= opts.stopBefore) break; // rest are olderyield s;}+ if (dropped) {+ throw new Error(`claude: ${dropped} chat-capable organization(s) past the ${CLAUDE_MAX_ORGS}-organization cap were not listed; the listing is incomplete`);+ }},async fetchConversation(@@ -202,10 +220,9 @@ export const claudeProvider: ChatHistoryProvider = {id: string,opts: { signal?: AbortSignal; orgId?: string } = {},): Promise<Record<string, unknown>> {- const org = opts.orgId ?? memoConversationOrg.get(client)?.get(id) ?? (await resolveOrgs(client, opts.signal))[0];- const conv = await client.fetchJSON<Record<string, unknown>>(- `/api/organizations/${encodeURIComponent(org)}/chat_conversations/${encodeURIComponent(id)}?tree=True&rendering_mode=messages`,- { signal: opts.signal },+ const org = opts.orgId ?? memoConversationOrg.get(client)?.get(id) ?? (await resolveOrgs(client, opts.signal)).ids[0];+ const conv = await orgFetch<Record<string, unknown>>(+ client, org, `/chat_conversations/${encodeURIComponent(id)}?tree=True&rendering_mode=messages`, opts.signal,);const rawMsgs = Array.isArray((conv as { chat_messages?: unknown }).chat_messages)? ((conv as { chat_messages: MsgRow[] }).chat_messages)diff --git a/src/core/connectors/sync.ts b/src/core/connectors/sync.tsindex 6d89798ff9..68c2880b53 100644--- a/src/core/connectors/sync.ts+++ b/src/core/connectors/sync.ts@@ -44,6 +44,7 @@ import {ConnectorHttpError,ConnectorNetworkError,ConnectorRateLimitedError,+ ConnectorRunLimitError,} from './client.ts';import type { ConnectorFetch } from './client.ts';import { getConnectorProvider } from './registry.ts';@@ -113,8 +114,11 @@ export interface ConnectorSyncResult {gone: string[];spoolPaths: string[];embedKickoff: EmbedKickoffOutcome;- /** #7482: set when the run stopped fetching early because CONSECUTIVE_FETCH_FAILURE_LIMIT fetches failed in a row. */- stopReason?: 'consecutive_fetch_failures';+ /**+ * Why the run stopped early: CONSECUTIVE_FETCH_FAILURE_LIMIT fetches failed in a row (#7482), or it reached its+ * request ceiling or deadline (#7515: MAX_CONNECTOR_REQUESTS_PER_RUN, --max-requests, --deadline).+ */+ stopReason?: 'consecutive_fetch_failures' | 'max_requests' | 'deadline';hint?: string;}@@ -181,6 +185,10 @@ export interface ConnectorSyncOpts {windowDays?: number;/** Embed during ingest (default OFF — the kickoff catches up post-run). */embed?: boolean;+ /** Request ceiling for this run, capped at MAX_CONNECTOR_REQUESTS_PER_RUN (#7515). */+ maxRequests?: number;+ /** Epoch ms after which the run starts no request (#7515). */+ deadlineAt?: number;signal?: AbortSignal;onProgress?: (p: { phase: 'list' | 'fetch' | 'ingest'; listed: number; fetched: number; imported: number }) => void;deps?: ConnectorSyncDeps;@@ -196,17 +204,17 @@ export function subtractDays(iso: string, days: number, now: () => number): strifunction buildClient(provider: ChatHistoryProvider,cred: import('./types.ts').ConnectorCredential,+ opts: ConnectorSyncOpts,deps: ConnectorSyncDeps,): ConnectorClient {if (deps.client) return deps.client;- const fetchImpl = deps.fetchImpl;return new ConnectorClient({baseUrl: deps.baseUrlOverride ?? provider.baseUrl,headers: () => provider.authHeaders(cred),- refresh: provider.refreshAccessToken- ? () => provider.refreshAccessToken!(cred, fetchImpl ?? (fetch as unknown as ConnectorFetch))- : undefined,- fetchImpl,+ refresh: provider.refreshAccessToken ? (client) => provider.refreshAccessToken!(cred, client) : undefined,+ maxRequests: opts.maxRequests,+ deadlineAt: opts.deadlineAt,+ fetchImpl: deps.fetchImpl,sleep: deps.sleep,now: deps.now,log: deps.log,@@ -254,7 +262,7 @@ export async function runConnectorSync(return { ...base, status: 'auth_required', hint: provider.sessionInstructions() };}- const client = buildClient(provider, resolved.cred, deps);+ const client = buildClient(provider, resolved.cred, opts, deps);// Probe first: a dead credential must not burn a full list+fetch.const probe = await provider.probe(client, opts.signal);@@ -290,6 +298,7 @@ export async function runConnectorSync(}} catch (e) {listErrored = true;+ if (e instanceof ConnectorRunLimitError) base.stopReason = e.reason;const term = classifyThrow(e);if (term) {if (term === 'auth_required') await stampAuthError(engine, opts.provider, now);@@ -363,8 +372,9 @@ export async function runConnectorSync(consecutiveFetchFailures = 0;opts.onProgress?.({ phase: 'fetch', listed: stubs.length, fetched, imported: importedTotal });} catch (e) {- // A cancelled run says nothing about the conversation: no strike.+ // A cancelled run, or one at its request ceiling or deadline, says nothing about the conversation: no strike.if (opts.signal?.aborted) { aborted = true; break; }+ if (e instanceof ConnectorRunLimitError) { base.stopReason = e.reason; break; }const term = classifyThrow(e);if (term) {if (term === 'auth_required') await stampAuthError(engine, opts.provider, now);@@ -512,9 +522,13 @@ export async function runConnectorSync(/** What the run left unarchived (failed or still publishing) and the command that shows it. */function unresolvedHint(base: ConnectorSyncResult, provider: ConnectorProviderName, sourceId: string): string | undefined {const parts: string[] = [];- if (base.stopReason) {+ if (base.stopReason === 'consecutive_fetch_failures') {parts.push(`Stopped after ${CONSECUTIVE_FETCH_FAILURE_LIMIT} conversation fetches failed in a row; the provider may be ` +'throttling or down. The next sync resumes from the same place.');+ } else if (base.stopReason) {+ parts.push(`Stopped at the run's ${base.stopReason === 'deadline' ? 'deadline' : 'request limit'} before every ` ++ `conversation was fetched. Run \`gbrain connectors sync ${provider}\` again (without --full) to continue: conversations ` ++ 'already imported are skipped.');}if (base.unresolved > 0) {parts.push(diff --git a/src/core/connectors/types.ts b/src/core/connectors/types.tsindex 174529d188..187e904743 100644--- a/src/core/connectors/types.ts+++ b/src/core/connectors/types.ts@@ -21,10 +21,7 @@import type { HostSpecTarget } from '../bootstrap/host-specs.ts';import type { TranscriptFormat } from '../transcripts/types.ts';-import type { ConnectorClient, ConnectorFetch } from './client.ts';--/** Re-export alias so the provider interface can name the fetch seam type. */-export type ConnectorFetchRef = ConnectorFetch;+import type { ConnectorClient } from './client.ts';/** Providers with a live connector in v1. Perplexity stays manual-only (no adapter). */export type ConnectorProviderName = 'chatgpt' | 'claude';@@ -116,11 +113,14 @@ export interface ChatHistoryProvider {authHeaders(cred: ConnectorCredential): Promise<Record<string, string>>;/*** Re-mint a short-lived accessToken from the durable cookie (chatgpt:- * `GET /api/auth/session`). Mutates `cred` in place, persists it, returns- * true on success. Absent when the provider has no re-mint path (claude: the- * cookie IS the auth, so a 401 is terminal → auth_required).+ * `GET /api/auth/session`) through `client`, so the request keeps the+ * client's origin guard, redirect refusal, pacing and request budget+ * (#7515). Mutates `cred` in place and returns true on success, false when+ * the session holds no token; a refusal throws the client's terminal error.+ * Absent when the provider has no re-mint path (claude: the cookie IS the+ * auth, so a 401 is terminal → auth_required).*/- refreshAccessToken?(cred: ConnectorCredential, fetchImpl: ConnectorFetchRef): Promise<boolean>;+ refreshAccessToken?(cred: ConnectorCredential, client: ConnectorClient): Promise<boolean>;/** Cheap liveness check — does this credential reach conversation history? */probe(client: ConnectorClient, signal?: AbortSignal): Promise<ProbeResult>;/**diff --git a/src/core/minions/handlers/connector-sync.ts b/src/core/minions/handlers/connector-sync.tsindex af32b19315..dda8197c69 100644--- a/src/core/minions/handlers/connector-sync.ts+++ b/src/core/minions/handlers/connector-sync.ts@@ -1,6 +1,12 @@/*** handlers/connector-sync.ts — the `connector-sync` minion handler.*+ * #7515: a job runs only while `connectors.<p>.auto_sync` is on, rechecked+ * when the job starts (autopilot checks it at enqueue time, but the owner may+ * turn it off while the job waits); a job `connectors sync <provider>+ * --background` queued (`explicit: true`) overrides it. Remote callers cannot+ * submit this job.+ ** Copies the embed-backfill skeleton: strict param parse, per-provider* single-flight DB lock (already_in_progress on contention, never a throw),* signal threading, progress → job.updateProgress, terminal auth/forbidden@@ -17,6 +23,7 @@ import type { MinionJobContext } from '../types.ts';import { runConnectorSync } from '../../connectors/sync.ts';import type { ConnectorSyncDeps } from '../../connectors/sync.ts';import { isConnectorProviderName } from '../../connectors/registry.ts';+import { autoSyncKey, isTruthy } from '../../connectors/config-keys.ts';import type { ConnectorProviderName } from '../../connectors/types.ts';/** 35-minute lock TTL (a shade over the 30-min handler wall budget). */@@ -31,8 +38,14 @@ interface ConnectorSyncJobParams {sourceId: string;full?: boolean;limit?: number;+ maxRequests?: number;+ deadlineSec?: number;+ /** Queued by an explicit `connectors sync <provider> --background`: runs even with auto_sync off. */+ explicit: boolean;}+const positive = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : undefined);+function parseParams(data: Record<string, unknown>): ConnectorSyncJobParams {const provider = typeof data.provider === 'string' ? data.provider : '';if (!isConnectorProviderName(provider)) {@@ -44,6 +57,9 @@ function parseParams(data: Record<string, unknown>): ConnectorSyncJobParams {sourceId,full: data.full === true,limit: typeof data.limit === 'number' ? data.limit : undefined,+ maxRequests: positive(data.maxRequests),+ deadlineSec: positive(data.deadlineSec),+ explicit: data.explicit === true,};}@@ -55,11 +71,16 @@ export function makeConnectorSyncHandler(engine: BrainEngine, deps: ConnectorSynreturn { status: 'already_in_progress', provider: params.provider };}try {+ if (!params.explicit && !isTruthy(await engine.getConfig(autoSyncKey(params.provider)))) {+ return { status: 'skipped', reason: 'auto_sync_off', provider: params.provider };+ }const result = await runConnectorSync(engine, {provider: params.provider,sourceId: params.sourceId,full: params.full,limit: params.limit,+ maxRequests: params.maxRequests,+ deadlineAt: params.deadlineSec !== undefined ? (deps.now ?? Date.now)() + params.deadlineSec * 1000 : undefined,signal: job.signal,onProgress: (p) => {void job.updateProgress({diff --git a/test/connectors-hardening-7515.test.ts b/test/connectors-hardening-7515.test.tsnew file mode 100644index 0000000000..dfadd957e7--- /dev/null+++ b/test/connectors-hardening-7515.test.ts@@ -0,0 +1,481 @@+/**+ * #7515: chat-connector hardening for unattended use with a browser session cookie.+ *+ * 1. Protects:+ * (a) a 403 (JSON body or www-authenticate) ends the run as auth_required and never refreshes and retries;+ * (b) ChatGPT's token refresh goes through the shared client: redirect 'manual', a 30x to another origin is never+ * followed (the cookie never leaves the provider's origin), refresh 403/429/401 surface as+ * forbidden/rate_limited/auth_required, and `connectors auth` does not probe after a failed refresh;+ * (c) auto_sync=false holds for an already-queued connector-sync job and for `connectors sync --all`; only an+ * explicit `connectors sync <provider>` overrides it;+ * (d) a run is bounded: a hard request ceiling (per run, per Claude organization, a Claude organization cap),+ * over-long list pages truncated locally, refresh requests paced and counted, and --max-requests/--deadline.+ * 2. Fails when: any of those paths falls back to refresh-and-retry, raw fetch, an unchecked queue/--all, or an+ * unbounded walk.+ * 3. Everything runs against the real ConnectorClient and providers with fixture servers or injected fetch on PGLite;+ * no real credential and no network. The dummy cookie is never printed.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { withEnv } from './helpers/with-env.ts';+import * as connectorClient from '../src/core/connectors/client.ts';+import { ConnectorAuthError, ConnectorClient, type ConnectorFetch } from '../src/core/connectors/client.ts';+import { runConnectorSync, type ConnectorSyncOpts } from '../src/core/connectors/sync.ts';+import { loadCredential, saveCredential } from '../src/core/connectors/credentials.ts';+import { watermarkKey } from '../src/core/connectors/config-keys.ts';+import { CHATGPT_BASE_URL, chatgptProvider } from '../src/core/connectors/providers/chatgpt.ts';+import * as claudeModule from '../src/core/connectors/providers/claude.ts';+import { CLAUDE_BASE_URL, claudeProvider } from '../src/core/connectors/providers/claude.ts';+import type { ConversationStub } from '../src/core/connectors/types.ts';+import { makeConnectorSyncHandler } from '../src/core/minions/handlers/connector-sync.ts';+import type { MinionJobContext } from '../src/core/minions/types.ts';+import { runConnectorSyncCmd } from '../src/commands/connectors/sync.ts';+import { runConnectorAuth } from '../src/commands/connectors/auth.ts';+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { chatgptHandler, claudeHandler, newFixtureState, startFixture, type FixtureConversation, type FixtureState } from './fixtures/connectors/fixture-server.ts';++const COOKIE = 'sessionKey=dummy-7515';+const T0 = 1_786_000_000;+const NOW_MS = (T0 + 100_000) * 1000;+const realFetch = globalThis.fetch;++let engine: PGLiteEngine;+let home: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ _resetCliExitVerdictForTests();+ await resetPgliteState(engine);+ home = mkdtempSync(join(tmpdir(), 'gbrain-connector-7515-'));+});+afterEach(() => {+ globalThis.fetch = realFetch;+ rmSync(home, { recursive: true, force: true });+ _resetCliExitVerdictForTests();+ process.exitCode = 0;+});++function conversations(n: number): FixtureConversation[] {+ return Array.from({ length: n }, (_, i) => ({+ id: `c-${i}`, title: `Topic ${i}`, createTime: T0 + i - 100, updateTime: T0 + i,+ turns: [{ role: 'user' as const, text: `q${i}` }, { role: 'assistant' as const, text: `a${i}` }],+ }));+}++interface Logged { origin: string; path: string; redirect?: string; at: number }++/** Rewrite each provider origin to its fixture; log every request; refuse anything unrouted (no network). */+function routeTo(map: Record<string, string>, log: Logged[] = [], clock?: { t: number; perRequest?: number }): ConnectorFetch {+ return (url, init) => {+ for (const [from, to] of Object.entries(map)) {+ if (!url.startsWith(from)) continue;+ const u = new URL(url);+ log.push({ origin: from, path: u.pathname + u.search, redirect: init?.redirect, at: clock?.t ?? 0 });+ if (clock?.perRequest) clock.t += clock.perRequest;+ return realFetch(to + url.slice(from.length), init);+ }+ return Promise.reject(new Error('test fetch refused an unrouted URL'));+ };+}++const ENV = {+ GBRAIN_CONNECTOR_CHATGPT_COOKIE: undefined, GBRAIN_CONNECTOR_CHATGPT_TOKEN: undefined,+ GBRAIN_CONNECTOR_CLAUDE_COOKIE: undefined, GBRAIN_CONNECTOR_CLAUDE_TOKEN: undefined,+};++function saveCookie(provider: 'chatgpt' | 'claude'): void {+ saveCredential({ provider, strategy: 'browser-session', cookie: COOKIE, savedAt: new Date(0).toISOString() });+}++async function syncChatgpt(state: FixtureState, opts: Partial<ConnectorSyncOpts> = {}, log: Logged[] = [], clock?: { t: number; perRequest?: number }) {+ const srv = startFixture(chatgptHandler(state));+ try {+ return await withEnv({ GBRAIN_HOME: home, ...ENV }, async () => {+ saveCookie('chatgpt');+ return runConnectorSync(engine, {+ provider: 'chatgpt', sourceId: 'default', ...opts,+ deps: {+ fetchImpl: routeTo({ [CHATGPT_BASE_URL]: srv.baseUrl }, log, clock),+ now: clock ? () => clock.t : () => NOW_MS,+ sleep: clock ? async (ms) => { clock.t += ms; } : () => Promise.resolve(),+ },+ });+ });+ } finally {+ srv.stop();+ }+}++const json = (body: unknown, status = 200, headers: Record<string, string> = {}) =>+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } });++// ── (a) a 403 never refreshes ───────────────────────────────────────────────+describe('#7515 (a) a 403 ends the run without refresh-and-retry', () => {+ for (const [label, response] of [+ ['JSON body', () => json({ error: 'token_expired' }, 403)],+ ['www-authenticate', () => new Response('nope', { status: 403, headers: { 'www-authenticate': 'Bearer' } })],+ ] as const) {+ test(`client: 403 + ${label} → ConnectorAuthError, refresh never called, one request`, async () => {+ let refreshes = 0;+ let calls = 0;+ const client = new ConnectorClient({+ baseUrl: CHATGPT_BASE_URL, headers: async () => ({}), minDelayMs: 0, sleep: async () => {},+ refresh: async () => { refreshes++; return true; },+ fetchImpl: async () => { calls++; return response(); },+ });+ await expect(client.fetchJSON('/backend-api/conversations')).rejects.toBeInstanceOf(ConnectorAuthError);+ expect(refreshes).toBe(0);+ expect(calls).toBe(1);+ });+ }++ test('sync: a 403 JSON on the probe → auth_required, no /api/auth/session request', async () => {+ const state = newFixtureState(conversations(3));+ state.script.push({ pathIncludes: '/backend-api/conversations', status: 403, body: { error: 'token_expired' } });+ const log: Logged[] = [];+ const r = await syncChatgpt(state, {}, log);+ expect(r.status).toBe('auth_required');+ expect(log.filter((l) => l.path.startsWith('/api/auth/session'))).toEqual([]);+ expect(log.length).toBe(1);+ });+});++// ── (b) ChatGPT refresh goes through the shared client ─────────────────────+describe('#7515 (b) ChatGPT token refresh uses the shared client protections', () => {+ test('a refresh 302 to another origin is not followed; the cookie never leaves the origin', async () => {+ const offOrigin = { hits: 0, sawCookie: false };+ const collector = startFixture((req) => {+ offOrigin.hits++;+ if (req.headers.get('cookie')) offOrigin.sawCookie = true;+ return json({ accessToken: 'collected' });+ });+ try {+ const state = newFixtureState(conversations(3));+ state.script.push({ pathIncludes: '/backend-api/conversations', status: 401, body: { error: 'expired' }, onCall: 1 });+ state.script.push({ pathIncludes: '/api/auth/session', status: 302, body: '', headers: { location: `${collector.baseUrl}/collect` } });+ const log: Logged[] = [];+ const r = await syncChatgpt(state, {}, log);+ expect(offOrigin.sawCookie).toBe(false);+ expect(offOrigin.hits).toBe(0);+ const session = log.filter((l) => l.path.startsWith('/api/auth/session'));+ expect(session.length).toBe(1);+ expect(session[0].redirect).toBe('manual');+ expect(r.status).toBe('auth_required');+ expect(log.length).toBe(2);+ expect(JSON.stringify(r)).not.toContain('dummy-7515');+ } finally {+ collector.stop();+ }+ });++ for (const [status, expected, extra] of [+ [403, 'forbidden', { body: 'blocked', contentType: 'text/plain' }],+ [429, 'rate_limited', { body: { error: 'slow down' }, headers: { 'retry-after': '3600' } }],+ [401, 'auth_required', { body: { error: 'expired' } }],+ ] as const) {+ test(`refresh answering ${status} → ${expected}, and no request after it`, async () => {+ const state = newFixtureState(conversations(3));+ state.script.push({ pathIncludes: '/backend-api/conversations', status: 401, body: { error: 'expired' }, onCall: 1 });+ state.script.push({ pathIncludes: '/api/auth/session', status, ...extra });+ const log: Logged[] = [];+ const r = await syncChatgpt(state, {}, log);+ expect(r.status).toBe(expected);+ expect(log.map((l) => l.path.split('?')[0])).toEqual(['/backend-api/conversations', '/api/auth/session']);+ });+ }++ test('connectors auth stops after a failed refresh: no probe, nothing saved, exit 1', async () => {+ const state = newFixtureState(conversations(1));+ state.script.push({ pathIncludes: '/api/auth/session', status: 403, body: 'blocked', contentType: 'text/plain' });+ const srv = startFixture(chatgptHandler(state));+ const log: Logged[] = [];+ globalThis.fetch = routeTo({ [CHATGPT_BASE_URL]: srv.baseUrl }, log) as unknown as typeof fetch;+ const errors: string[] = [];+ const prevError = console.error;+ const prevLog = console.log;+ console.error = (...p: unknown[]) => { errors.push(p.join(' ')); };+ console.log = () => {};+ try {+ await withEnv({ GBRAIN_HOME: home, ...ENV }, async () => {+ await runConnectorAuth(engine, ['chatgpt', '--cookie', COOKIE]);+ expect(loadCredential('chatgpt')).toBeNull();+ });+ } finally {+ console.error = prevError;+ console.log = prevLog;+ globalThis.fetch = realFetch;+ srv.stop();+ }+ expect(log.map((l) => l.path.split('?')[0])).toEqual(['/api/auth/session']);+ expect(currentExitCode()).toBe(1);+ expect(errors.join(' ')).not.toContain('dummy-7515');+ });+});++// ── (c) auto_sync=false is enforced where jobs run ─────────────────────────+function fakeJob(data: Record<string, unknown>): MinionJobContext {+ return {+ id: 1, name: 'connector-sync', data, attempts_made: 0,+ signal: new AbortController().signal, shutdownSignal: new AbortController().signal, deadlineAtMs: null,+ updateProgress: async () => {}, updateTokens: async () => {}, log: async () => {},+ isActive: async () => true, readInbox: async () => [],+ } as unknown as MinionJobContext;+}++describe('#7515 (c) auto_sync=false holds for queued jobs and --all', () => {+ test('a queued connector-sync job with auto_sync off does nothing; an explicit one runs', async () => {+ const state = newFixtureState(conversations(2));+ const srv = startFixture(chatgptHandler(state));+ const log: Logged[] = [];+ try {+ await withEnv({ GBRAIN_HOME: home, ...ENV }, async () => {+ saveCookie('chatgpt');+ const handler = makeConnectorSyncHandler(engine, {+ fetchImpl: routeTo({ [CHATGPT_BASE_URL]: srv.baseUrl }, log), now: () => NOW_MS, sleep: () => Promise.resolve(),+ });+ const unset = (await handler(fakeJob({ provider: 'chatgpt', sourceId: 'default' }))) as { status: string };+ expect(unset.status).toBe('skipped');+ await engine.setConfig('connectors.chatgpt.auto_sync', 'false');+ const off = (await handler(fakeJob({ provider: 'chatgpt', sourceId: 'default' }))) as { status: string };+ expect(off.status).toBe('skipped');+ expect(log).toEqual([]);+ const explicit = (await handler(fakeJob({ provider: 'chatgpt', sourceId: 'default', explicit: true }))) as { status: string };+ expect(explicit.status).not.toBe('skipped');+ expect(log.length).toBeGreaterThan(0);+ });+ } finally {+ srv.stop();+ }+ });++ async function cli(args: string[]): Promise<{ chatgpt: number; claude: number }> {+ const gpt = startFixture(chatgptHandler(newFixtureState(conversations(1))));+ const cl = startFixture(claudeHandler(newFixtureState(conversations(1))));+ const log: Logged[] = [];+ globalThis.fetch = routeTo({ [CHATGPT_BASE_URL]: gpt.baseUrl, [CLAUDE_BASE_URL]: cl.baseUrl }, log) as unknown as typeof fetch;+ const prevError = console.error;+ const prevLog = console.log;+ console.error = () => {};+ console.log = () => {};+ try {+ await withEnv({ GBRAIN_HOME: home, ...ENV }, async () => {+ saveCookie('chatgpt');+ saveCookie('claude');+ await engine.setConfig('connectors.claude.auto_sync', 'true');+ await runConnectorSyncCmd(engine, args);+ });+ } finally {+ console.error = prevError;+ console.log = prevLog;+ globalThis.fetch = realFetch;+ gpt.stop();+ cl.stop();+ }+ return { chatgpt: log.filter((l) => l.origin === CHATGPT_BASE_URL).length, claude: log.filter((l) => l.origin === CLAUDE_BASE_URL).length };+ }++ test('connectors sync --all skips a provider whose auto_sync is off', async () => {+ const hits = await cli(['--all', '--dry-run']);+ expect(hits.chatgpt).toBe(0);+ expect(hits.claude).toBeGreaterThan(0);+ }, 30_000);++ test('an explicit connectors sync <provider> still syncs with auto_sync off', async () => {+ const hits = await cli(['chatgpt', '--dry-run']);+ expect(hits.chatgpt).toBeGreaterThan(0);+ expect(hits.claude).toBe(0);+ }, 30_000);+});++// ── (d) an overall bound ────────────────────────────────────────────────────+describe('#7515 (d) a run is bounded', () => {+ const okClient = (opts: Record<string, unknown>, onCall?: () => void) => new ConnectorClient({+ baseUrl: CHATGPT_BASE_URL, headers: async () => ({}), minDelayMs: 0, sleep: async () => {},+ fetchImpl: async () => { onCall?.(); return json({ items: [] }); },+ ...opts,+ } as never);++ test('client: --max-requests stops before the next request with a run-limit error', async () => {+ let calls = 0;+ const client = okClient({ maxRequests: 3 }, () => { calls++; });+ for (let i = 0; i < 3; i++) await client.fetchJSON('/x');+ const e = await client.fetchJSON('/x').then(() => null, (err: unknown) => err) as { name?: string; reason?: string } | null;+ expect(e?.name).toBe('ConnectorRunLimitError');+ expect(e?.reason).toBe('max_requests');+ expect(calls).toBe(3);+ });++ test('client: the hard ceiling holds by default and caps a larger --max-requests', async () => {+ const ceiling = (connectorClient as Record<string, unknown>).MAX_CONNECTOR_REQUESTS_PER_RUN as number;+ expect(ceiling).toBe(10_000);+ for (const opts of [{}, { maxRequests: ceiling * 10 }]) {+ let calls = 0;+ const client = okClient(opts, () => { calls++; });+ for (let i = 0; i < ceiling; i++) await client.fetchJSON('/x');+ await expect(client.fetchJSON('/x')).rejects.toMatchObject({ name: 'ConnectorRunLimitError', reason: 'max_requests' });+ expect(calls).toBe(ceiling);+ }+ });++ test('client: a deadline stops before the next request and before a Retry-After wait that would pass it', async () => {+ const clock = { t: NOW_MS };+ let calls = 0;+ const client = okClient({ now: () => clock.t, deadlineAt: NOW_MS + 2_500 }, () => { calls++; clock.t += 1_000; });+ for (let i = 0; i < 3; i++) await client.fetchJSON('/x');+ await expect(client.fetchJSON('/x')).rejects.toMatchObject({ name: 'ConnectorRunLimitError', reason: 'deadline' });+ expect(calls).toBe(3);++ const sleeps: number[] = [];+ const limited = new ConnectorClient({+ baseUrl: CHATGPT_BASE_URL, headers: async () => ({}), minDelayMs: 0, now: () => NOW_MS, deadlineAt: NOW_MS + 10_000,+ sleep: async (ms: number) => { sleeps.push(ms); }, fetchImpl: async () => json({ error: 'slow down' }, 429, { 'retry-after': '60' }),+ } as never);+ await expect(limited.fetchJSON('/x')).rejects.toMatchObject({ name: 'ConnectorRunLimitError', reason: 'deadline' });+ expect(sleeps).toEqual([]);+ });++ test('sync --full stops at --max-requests: partial with stopReason max_requests, no watermark, no strikes', async () => {+ const state = newFixtureState(conversations(12));+ const log: Logged[] = [];+ const r = await syncChatgpt(state, { full: true, maxRequests: 6 } as Partial<ConnectorSyncOpts>, log);+ expect(r.status).toBe('partial');+ expect(r.stopReason as string).toBe('max_requests');+ expect(log.length).toBe(6);+ expect(r.hint).toMatch(/request/i);+ expect(r.quarantined).toEqual([]);+ expect(await engine.getConfig(watermarkKey('chatgpt', 'default'))).toBeNull();+ });++ test('sync stops at --deadline: partial with stopReason deadline; no request starts after it', async () => {+ const state = newFixtureState(conversations(12));+ const log: Logged[] = [];+ const clock = { t: NOW_MS, perRequest: 1_000 };+ const deadlineAt = NOW_MS + 8_000;+ const r = await syncChatgpt(state, { full: true, deadlineAt } as Partial<ConnectorSyncOpts>, log, clock);+ expect(r.status).toBe('partial');+ expect(r.stopReason as string).toBe('deadline');+ expect(log.length).toBeGreaterThan(0);+ expect(log.length).toBeLessThan(15);+ expect(log.every((l) => l.at < deadlineAt)).toBe(true);+ });++ test('a refresh request is paced like any other request', async () => {+ const state = newFixtureState(conversations(1));+ state.script.push({ pathIncludes: '/backend-api/conversations', status: 401, body: { error: 'expired' }, onCall: 1 });+ const log: Logged[] = [];+ const clock = { t: NOW_MS };+ await syncChatgpt(state, {}, log, clock);+ const [first, session] = log;+ expect(session.path).toBe('/api/auth/session');+ expect(session.at - first.at).toBeGreaterThanOrEqual(700);+ });++ async function collect(gen: AsyncGenerator<ConversationStub>): Promise<ConversationStub[]> {+ const out: ConversationStub[] = [];+ for await (const s of gen) out.push(s);+ return out;+ }++ function fakeClient(baseUrl: string, handler: (url: URL) => Response, seen: string[]): ConnectorClient {+ return new ConnectorClient({+ baseUrl, headers: async () => ({}), minDelayMs: 0, sleep: () => Promise.resolve(),+ fetchImpl: async (input: string) => { const u = new URL(input); seen.push(u.pathname + u.search); return handler(u); },+ });+ }++ const offsetOf = (p: string) => new URL(`http://x${p}`).searchParams.get('offset');++ test('chatgpt: an over-long list page is truncated to the page limit and the walk continues from there', async () => {+ const all = Array.from({ length: 100 }, (_, i) => ({ id: `g-${i}`, title: `t${i}`, update_time: T0 - i }));+ const seen: string[] = [];+ const client = fakeClient(CHATGPT_BASE_URL, (u) => {+ if (u.searchParams.get('is_archived')) return json({ items: [], total: 0 });+ return json({ items: all.slice(Number(u.searchParams.get('offset'))), total: all.length });+ }, seen);+ const stubs = await collect(chatgptProvider.listConversations(client));+ expect(stubs.map((s) => s.id)).toEqual(all.map((a) => a.id));+ expect(seen.filter((p) => !p.includes('is_archived')).map(offsetOf)).toEqual(['0', '28', '56', '84']);+ });++ test('chatgpt: an over-long page that ignores offset is drift, never a silently truncated list', async () => {+ const all = Array.from({ length: 100 }, (_, i) => ({ id: `g-${i}`, title: `t${i}`, update_time: T0 - i }));+ const client = fakeClient(CHATGPT_BASE_URL, () => json({ items: all, total: all.length }), []);+ await expect(collect(chatgptProvider.listConversations(client))).rejects.toThrow(/truncated|offset/i);+ });++ test('claude: an over-long page is truncated; an endpoint that ignores offset after it is drift', async () => {+ const rows = Array.from({ length: 150 }, (_, i) => ({ uuid: `u-${i}`, name: `n${i}`, updated_at: new Date((T0 - i) * 1000).toISOString() }));+ const seen: string[] = [];+ const honoring = fakeClient(CLAUDE_BASE_URL, (u) => {+ if (u.pathname === '/api/organizations') return json([{ uuid: 'org-a' }]);+ return json(rows.slice(Number(u.searchParams.get('offset') ?? '0')));+ }, seen);+ const stubs = await collect(claudeProvider.listConversations(honoring));+ expect(stubs.length).toBe(150);+ expect(seen.filter((p) => p.includes('chat_conversations')).map(offsetOf)).toEqual(['0', '100', '150']);++ const ignoring = fakeClient(CLAUDE_BASE_URL, (u) => (u.pathname === '/api/organizations' ? json([{ uuid: 'org-a' }]) : json(rows)), []);+ await expect(collect(claudeProvider.listConversations(ignoring))).rejects.toThrow(/truncated|offset/i);+ });++ test('claude: only the first CLAUDE_MAX_ORGS organizations are listed, and the listing is not treated as complete', async () => {+ const maxOrgs = (claudeModule as Record<string, unknown>).CLAUDE_MAX_ORGS as number;+ expect(maxOrgs).toBe(10);+ const orgs = Array.from({ length: maxOrgs + 5 }, (_, i) => ({ uuid: `org-${i}` }));+ const seen: string[] = [];+ const client = fakeClient(CLAUDE_BASE_URL, (u) => {+ if (u.pathname === '/api/organizations') return json(orgs);+ const org = u.pathname.split('/')[3];+ return json(Number(u.searchParams.get('offset') ?? '0') === 0 ? [{ uuid: `${org}-c`, name: 'x', updated_at: new Date(T0 * 1000).toISOString() }] : []);+ }, seen);+ await expect(collect(claudeProvider.listConversations(client))).rejects.toThrow(/organization/i);+ const listedOrgs = new Set(seen.filter((p) => p.includes('chat_conversations')).map((p) => p.split('/')[3]));+ expect(listedOrgs.size).toBe(maxOrgs);+ });++ test('claude: requests to one organization stop at CLAUDE_MAX_REQUESTS_PER_ORG', async () => {+ const perOrg = (claudeModule as Record<string, unknown>).CLAUDE_MAX_REQUESTS_PER_ORG as number;+ expect(perOrg).toBe(5_000);+ const seen: string[] = [];+ const client = fakeClient(CLAUDE_BASE_URL, (u) => json({ uuid: u.pathname.split('/').pop(), chat_messages: [] }), seen);+ for (let i = 0; i < perOrg; i++) await claudeProvider.fetchConversation(client, `c-${i}`, { orgId: 'org-a' });+ await expect(claudeProvider.fetchConversation(client, 'c-over', { orgId: 'org-a' })).rejects.toMatchObject({ name: 'ConnectorRunLimitError', reason: 'max_requests' });+ expect(seen.length).toBe(perOrg);+ });++ test('CLI: --max-requests and --deadline are validated (invalid_params) and accepted when valid', async () => {+ for (const args of [+ ['chatgpt', '--max-requests', '0'],+ ['chatgpt', '--max-requests', 'many'],+ ['chatgpt', '--max-requests', '10001'],+ ['chatgpt', '--max-requests'],+ ['chatgpt', '--deadline', 'soon'],+ ['chatgpt', '--deadline', '0'],+ ['chatgpt', '--deadline'],+ ]) {+ const e = await runConnectorSyncCmd({ getConfig: async () => null } as never, args).then(() => null, (err: unknown) => err);+ expect(e).toBeInstanceOf(OperationError);+ expect((e as OperationError).code).toBe('invalid_params');+ expect((e as OperationError).message).toContain(args[1]);+ }+ const prevError = console.error;+ console.error = () => {};+ try {+ await withEnv({ GBRAIN_HOME: home, ...ENV }, async () => {+ await expect(runConnectorSyncCmd({ getConfig: async () => null } as never, ['chatgpt', '--max-requests', '50', '--deadline', '30m'])).resolves.toBeUndefined();+ });+ } finally {+ console.error = prevError;+ }+ });+});diff --git a/test/e2e/connector-sync-handler-pglite.test.ts b/test/e2e/connector-sync-handler-pglite.test.tsindex 05df411533..aa309312f4 100644--- a/test/e2e/connector-sync-handler-pglite.test.ts+++ b/test/e2e/connector-sync-handler-pglite.test.ts@@ -61,6 +61,8 @@ describe('connector-sync handler', () => {});test('no credential → returns auth_required (NOT thrown), releases the lock', async () => {+ // #7515: a scheduled job runs only while auto_sync is on (test/connectors-hardening-7515.test.ts pins the skip).+ await engine.setConfig('connectors.chatgpt.auto_sync', 'true');const handler = makeConnectorSyncHandler(engine);const r = (await handler(fakeJob({ provider: 'chatgpt', sourceId: 'default' }))) as { status: string };expect(r.status).toBe('auth_required');