Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
google: report an unreadable calendar instead of an empty one (#5012 item 9)
garrytana76e7b5ee1c7
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex a763f639b9..bc5c015219 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -358,6 +358,16 @@ More: [docs/guides/dream-patterns.md#budget-sizing](../../docs/guides/dream-pattMore: [docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover](../../docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover)+### calendar_unreadable++<a id="calendar_unreadable"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A Google source's configured calendar returned HTTP 403 or 404 to its account, so its sync imports no events. | Without the typed result an unreadable calendar looks exactly like an empty one. The calendar sweep records it in the source's connector state (the run is not failed); `gbrain doctor` (google_calendar_readable) reads it with no network call and `gbrain google status` probes it live. | List the calendars the account can read with `gbrain google calendars --account <email>`, then point the source at one with `gbrain sources set-calendar <source> <calendar-id>` and run `gbrain sync --source <source>`. Run: gbrain google calendars --json | agent | `gbrain doctor --only google_calendar_readable --json` | 1 | no |++More: [docs/guides/google-connect.md#unreadable-calendar](../../docs/guides/google-connect.md#unreadable-calendar)+### cancelled<a id="cancelled"></a>diff --git a/src/commands/doctor/checks/google-calendar.ts b/src/commands/doctor/checks/google-calendar.tsnew file mode 100644index 0000000000..f7365dc48c--- /dev/null+++ b/src/commands/doctor/checks/google-calendar.ts@@ -0,0 +1,46 @@+import type { BrainEngine } from '../../../core/engine.ts';+import type { Check } from '../../doctor.ts';+import { readConnectorCursorState, type ConnectorSourceRow } from '../../../core/connectors/item-holds-store.ts';+import { parseGoogleSourceConfig } from '../../../core/google/source-config.ts';+import type { CalendarUnreadable } from '../../../core/google/types.ts';+import { calendarUnreadableFix } from '../../google-calendar-status.ts';+import { agentFix } from '../check-fix.ts';++/**+ * #5012 item 9: Google sources whose last calendar sweep could not read the+ * configured calendar (403/404 recorded as `calendar_unreadable` in connector+ * state). Zero-network: it reads the stored result only; `gbrain google+ * status` probes the calendar live. Without it an unreadable calendar looks+ * exactly like an empty one.+ */+export async function googleCalendarReadableCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {+ try {+ const rows = await engine.executeRaw<ConnectorSourceRow>(+ "SELECT id, incarnation::text AS incarnation, local_path, config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' = 'google' ORDER BY id");+ const unreadable = [];+ for (const row of rows) {+ if (sourceIds && !sourceIds.includes(row.id)) continue;+ const cfg = parseGoogleSourceConfig(row.config, '');+ if (!cfg.services.includes('calendar')) continue;+ const stored = (await readConnectorCursorState(engine, row))?.calendar_unreadable as CalendarUnreadable | null | undefined;+ if (!stored || stored.calendar_id !== cfg.calendarId) continue;+ unreadable.push({ source_id: row.id, account: cfg.account, calendar_id: cfg.calendarId, http_status: stored.http_status, at: stored.at,+ ...calendarUnreadableFix(cfg.account, row.id) });+ }+ const details = { code: unreadable.length ? 'calendar_unreadable' : undefined, count: unreadable.length, sources: unreadable,+ docs: 'docs/guides/google-connect.md#unreadable-calendar' };+ if (!unreadable.length) return { name: 'google_calendar_readable', status: 'ok', message: 'Every Google source calendar was readable at its last sync.', details };+ const first = unreadable[0]!;+ return {+ name: 'google_calendar_readable', status: 'warn', details,+ message: unreadable.map((u) => `Google source ${u.source_id}: ${u.account} cannot read calendar "${u.calendar_id}" (HTTP ${u.http_status} at the last sync), `+ + `so it imports no events. List the readable calendars with ${u.list_command}, then run ${u.set_command}.`).join(' '),+ fix: agentFix(['gbrain', 'google', 'calendars', '--account', first.account, '--json'],+ 'Read-only: lists the calendar ids this account can read; pick one and point the source at it with gbrain sources set-calendar.',+ 'google_calendar_readable', { docs: 'docs/guides/google-connect.md#unreadable-calendar' }),+ };+ } catch (error) {+ return { name: 'google_calendar_readable', status: 'warn', fix_unavailable_reason: 'check_errored', details: { count: 'unknown' },+ message: `Google calendar readability could not be read from source state: ${error instanceof Error ? error.message : String(error)}. Health is unknown.` };+ }+}diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.tsindex ee1d51e914..d8520be95d 100644--- a/src/commands/doctor/checks/graph-health.ts+++ b/src/commands/doctor/checks/graph-health.ts@@ -342,6 +342,7 @@ export const timelineHistoryEntry: DoctorEntry = {'keyword_plan','stale_embedding_effects','google_file_modes',+ 'google_calendar_readable','extractor_facts_expired','conversation_label_facts','conversation_outcomes_stale',diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.tsindex 2c438a4620..bd277dc181 100644--- a/src/commands/doctor/wave-checks.ts+++ b/src/commands/doctor/wave-checks.ts@@ -277,6 +277,14 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [impact: 'Some files gbrain wrote under a Google source directory outside ~/.gbrain are readable by other local users',run: async (engine, scope) => (await import('./checks/google-file-modes.ts')).checkGoogleFileModes(engine, scope.sourceIds),},+ {+ id: 'google_calendar_readable', resolution: 'operator', registration: 'wave',+ hostOnly: 'Connector state and the account address live on the brain host.',+ count: d => Number(d.count ?? 0),+ impact: 'A Google source is configured with a calendar its account cannot read, so it imports no events',+ instruction: 'List the readable calendars with `gbrain google calendars --account <email>`, then `gbrain sources set-calendar <source> <calendar-id>` and `gbrain sync --source <source>` (docs/guides/google-connect.md#unreadable-calendar).',+ run: async (engine, scope) => (await import('./checks/google-calendar.ts')).googleCalendarReadableCheck(engine, scope.sourceIds),+ },{id: 'atom_provenance_drift', resolution: 'repair', registration: 'doctor.ts',hostOnly: 'Retiring stale atoms is a host-side, explicit-only repair.',diff --git a/src/commands/google-calendar-status.ts b/src/commands/google-calendar-status.tsnew file mode 100644index 0000000000..b2c6ea1cbe--- /dev/null+++ b/src/commands/google-calendar-status.ts@@ -0,0 +1,48 @@+/**+ * #5012 item 9: calendar readability per linked Google source, for+ * `gbrain google status`. With a probe (the default) each source that syncs+ * Calendar gets one live `events.list` read of its configured calendar; with+ * `--no-probe` the result its last sweep recorded (`calendar_unreadable` in+ * connector state) is reported instead. A 403 or 404 is `calendar_unreadable`+ * with the commands that list readable calendars and change the source's+ * calendar id.+ */+import type { BrainEngine } from '../core/engine.ts';+import { readConnectorCursorState, type ConnectorSourceRow } from '../core/connectors/item-holds-store.ts';+import { parseGoogleSourceConfig } from '../core/google/source-config.ts';+import type { CalendarUnreadable } from '../core/google/types.ts';++export interface CalendarReadability {+ calendar_id: string;+ readable: boolean | null;+ checked: 'live' | 'last_sync';+ code?: 'calendar_unreadable';+ http_status?: 403 | 404;+ error?: string;+ fix?: { list_command: string; set_command: string };+}++export type CalendarProbe = (account: string, calendarId: string) => Promise<{ readable: true } | { readable: false; httpStatus: 403 | 404 }>;++export function calendarUnreadableFix(account: string, sourceId: string): { list_command: string; set_command: string } {+ return { list_command: `gbrain google calendars --account ${account}`, set_command: `gbrain sources set-calendar ${sourceId} <calendar-id>` };+}++/** Readability of one source's calendar, or null when the source does not sync Calendar. */+export async function sourceCalendarReadability(engine: BrainEngine, source: ConnectorSourceRow, probe: CalendarProbe | null): Promise<CalendarReadability | null> {+ const cfg = parseGoogleSourceConfig(source.config, '');+ if (!cfg.services.includes('calendar')) return null;+ const unreadable = (httpStatus: 403 | 404, checked: CalendarReadability['checked']): CalendarReadability => ({+ calendar_id: cfg.calendarId, readable: false, checked, code: 'calendar_unreadable', http_status: httpStatus, fix: calendarUnreadableFix(cfg.account, source.id) });+ if (probe) {+ try {+ const result = await probe(cfg.account, cfg.calendarId);+ return result.readable ? { calendar_id: cfg.calendarId, readable: true, checked: 'live' } : unreadable(result.httpStatus, 'live');+ } catch (e) {+ return { calendar_id: cfg.calendarId, readable: null, checked: 'live', error: e instanceof Error ? e.message : String(e) };+ }+ }+ const stored = (await readConnectorCursorState(engine, source))?.calendar_unreadable as CalendarUnreadable | null | undefined;+ if (stored && stored.calendar_id === cfg.calendarId) return unreadable(stored.http_status, 'last_sync');+ return { calendar_id: cfg.calendarId, readable: stored === null ? true : null, checked: 'last_sync' };+}diff --git a/src/commands/google.ts b/src/commands/google.tsindex 4e56f6908a..4cc1e0f36b 100644--- a/src/commands/google.ts+++ b/src/commands/google.ts@@ -59,6 +59,7 @@ import { setCliExitVerdict } from '../core/cli-force-exit.ts';// ── Shared bits ──────────────────────────────────────────────────────────────import { ALL_GOOGLE_SERVICES, type GoogleService } from '../core/google/types.ts';+import { sourceCalendarReadability, type CalendarProbe, type CalendarReadability } from './google-calendar-status.ts';export const GOOGLE_SERVICES = ALL_GOOGLE_SERVICES;export type { GoogleService };@@ -673,8 +674,9 @@ export async function runGoogleStatus(args: string[]): Promise<void> {accounts.push(row);}- // Linked sources: best-effort, engine optional.- let linkedSources: Array<{ id: string; account: string | null }> = [];+ // Linked sources: best-effort, engine optional. #5012 item 9: each one that+ // syncs Calendar reports whether its configured calendar is readable.+ let linkedSources: Array<{ id: string; account: string | null; calendar?: CalendarReadability }> = [];try {const { loadConfig, toEngineConfig } = await import('../core/config.ts');const cfg = loadConfig();@@ -684,21 +686,25 @@ export async function runGoogleStatus(args: string[]): Promise<void> {const engine = await createEngine(engineConfig);await engine.connect(engineConfig);try {- const rows = await engine.executeRaw<{ id: string; config: unknown }>(- `SELECT id, config FROM sources WHERE archived IS NOT TRUE`,+ const rows = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null; config: unknown }>(+ `SELECT id, incarnation::text AS incarnation, local_path, config FROM sources WHERE archived IS NOT TRUE`,[],);- linkedSources = rows- .map((r) => {- const c =- typeof r.config === 'string'- ? (JSON.parse(r.config) as Record<string, unknown>)- : ((r.config ?? {}) as Record<string, unknown>);- return c.kind === 'google'- ? { id: r.id, account: typeof c.g_account === 'string' ? c.g_account : null }- : null;- })- .filter((x): x is { id: string; account: string | null } => x !== null);+ const calendarProbe: CalendarProbe | null = probe ? async (account, calendarId) => {+ const entry = await vault.get(credentialId(GOOGLE_PROVIDER, account));+ if (!entry) throw new CredentialError('not_connected', ` for ${account}`);+ const { CalendarClient } = await import('../core/google/google-clients.ts');+ return new CalendarClient(new GoogleTokenProvider(vault, entry.id, fetch), fetch, () => {}, entry.meta.client_id).probeCalendar(calendarId);+ } : null;+ for (const r of rows) {+ const c =+ typeof r.config === 'string'+ ? (JSON.parse(r.config) as Record<string, unknown>)+ : ((r.config ?? {}) as Record<string, unknown>);+ if (c.kind !== 'google') continue;+ const calendar = await sourceCalendarReadability(engine, { ...r, config: c }, calendarProbe).catch(() => null);+ linkedSources.push({ id: r.id, account: typeof c.g_account === 'string' ? c.g_account : null, ...(calendar ? { calendar } : {}) });+ }} finally {await engine.disconnect();}@@ -707,11 +713,13 @@ export async function runGoogleStatus(args: string[]): Promise<void> {/* no engine — vault-only status */}+ const unreadableCalendars = linkedSources.filter((s) => s.calendar?.code === 'calendar_unreadable');+ if (unreadableCalendars.length > 0) setCliExitVerdict(1);if (json) {process.stdout.write(JSON.stringify({- ok: true,+ ok: unreadableCalendars.length === 0,status: accounts.length > 0 ? 'connected' : 'not_connected',client_on_file: client !== null,accounts,@@ -747,6 +755,12 @@ export async function runGoogleStatus(args: string[]): Promise<void> {process.stdout.write(`Linked sources: ${linkedSources.map((s) => s.id).join(', ')}\n`,);+ for (const s of unreadableCalendars) {+ const cal = s.calendar!;+ process.stdout.write(` ${s.id}: calendar_unreadable — ${s.account ?? 'this account'} cannot read calendar "${cal.calendar_id}" `+ + `(HTTP ${cal.http_status}, ${cal.checked === 'live' ? 'checked now' : 'at the last sync'}); its sync imports no events.\n`+ + ` List readable calendars: ${cal.fix!.list_command}\n Change the source's calendar: ${cal.fix!.set_command}\n`);+ }} else {process.stdout.write('Linked sources: none yet — `gbrain sources add <id> --kind google --account <email>`\n');}@@ -809,7 +823,9 @@ Subcommands:--history-days <n> backfill window for the source (default 90)--sync-budget-ms <ms> first-sync wall-clock budget(+ all connect flags above)- status accounts, scopes, refresh probe, linked sources [--json] [--no-probe]+ status accounts, scopes, refresh probe, linked sources and whether each+ source's calendar is readable [--json] [--no-probe]+ (--no-probe: no network; reports the last sync's calendar result)attachments backfill --source <id> [--yes] [--limit 1-25] [--retry-failed] [--json]bounded metadata-only repair of imported Gmail; managed persistence requiredSee docs/guides/google-connect.md#attachment-receipts-and-historical-repairdiff --git a/src/commands/sources-set-calendar.ts b/src/commands/sources-set-calendar.tsnew file mode 100644index 0000000000..0077bb3b97--- /dev/null+++ b/src/commands/sources-set-calendar.ts@@ -0,0 +1,53 @@+/**+ * `gbrain sources set-calendar <source> <calendar-id> [--yes]` (#5012 item 9):+ * points a Google source's calendar sweep at another calendar+ * (`sources.config.g_calendar_id`; `primary` is the account's own). It is the+ * fix `calendar_unreadable` names: `gbrain google calendars` lists the ids+ * the account can read. The write is updateSourceConfig's single-key merge.+ *+ * The next sweep discards the old calendar's sync token and lists the new+ * calendar from a fresh window; pages already imported from the old calendar+ * stay. On a managed brain the connector cursor is keyed by the source's+ * configuration, so a source that also syncs Gmail or Contacts re-reads their+ * history on its next sync; that needs `--yes` (exit 3 without it).+ */+import type { BrainEngine } from '../core/engine.ts';+import { exitCliError, usageError } from '../cli/cli-error.ts';+import { opError } from '../core/ops/contract.ts';+import { parseSourceConfig } from '../core/sources-load.ts';+import { parseGoogleSourceConfig } from '../core/google/source-config.ts';+import { readManagedMode } from '../core/persistence/managed-mode.ts';++const CALENDAR_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._%+#@-]{0,253}$/;++export async function runSetCalendar(engine: BrainEngine, args: string[]): Promise<void> {+ const [id, calendarId] = args.filter((a) => !a.startsWith('--'));+ const usage = 'Usage: gbrain sources set-calendar <source> <calendar-id> [--yes]. List the calendar ids the account can read with: gbrain google calendars';+ if (!id || !calendarId) exitCliError(usageError('gbrain sources set-calendar needs a source id and a calendar id.', usage), 'sources');+ if (!CALENDAR_ID_RE.test(calendarId!)) exitCliError(usageError(`"${calendarId}" is not a Google calendar id.`, usage), 'sources');+ const [src] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1 AND archived IS NOT TRUE', [id]);+ if (!src) {+ console.error(`Source "${id}" not found. List sources with: gbrain sources list`);+ process.exit(4);+ }+ const config = parseSourceConfig(src!.config);+ if (config.kind !== 'google') {+ exitCliError(usageError(`Source "${id}" is not a Google source; only a Google source has a calendar.`, 'List sources and their kind with: gbrain sources list'), 'sources');+ }+ const google = parseGoogleSourceConfig(config, '');+ if (google.calendarId === calendarId) {+ console.log(`Source "${id}" already syncs calendar ${calendarId}.`);+ return;+ }+ const others = google.services.filter((s) => s !== 'calendar');+ if (others.length > 0 && !args.includes('--yes') && await readManagedMode(engine)) {+ exitCliError(opError('confirmation_required', `Changing the calendar of "${id}" makes its next sync re-read ${others.join(' and ')} history from the start.`,+ `On this managed brain the source's sync cursor is keyed by its configuration, so the change starts a fresh cursor for every service the source syncs (${google.services.join(', ')}); pages already imported stay. With the user's agreement, run gbrain sources set-calendar ${id} ${calendarId} --yes.`, {+ fix: { argv: ['gbrain', 'sources', 'set-calendar', id!, calendarId!, '--yes'], consent: [], actor: 'agent', why: 'Points the source at the new calendar after the user agrees to the re-read.', requires_exclusive: false,+ ask_user: true, user_message: `Point ${id} at calendar ${calendarId}? Its next sync re-reads ${others.join(' and ')} history (no cost; already imported pages stay).` },+ }), 'sources');+ }+ await engine.updateSourceConfig(id!, { g_calendar_id: calendarId });+ console.log(`Source "${id}" now syncs calendar ${calendarId} (was ${google.calendarId}).`);+ console.log(` The next sync lists it from a fresh window; pages from the old calendar stay. Run it now: gbrain sync --source ${id}`);+}diff --git a/src/commands/sources.ts b/src/commands/sources.tsindex 0f772e6cd2..a2e8618dbd 100644--- a/src/commands/sources.ts+++ b/src/commands/sources.ts@@ -1908,6 +1908,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<vcase 'tracked-branch': return runTrackedBranch(engine, rest);// v0.40.3.0 contextual retrieval (from master)case 'set-cr-mode': return runSetCrMode(engine, rest);+ case 'set-calendar': return (await import('./sources-set-calendar.ts')).runSetCalendar(engine, rest);case 'set-trust': { const { runSetTrust } = await import('./sources-trust.ts'); return runSetTrust(engine, rest); }// #4739 non-destructive local_path pointer repaircase 'set-path': { const { runSetPath } = await import('./sources-set-path.ts'); return runSetPath(engine, rest); }@@ -1994,6 +1995,7 @@ Subcommands:override (v0.40.3.0). Pass "unset" or"default" to clear (NULL falls throughto the global search.mode bundle).+ set-calendar <id> <calendar-id> [--yes] Point a Google source at another calendar (ids: gbrain google calendars).set-trust <id> <tier>|--clear Trust default for this source's sync and import (operator_curated or lower).set-path <id> <path> [--force] Repair a source's local_path pointer(DB column only, never touches disk).diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 85ba5b7973..9e46201a00 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -259,6 +259,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set(['db_only_collector_collision','federation_health','google_file_modes',+ // #5012 item 9: a Google source's configured calendar was unreadable at its last sync (doctor/checks/google-calendar.ts).+ 'google_calendar_readable','google_oauth','home_dir_in_worktree','index_audit',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 01178a9914..440e747338 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -84,6 +84,7 @@ export const CODES = {bucket_not_found: { class: 'unavailable', summary: "The configured storage bucket does not exist." },budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },cache_quota_exceeded: { class: 'caller', summary: "Retained shared-skill revisions reached this installation's local cache quota.", docs: 'docs/guides/shared-brain-skills.md#troubleshoot-leave-and-recover' },+ calendar_unreadable: { class: 'caller', summary: "A Google source's configured calendar returned HTTP 403 or 404 to its account, so its sync imports no events.", why: "Without the typed result an unreadable calendar looks exactly like an empty one. The calendar sweep records it in the source's connector state (the run is not failed); `gbrain doctor` (google_calendar_readable) reads it with no network call and `gbrain google status` probes it live.", docs: 'docs/guides/google-connect.md#unreadable-calendar', suggestion: 'List the calendars the account can read with `gbrain google calendars --account <email>`, then point the source at one with `gbrain sources set-calendar <source> <calendar-id>` and run `gbrain sync --source <source>`.', fix: { argv: ['gbrain', 'google', 'calendars', '--json'], consent: [], actor: 'agent', why: 'Read-only: lists the calendar ids the connected account can read.', requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'google_calendar_readable', '--json'] } } },cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },capacity_paused: { class: 'host_only', retryable: false, reasons: ['lifetime_ids', 'terminal_bytes'],summary: "A managed sync passed its capacity preflight, then a cumulative write cap (or the background pause line) refused its next admission, so the drain stopped resumable with its cursor and accepted writes intact; nothing failed.",diff --git a/src/core/google/people-calendar-sweep.ts b/src/core/google/people-calendar-sweep.tsindex 94d8c351bd..764fe3f17d 100644--- a/src/core/google/people-calendar-sweep.ts+++ b/src/core/google/people-calendar-sweep.ts@@ -8,7 +8,7 @@ import { existsSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, staleCalendarPages } from './calendar-window.ts';-import { CalendarClient, CONTACT_PERSON_FIELDS, GoogleCursorExpiredError, GoogleSyncTokenRejectedError, PeopleClient } from './google-clients.ts';+import { CalendarClient, calendarUnreadableStatus, CONTACT_PERSON_FIELDS, GoogleCursorExpiredError, GoogleSyncTokenRejectedError, PeopleClient } from './google-clients.ts';import { calendarRelPath, contactIdSlug, personSlugFromContact, renderCalendarEventPage, renderPersonPage } from './google-render.ts';import { DEFAULT_CALENDAR_ID, type CalendarEventData, type ContactData, type GoogleSourceState } from './types.ts';import { deletePageByRelPath, importRendered, type ActivePack, type GoogleSyncDeps, type GoogleSyncSummary } from './sweep-shared.ts';@@ -212,12 +212,21 @@ export async function sweepCalendar(try {result = await list(deltaToken === null ? range.listBounds() : { syncToken: deltaToken });} catch (e) {- if (!(e instanceof GoogleCursorExpiredError)) throw e;+ if (deltaToken === null || !(e instanceof GoogleCursorExpiredError)) {+ if (recordCalendarUnreadable(deps, state, e)) return;+ throw e;+ }deps.log('[google] calendar syncToken expired; windowed re-list');state.calendar_sync_token = null;wholeWindow = true;- result = await list(range.listBounds());+ try {+ result = await list(range.listBounds());+ } catch (relist) {+ if (recordCalendarUnreadable(deps, state, relist)) return;+ throw relist;+ }}+ state.calendar_unreadable = null;const tally = { outside: 0 };const sweepCtx = { activePack, summary, countedSlugs };if (!await applyCalendarList(deps, result.events, range, sweepCtx, tally)) return;@@ -241,6 +250,25 @@ export async function sweepCalendar(if (deps.opts.full) await reconcileCalendarWindow(deps, new Set(result.events.map(ev => ev.id)), range, summary);}+/**+ * #5012 item 9: a 403 or 404 from `events.list` on the configured calendar+ * means this account cannot read it. Instead of a sweep that looks like an+ * empty calendar, the typed result is recorded in source state (doctor's+ * `google_calendar_readable` reads it with no network call) and the log line+ * names the fix. The run is not failed: the calendar stays unreadable until+ * the user changes the source, and a failed run would also hold back Gmail's+ * freshness on every sync.+ */+function recordCalendarUnreadable(deps: GoogleSyncDeps, state: GoogleSourceState, e: unknown): boolean {+ const httpStatus = calendarUnreadableStatus(e);+ if (httpStatus === null) return false;+ state.calendar_unreadable = { code: 'calendar_unreadable', calendar_id: deps.cfg.calendarId, http_status: httpStatus, at: new Date().toISOString() };+ deps.log(`[google] calendar_unreadable: ${deps.cfg.account} cannot read calendar "${deps.cfg.calendarId}" (HTTP ${httpStatus}); no events were synced. `+ + `List the calendars it can read: gbrain google calendars --account ${deps.cfg.account}; `+ + `then point the source at one: gbrain sources set-calendar ${deps.sourceId} <calendar-id>`);+ return true;+}+/*** Apply one calendar list to the brain, event by event. Returns false when* the sweep was aborted part-way, so the caller commits no cursor state.diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex f3fc37b7ba..5967ae7058 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -489,6 +489,10 @@"category": "ops","name": "google_file_modes"},+ {+ "category": "ops",+ "name": "google_calendar_readable"+ },{"category": "brain","name": "extractor_facts_expired"diff --git a/test/google-calendar-unreadable-5012.test.ts b/test/google-calendar-unreadable-5012.test.tsnew file mode 100644index 0000000000..dd155b3f80--- /dev/null+++ b/test/google-calendar-unreadable-5012.test.ts@@ -0,0 +1,210 @@+/**+ * #5012 item 9: an unreadable calendar is reported, not synced as empty.+ *+ * - the calendar sweep records `calendar_unreadable` (403 or 404 from+ * events.list on the configured calendar) in source state and names the+ * fix, instead of failing like a cursor expiry; a readable list clears it;+ * - `CalendarClient.probeCalendar` classifies the live read;+ * - doctor `google_calendar_readable` reads the stored result (zero-network)+ * and `google status --no-probe` reports the same;+ * - `gbrain sources set-calendar` changes the source's calendar id;+ * - (#5012 item 6) changing the contextual retrieval mode prints that+ * existing pages keep theirs, with the repair command.+ *+ * Synthetic data only.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } 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 { CalendarClient, type FetchImpl } from '../src/core/google/google-clients.ts';+import { sweepCalendar } from '../src/core/google/people-calendar-sweep.ts';+import type { GoogleSourceState } from '../src/core/google/types.ts';+import { runSources } from '../src/commands/sources.ts';+import { runConfig } from '../src/commands/config.ts';++const tokens = { getAccessToken: async () => 'token', forceRefresh: async () => 'token' };++function calendarFetch(status: number, body: unknown = {}): { fetchImpl: FetchImpl; urls: string[] } {+ const urls: string[] = [];+ const fetchImpl: FetchImpl = async (url) => {+ urls.push(url);+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });+ };+ return { fetchImpl, urls };+}++const forbidden = { error: { code: 403, message: 'Forbidden', errors: [{ reason: 'forbidden', message: 'Forbidden' }] } };++function sweepDeps(logs: string[]) {+ return {+ sourceId: 'gmail-me',+ cfg: { account: '[email protected]', services: ['calendar'], historyDays: 30, calendarId: '[email protected]', dir: '/nonexistent', access: 'vault', contactsDir: 'contacts' },+ opts: {},+ log: (m: string) => logs.push(m),+ } as never;+}++describe('calendar sweep records an unreadable calendar (forced probe)', () => {+ for (const [status, body] of [[404, { error: { code: 404, message: 'Not Found' } }], [403, forbidden]] as const) {+ test(`HTTP ${status} on events.list is recorded as calendar_unreadable and named in the log`, async () => {+ const { fetchImpl } = calendarFetch(status, body);+ const logs: string[] = [];+ const state = { calendar_sync_token: null } as unknown as GoogleSourceState;+ await sweepCalendar(sweepDeps(logs), new CalendarClient(tokens, fetchImpl), state, undefined, {} as never, new Set());+ expect(state.calendar_unreadable).toMatchObject({ code: 'calendar_unreadable', calendar_id: '[email protected]', http_status: status });+ const line = logs.join('\n');+ expect(line).toContain('calendar_unreadable');+ expect(line).toContain('gbrain google calendars --account [email protected]');+ expect(line).toContain('gbrain sources set-calendar gmail-me <calendar-id>');+ expect(line).not.toContain('syncToken expired');+ });+ }++ test('a readable list clears the stored result', async () => {+ const { fetchImpl } = calendarFetch(200, { items: [], nextSyncToken: 'tok-1' });+ const state = { calendar_sync_token: null, calendar_unreadable: { code: 'calendar_unreadable', calendar_id: 'x', http_status: 404, at: '2026-10-01T00:00:00Z' } } as unknown as GoogleSourceState;+ await sweepCalendar(sweepDeps([]), new CalendarClient(tokens, fetchImpl), state, undefined, {} as never, new Set());+ expect(state.calendar_unreadable).toBeNull();+ expect(state.calendar_sync_token).toBe('tok-1');+ });++ test('any other upstream failure still fails the calendar sweep', async () => {+ const { fetchImpl } = calendarFetch(500, { error: { message: 'backend' } });+ const state = { calendar_sync_token: null } as unknown as GoogleSourceState;+ await expect(sweepCalendar(sweepDeps([]), new CalendarClient(tokens, fetchImpl), state, undefined, {} as never, new Set())).rejects.toThrow();+ expect(state.calendar_unreadable).toBeUndefined();+ });++ test('probeCalendar: readable, 403 and 404', async () => {+ const probe = (client: CalendarClient) => (client as unknown as { probeCalendar: (id: string) => Promise<unknown> }).probeCalendar('[email protected]');+ const ok = calendarFetch(200, { kind: 'calendar#events' });+ expect(await probe(new CalendarClient(tokens, ok.fetchImpl))).toEqual({ readable: true });+ expect(ok.urls[0]).toContain('/calendars/team0123%40group.calendar.google.com/events?maxResults=1');+ expect(await probe(new CalendarClient(tokens, calendarFetch(403, forbidden).fetchImpl))).toEqual({ readable: false, httpStatus: 403 });+ expect(await probe(new CalendarClient(tokens, calendarFetch(404).fetchImpl))).toEqual({ readable: false, httpStatus: 404 });+ });+});++describe('doctor, google status and sources set-calendar', () => {+ let engine: PGLiteEngine;+ let dir: string;+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ dir = mkdtempSync(join(tmpdir(), 'gbrain-cal-5012-'));+ });+ afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+ });+ beforeEach(async () => {+ await resetPgliteState(engine);+ await engine.executeRaw(+ `INSERT INTO sources (id, name, config) VALUES ('gmail-me', 'gmail-me', $1::text::jsonb)+ ON CONFLICT (id) DO UPDATE SET config = EXCLUDED.config`,+ [JSON.stringify({ kind: 'google', g_account: '[email protected]', g_dir: dir, g_calendar_id: '[email protected]' })]);+ writeFileSync(join(dir, '.google-source.json'), '{}');+ });++ const stored = (calendarId: string) => writeFileSync(join(dir, '.google-source.json'), JSON.stringify({+ calendar_unreadable: { code: 'calendar_unreadable', calendar_id: calendarId, http_status: 404, at: '2026-10-14T00:00:00Z' } }));++ test('doctor google_calendar_readable warns from stored state with a read-only fix, and is ok otherwise', async () => {+ const { googleCalendarReadableCheck } = await import('../src/commands/doctor/checks/google-calendar.ts');+ expect((await googleCalendarReadableCheck(engine)).status).toBe('ok');+ stored('[email protected]');+ const check = await googleCalendarReadableCheck(engine);+ expect(check.status).toBe('warn');+ expect(check.details).toMatchObject({ code: 'calendar_unreadable', count: 1, sources: [{ source_id: 'gmail-me', http_status: 404 }] });+ expect(check.message).toContain('gbrain google calendars --account [email protected]');+ expect(check.message).toContain('gbrain sources set-calendar gmail-me <calendar-id>');+ expect((check.fix as { argv: string[]; verify: { argv: string[] } })).toMatchObject({+ argv: ['gbrain', 'google', 'calendars', '--account', '[email protected]', '--json'],+ verify: { argv: ['gbrain', 'doctor', '--only', 'google_calendar_readable', '--json'] } });+ // A result recorded for a calendar the source no longer uses is not reported.+ stored('[email protected]');+ expect((await googleCalendarReadableCheck(engine)).status).toBe('ok');+ });++ test('google status: --no-probe reports the stored result; a live probe overrides it', async () => {+ const { sourceCalendarReadability } = await import('../src/commands/google-calendar-status.ts');+ const [row] = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null; config: Record<string, unknown> }>(+ `SELECT id, incarnation::text AS incarnation, local_path, config FROM sources WHERE id = 'gmail-me'`);+ stored('[email protected]');+ expect(await sourceCalendarReadability(engine, row!, null)).toMatchObject({ readable: false, checked: 'last_sync', code: 'calendar_unreadable',+ fix: { list_command: 'gbrain google calendars --account [email protected]', set_command: 'gbrain sources set-calendar gmail-me <calendar-id>' } });+ const probed: string[] = [];+ expect(await sourceCalendarReadability(engine, row!, async (account, id) => { probed.push(`${account} ${id}`); return { readable: true }; }))+ .toEqual({ calendar_id: '[email protected]', readable: true, checked: 'live' });+ expect(probed).toEqual(['[email protected] [email protected]']);+ expect(await sourceCalendarReadability(engine, row!, async () => ({ readable: false, httpStatus: 403 }))).toMatchObject({ readable: false, http_status: 403, checked: 'live' });+ });++ async function cli(fn: () => Promise<void>): Promise<{ out: string; err: string; exit: number | null }> {+ const out: string[] = [];+ const err: string[] = [];+ let exit: number | null = null;+ const log = spyOn(console, 'log').mockImplementation((...a: unknown[]) => { out.push(a.join(' ')); });+ const error = spyOn(console, 'error').mockImplementation((...a: unknown[]) => { err.push(a.join(' ')); });+ const write = spyOn(process.stderr, 'write').mockImplementation(((c: string) => { err.push(String(c)); return true; }) as never);+ const ex = spyOn(process, 'exit').mockImplementation(((code?: number) => { exit = code ?? 0; throw new Error(`EXIT:${code}`); }) as never);+ try { await fn(); } catch (e) { if (!(e as Error).message.startsWith('EXIT:')) throw e; } finally {+ log.mockRestore(); error.mockRestore(); write.mockRestore(); ex.mockRestore();+ }+ return { out: out.join('\n'), err: err.join('\n'), exit };+ }++ test('sources set-calendar writes g_calendar_id and names the sync; refuses a non-Google source', async () => {+ const r = await cli(() => runSources(engine, ['set-calendar', 'gmail-me', '[email protected]']));+ expect(r.exit).toBeNull();+ expect(r.out).toContain('now syncs calendar [email protected]');+ expect(r.out).toContain('gbrain sync --source gmail-me');+ const [src] = await engine.executeRaw<{ config: Record<string, unknown> }>(`SELECT config FROM sources WHERE id = 'gmail-me'`);+ expect(src!.config.g_calendar_id).toBe('[email protected]');+ expect(src!.config.g_account).toBe('[email protected]');+ const notGoogle = await cli(() => runSources(engine, ['set-calendar', 'default', 'primary']));+ expect(notGoogle.exit).toBe(2);+ const missing = await cli(() => runSources(engine, ['set-calendar', 'nope', 'primary']));+ expect(missing.exit).toBe(4);+ });++ test('sources set-calendar on a managed brain asks first when the source also syncs Gmail (exit 3), then writes with --yes', async () => {+ const managed = new Proxy(engine, { get(target, prop, recv) {+ if (prop !== 'executeRaw') return Reflect.get(target, prop, recv);+ return (sql: string, ...rest: unknown[]) => sql.includes('FROM persistence_brain') ? Promise.resolve([{ enabled: true }])+ : (target.executeRaw as (...a: unknown[]) => Promise<unknown>).call(target, sql, ...rest);+ } }) as PGLiteEngine;+ const asked = await cli(() => runSources(managed, ['set-calendar', 'gmail-me', '[email protected]']));+ expect(asked.exit).toBe(3);+ expect(asked.err).toContain('re-read gmail and contacts history');+ const [before] = await engine.executeRaw<{ config: Record<string, unknown> }>(`SELECT config FROM sources WHERE id = 'gmail-me'`);+ expect(before!.config.g_calendar_id).toBe('[email protected]');+ const yes = await cli(() => runSources(managed, ['set-calendar', 'gmail-me', '[email protected]', '--yes']));+ expect(yes.exit).toBeNull();+ const [after] = await engine.executeRaw<{ config: Record<string, unknown> }>(`SELECT config FROM sources WHERE id = 'gmail-me'`);+ expect(after!.config.g_calendar_id).toBe('[email protected]');+ });++ test('#5012 item 6: config set search.contextual_retrieval and sources set-cr-mode print the existing-pages hint', async () => {+ const global = await cli(() => runConfig(engine, ['set', 'search.contextual_retrieval', 'title']));+ expect(global.out).toContain('Existing pages keep the contextual retrieval mode recorded when they were imported');+ expect(global.out).toContain('gbrain repair contextual-mode --apply');+ const perSource = await cli(() => runSources(engine, ['set-cr-mode', 'gmail-me', 'none']));+ expect(perSource.out).toContain('Existing pages keep the contextual retrieval mode');+ expect(perSource.out).toContain('gbrain repair contextual-mode --source gmail-me --apply');+ });++ test('config set loops.updates_require_reciprocity validates a boolean and writes nothing on a bad value', async () => {+ const bad = await cli(() => runConfig(engine, ['set', 'loops.updates_require_reciprocity', 'maybe']));+ expect(bad.exit).not.toBeNull();+ expect(await engine.getConfig('loops.updates_require_reciprocity')).toBeNull();+ const good = await cli(() => runConfig(engine, ['set', 'loops.updates_require_reciprocity', 'true']));+ expect(good.exit).toBeNull();+ expect(await engine.getConfig('loops.updates_require_reciprocity')).toBe('true');+ });+});