Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(google): keep calendar sync inside its 60-day window (#5511)
time-attack397e00f248b6
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 88b5f418d5..1bfd56f286 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -19,11 +19,12 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding- `src/core/creds/redirect.ts` — how the authorization code gets back to us: `RedirectStrategy = 'loopback' | 'paste' | 'hosted-callback'`. Loopback is an ephemeral 127.0.0.1 listener; paste mode needs NO listener (the fixed `PASTE_REDIRECT_URI` fails to load, the user pastes the full address-bar URL back) and is auto-selected by `sniffHeadless` (SSH/WSL/container/no-display). Google's device-code flow is NOT an option — Gmail/Calendar/Contacts scopes are excluded from it; don't re-litigate.- `src/core/creds/relay-client.ts` — the typed CLIENT half of the gbrain.io zero-retention consent relay (`createSession` → user clicks the consent URL → poll a one-time `claim`; the relay deletes tokens on first successful claim or at session TTL). Inert unless `GBRAIN_OAUTH_RELAY_URL` is set (unset = the BYO flow, which always works). `test/creds-relay-client.test.ts` is the server conformance spec — a server that round-trips those fixtures is compatible.- `src/core/creds/export.ts` — versioned passphrase-encrypted credential bundles (scrypt N=2^15, r=8, p=1 → AES-256-GCM) for machine moves and hosted-upgrade transfer. A bundle carries selected vault entries PLUS the provider client records they depend on (Google refresh tokens are bound to the client that minted them — moving one without the other produces dead tokens). Format frozen here; hosted's import endpoint conforms to it.-- `src/core/google/types.ts` — pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads, `GoogleSourceConfig` (account pointer, services, historyDays, managed dir), and the `GoogleSourceState` cursor file persisted at `<managed dir>/.google-source.json` (gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. Exports `DEFAULT_CALENDAR_ID = 'primary'` (the Calendar API's own alias; every `'primary'` literal in google-clients/google-source/sources/sources-ops resolves through it) and `GoogleSourceConfig.calendarId` (one calendar per source). `GoogleSourceState.calendar_id` records which calendar `calendar_sync_token` was minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's.+- `src/core/google/types.ts` — pure data shapes for the google source kind: normalized Gmail/Calendar/People payloads, `GoogleSourceConfig` (account pointer, services, historyDays, managed dir), and the `GoogleSourceState` cursor file persisted at `<managed dir>/.google-source.json` (gmail history id, downward-moving backfill floor, per-service syncTokens). No I/O. Exports `DEFAULT_CALENDAR_ID = 'primary'` (the Calendar API's own alias; every `'primary'` literal in google-clients/google-source/sources/sources-ops resolves through it) and `GoogleSourceConfig.calendarId` (one calendar per source). `GoogleSourceState.calendar_id` records which calendar `calendar_sync_token` was minted for — a token is only valid against its own calendar; absent on legacy state, which is therefore primary's. `GoogleSourceState.calendar_horizon_ms` records how far the calendar has been listed (calendar-window.ts); absent on legacy state.- `src/core/google/access.ts` — the pluggable Google-access seam: `GoogleAccessProvider` (`getAccessToken`/`forceRefresh`) with `CommandAccessProvider` (`--access command`: any CLI that prints a token — gog/gcloud/a gateway's mint command; parsed as a bare token line or JSON `{token|access_token, expiry|expires_in}`, cached until expiry with a 60s margin, 30s exec timeout, failures = `access_command_failed` carrying the stderr tail) and `EnvAccessProvider` (`--access env`: a live token read from a NAMED env var each call, refreshed outside gbrain; missing = `access_env_missing`). The vault flow's `GoogleTokenProvider` satisfies the same interface. The token command executes only in the locally-running sync (google config keys are unreachable over MCP; same trust class as recipe health-check argv).- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`). A People request with a nonempty `syncToken` maps HTTP 400 to `GoogleCursorExpiredError` only for typed `google.rpc.ErrorInfo` reason `EXPIRED_SYNC_TOKEN` or a message beginning `Sync token [is] expired`; unrelated 400s, initial-list requests, and other APIs remain upstream failures. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. Pinned by injected-response tests in `test/google-clients.test.ts` and `test/google-source-reconcile.test.ts`, not live-provider validation.- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path. FILE MODES (every write, both paths): `writeGoogleState` writes `.google-source.json` through `atomicWriteFileSync(..., { mode: 0o600 })` under `mkdirPrivate(dir)`; a corrupt state file is chmod-ed 0600 and then renamed to `.corrupt`, and if either step fails stderr names the path, the failed step, the exposure and the fix (`chmod 600 <path>` or delete it) while the sync continues with empty cursors. A legacy page goes through `writePrivateTemp`: a stale `<page>.tmp` is removed with `lstat` (never followed; a stale `.tmp` directory fails that item with `Stale temporary path <path> is a directory; remove it and re-run the sync.`), the temp file is created `wx` at 0600 and fchmod-ed past the umask, imported, then renamed over the page; page directories come from `mkdirPrivate(dirname(page), cfg.dir)`. 0600 is reasserted on every rewrite, so a looser mode set by hand is reverted on the next rewrite (unchanged pages are not rewritten). Managed pages get the same modes through `publishMode` (see the persistence coordinator). Mode assertions are skipped on win32. Tests: `test/google-file-modes.test.ts` (child process under umask 0000, `test/helpers/google-file-modes-child.ts`). The loops enqueue runs on every non-aborted sweep in both persistence modes (`--no-extract` gates only the inline link/timeline extract), logs every skip reason and reports `loops_enqueue { enqueued, deferred, skipped_reason }` in the sync result; job payloads carry the page revision (`newestMs`). After the delta and item-hold passes the sweep seeds and settles grace holds, and a managed sweep runs the 30-day catch-up (both in `loop-catchup.ts`); a partial managed run publishes that state with its item holds (`publishHolds` extra), never the Gmail cursor.+- `src/core/google/calendar-window.ts` — the calendar sync window `[now - historyDays, now + 60d]`, enforced on every calendar list (initial, incremental, 410 re-list, `--full`) with the Calendar API's semantics (floor vs the event's end, ceiling vs its start). `applyCalendarEvents` skips past events (their pages stay), deletes the page of an event rescheduled past the horizon, and lets a cancellation (even an id-only skeleton) delete its own page wherever it sits. `calendarCoverageRange` names the bounded stretch still owed after the cursor's list: none after a windowed list, `[now, ceil]` once for state without `calendar_horizon_ms`, else `[horizon, ceil]` when the ceiling moved a day; the coverage list's sync token never replaces the cursor and the horizon advances only after it applied. `unlistedInWindow` is the `--full` reconcile scope: pages with an `event_id` whose event starts inside the listed window and that the complete window list no longer names; `google-source.ts` removes them through the >200 mass-delete guard (refusal marks the run partial) and `deletePageByRelPath`. Nothing before the floor is ever reconciled. Tests: `test/google-source-reconcile.test.ts` (calendar sync window), `test/google-source-materialize.test.ts`.- `src/core/google/file-modes.ts` — detection and tightening for group/world-readable files gbrain wrote under a Google source directory outside `~/.gbrain` (inside it the 0700 home already protects them). `scanGoogleFileModes(engine, { sourceIds? })` reads non-archived Google sources, skips dirs inside the home (`outsideGbrainHome`, realpath-aware), and inspects only gbrain's own layout: `.google-source.json*` in the root, every recorded page `source_path` under `emails/`, `calendar/`, `people/` (malformed paths ignored), each page's `.tmp`, and the directories between the root and those pages. Each path is `lstat`-ed component by component (a symlink anywhere on the path, another owner, or the wrong file type is counted in `skipped`, never followed); an entry is loose when `mode & 0o077`. `tightenGoogleEntry(root, entry)` re-checks the path, opens the leaf `O_NOFOLLOW` (`O_DIRECTORY` for dirs), re-checks the owner on the fd and `fchmod`s `mode & ~0o077`, so a swap after the scan is refused, not followed; the user-chosen root is never in the candidate set. `googleFileModesPreviewCommand`/`googleFileModesApplyCommand` build the `gbrain repair google-file-modes --source <id> [--apply]` strings every surface prints. win32: scan returns nothing. Tests: `test/google-file-modes-repair.test.ts`.- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`), except that my acknowledgement-only reply to their question (`isAcknowledgementOnly`: "Thanks!", "Got it, thanks.") is dropped from the substantive run so it neither closes nor restarts the loop (N7-2); `asksQuestion` ignores a `?` inside a link (N7-7); each spec carries `openedMs`, the oldest obligation-carrying message in the run, which the apply step writes as `opened_at` (N7-6). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync. A grace-window hold returns `held: { untilMs, spec }` (the loop it would open) and `applyThreadLoopVerdict` returns the verdict, so the sweep can record it (`loop-catchup.ts`); `openDueGraceHold` opens a stored spec after re-reading suppressions.- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes.diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.mdindex 5ae3e6720e..a41d46c1d3 100644--- a/docs/guides/google-connect.md+++ b/docs/guides/google-connect.md@@ -127,6 +127,29 @@ re-lists the new calendar from a fresh window instead of replaying the oldcalendar's delta. Pages already imported from the previous calendar stay inthe brain until you remove them — they are not reconciled automatically.+## Calendar window++The calendar keeps pages for events from `--history-days` back to 60 days+ahead. Every sweep enforces that window itself, including incremental syncs:+a change to a recurring series makes Google return every instance of it,+years in both directions, and only the ones inside the window become pages.+As days pass, the sweep lists the newly reached stretch of the 60-day+horizon, so upcoming instances of an unchanged series still arrive. A+meeting rescheduled past the horizon loses its page until it comes back in+range; meetings that aged out of the window keep their pages.++`gbrain sync --source <id> --full` re-lists the whole window and removes the+pages of events that start inside it but are no longer listed (cancelled or+deleted since). It never removes a page whose event starts before the window,+so shrinking `--history-days` keeps your history. More than 200 removals in+one run are refused and the run is reported partial; if that many are+genuinely gone, run it once with `GBRAIN_ALLOW_MASS_RECONCILE=1`. Pages a+source wrote beyond the horizon before the window existed are not removed+automatically.++**Say to your agent:** *"re-sync my calendar from scratch"* (your agent runs+`gbrain sync --source <id> --full`).+## Continuous syncGoogle sources are ordinary gbrain sources: `gbrain sync --source <id>`,diff --git a/src/core/google/calendar-window.ts b/src/core/google/calendar-window.tsnew file mode 100644index 0000000000..5f9397427f--- /dev/null+++ b/src/core/google/calendar-window.ts@@ -0,0 +1,100 @@+/**+ * The calendar sync window: every calendar path materializes only events in+ * `[now - historyDays, now + CALENDAR_HORIZON_DAYS]`.+ *+ * A syncToken delta cannot carry timeMin/timeMax, and with singleEvents=true+ * one change to a recurring series returns every expanded instance, years+ * back and forward. So the window is enforced here on every list (initial,+ * incremental, token-expired and full), with the Calendar API's own+ * semantics: the floor compares an event's END, the ceiling its START.+ *+ * A delta reports changed events only, so an unchanged instance that has+ * entered the horizon since the last list would never arrive. The state's+ * `calendar_horizon_ms` records how far the calendar has been listed, and+ * `calendarCoverageRange` names the bounded stretch to list next. A `--full`+ * reconcile deletes only pages whose event starts inside the listed window and+ * that the complete window list no longer names; nothing before the floor is+ * ever deleted, so shrinking historyDays never removes history.+ */+import type { CalendarEventData } from './types.ts';++/** Days ahead of now the calendar keeps pages for (the windowed list's timeMax). */+export const CALENDAR_HORIZON_DAYS = 60;+const DAY_MS = 86_400_000;++export interface CalendarWindow { floorMs: number; ceilMs: number }++export function calendarWindowAt(nowMs: number, historyDays: number): CalendarWindow {+ return { floorMs: nowMs - historyDays * DAY_MS, ceilMs: nowMs + CALENDAR_HORIZON_DAYS * DAY_MS };+}++/** An event's place against the window; an unparseable start (a cancelled skeleton) counts as in-window. */+export function calendarWindowPlacement(startIso: string, endIso: string, window: CalendarWindow): 'past' | 'in' | 'future' {+ const startMs = Date.parse(startIso);+ if (Number.isFinite(startMs) && startMs >= window.ceilMs) return 'future';+ const endMs = Date.parse(endIso);+ const lastMs = Number.isFinite(endMs) ? endMs : startMs;+ if (Number.isFinite(lastMs) && lastMs <= window.floorMs) return 'past';+ return 'in';+}++/**+ * The stretch still to list after the cursor's own list, or null when none is+ * owed. A windowed list already covered through the ceiling. State that never+ * recorded a horizon (written before it existed) gets one bounded `[now, ceil]`+ * coverage list before the horizon is set; otherwise the stretch past the+ * recorded horizon is listed once the ceiling has moved a day.+ */+export function calendarCoverageRange(horizonMs: number | null | undefined, listedWindow: boolean, window: CalendarWindow,+ nowMs: number): { fromMs: number } | null {+ if (listedWindow) return null;+ if (typeof horizonMs !== 'number') return { fromMs: nowMs };+ return window.ceilMs - horizonMs >= DAY_MS ? { fromMs: horizonMs } : null;+}++export interface CalendarApplyIo<R extends { relPath: string }> {+ signal?: AbortSignal;+ render: (ev: CalendarEventData) => R | null;+ existingPath: (eventId: string) => Promise<string | null>;+ fallbackPath: (ev: CalendarEventData) => string;+ deletePage: (relPath: string) => Promise<void>;+ importPage: (rendered: R) => Promise<void>;+}++/**+ * Materialize listed events inside the window; returns how many were outside+ * it. A past event leaves its page as imported (aged-out history is kept). A+ * cancellation deletes its page wherever the event sits. An event rescheduled+ * past the horizon loses its page; the coverage list brings it back in range.+ */+export async function applyCalendarEvents<R extends { relPath: string }>(events: CalendarEventData[], window: CalendarWindow, io: CalendarApplyIo<R>): Promise<number> {+ let outside = 0;+ for (const ev of events) {+ if (io.signal?.aborted) return outside;+ const rendered = io.render(ev);+ const placement = rendered ? calendarWindowPlacement(ev.startIso, ev.endIso, window) : 'in';+ if (placement === 'past') { outside++; continue; }+ // Identity is the immutable event id, not the date-derived path: reschedules move and+ // cancelled skeletons (id + status only) still find their page.+ const existingPath = await io.existingPath(ev.id);+ if (!rendered) { await io.deletePage(existingPath ?? io.fallbackPath(ev)); continue; }+ if (placement === 'future') {+ outside++;+ if (existingPath) await io.deletePage(existingPath);+ continue;+ }+ if (existingPath && existingPath !== rendered.relPath) await io.deletePage(existingPath);+ await io.importPage(rendered);+ }+ return outside;+}++/** Calendar pages a complete `--full` list of `window` no longer names, limited to events starting inside it. */+export function unlistedInWindow<T extends { event_id: string | null; start_iso: string | null }>(rows: T[], listedIds: ReadonlySet<string>,+ window: CalendarWindow): T[] {+ return rows.filter(row => {+ const startMs = Date.parse(row.start_iso ?? '');+ return row.event_id !== null && !listedIds.has(row.event_id)+ && Number.isFinite(startMs) && startMs >= window.floorMs && startMs < window.ceilMs;+ });+}diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.tsindex b195f12a7d..f2bdc5754e 100644--- a/src/core/google/google-source.ts+++ b/src/core/google/google-source.ts@@ -33,6 +33,7 @@ import { chmodSync, closeSync, existsSync, fchmodSync, lstatSync, openSync, readimport { dirname, join, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';+import { applyCalendarEvents, calendarCoverageRange, calendarWindowAt, unlistedInWindow, type CalendarApplyIo, type CalendarWindow } from './calendar-window.ts';import type { SyncOpts, SyncResult } from '../../commands/sync.ts';import { CredentialError, isCredentialError } from '../creds/errors.ts';import { GOOGLE_PROVIDER, GoogleTokenProvider, fetchSendAsAliases } from '../creds/providers/google.ts';@@ -96,6 +97,7 @@ function emptyState(): GoogleSourceState {gmail_newest_ms: null,calendar_sync_token: null,calendar_id: null,+ calendar_horizon_ms: null,contacts_sync_token: null,last_full_at: null,};@@ -458,11 +460,10 @@ async function sweepCalendar(summary: GoogleSyncSummary,countedSlugs: Set<string>,): Promise<void> {- const now = Date.now();- const windowOpts = {- timeMinIso: new Date(now - deps.cfg.historyDays * 86_400_000).toISOString(),- timeMaxIso: new Date(now + 60 * 86_400_000).toISOString(),- };+ const nowMs = Date.now();+ const window = calendarWindowAt(nowMs, deps.cfg.historyDays);+ const windowOpts = { timeMinIso: new Date(window.floorMs).toISOString(), timeMaxIso: new Date(window.ceilMs).toISOString() };+ const signalOpts = deps.opts.signal ? { signal: deps.opts.signal } : {};// The stored token is bound to the calendar it was minted for (legacy state// without calendar_id predates secondary calendars, so it was primary's).// A re-pointed source starts a fresh window; pairing the NEW calendar with@@ -474,48 +475,73 @@ async function sweepCalendar();state.calendar_sync_token = null;}+ let listedWindow = deps.opts.full || !state.calendar_sync_token;let result;try {result = await calendar.listEvents(deps.cfg.account, {calendarId: deps.cfg.calendarId,- ...(deps.opts.full || !state.calendar_sync_token ? windowOpts : { syncToken: state.calendar_sync_token }),- ...(deps.opts.signal ? { signal: deps.opts.signal } : {}),+ ...(listedWindow ? windowOpts : { syncToken: state.calendar_sync_token }),+ ...signalOpts,});} catch (e) {if (e instanceof GoogleCursorExpiredError) {deps.log('[google] calendar syncToken expired; windowed re-list');state.calendar_sync_token = null;- result = await calendar.listEvents(deps.cfg.account, {- calendarId: deps.cfg.calendarId,- ...windowOpts,- ...(deps.opts.signal ? { signal: deps.opts.signal } : {}),- });+ listedWindow = true;+ result = await calendar.listEvents(deps.cfg.account, { calendarId: deps.cfg.calendarId, ...windowOpts, ...signalOpts });} else {throw e;}}- for (const ev of result.events) {- if (deps.opts.signal?.aborted) return;- // The page path derives from MUTABLE fields (start date, summary) while- // identity is the immutable event id — look up the existing page by- // frontmatter event_id so reschedules move (old page deleted) and- // cancelled skeletons (id + status only, per the Calendar API) still- // find their page instead of computing a 1970 ghost path.- const existingPath = await calendarPageRelPathByEventId(deps, ev.id);- const rendered = renderCalendarEventPage(ev);- if (!rendered) {- await deletePageByRelPath(deps, existingPath ?? calendarRelPath(ev), summary);- continue;- }- if (existingPath && existingPath !== rendered.relPath) {- await deletePageByRelPath(deps, existingPath, summary); // rescheduled → moved- }- await importRendered(deps, rendered.relPath, rendered.markdown, activePack, summary, countedSlugs);- }+ const io: CalendarApplyIo<NonNullable<ReturnType<typeof renderCalendarEventPage>>> = {+ signal: deps.opts.signal,+ render: renderCalendarEventPage,+ existingPath: eventId => calendarPageRelPathByEventId(deps, eventId),+ fallbackPath: calendarRelPath,+ deletePage: relPath => deletePageByRelPath(deps, relPath, summary),+ importPage: async rendered => { await importRendered(deps, rendered.relPath, rendered.markdown, activePack, summary, countedSlugs); },+ };+ let outside = await applyCalendarEvents(result.events, window, io);+ if (deps.opts.signal?.aborted) return;if (result.nextSyncToken) {state.calendar_sync_token = result.nextSyncToken;state.calendar_id = deps.cfg.calendarId;}+ // The coverage list's own sync token is never the cursor; the horizon advances only after it applied.+ const coverage = calendarCoverageRange(state.calendar_horizon_ms, listedWindow, window, nowMs);+ if (coverage) {+ const listed = await calendar.listEvents(deps.cfg.account, {+ calendarId: deps.cfg.calendarId, timeMinIso: new Date(coverage.fromMs).toISOString(), timeMaxIso: windowOpts.timeMaxIso, ...signalOpts,+ });+ outside += await applyCalendarEvents(listed.events, window, io);+ if (deps.opts.signal?.aborted) return;+ }+ state.calendar_horizon_ms = window.ceilMs;+ if (outside > 0) deps.log(`[google] calendar: skipped ${outside} event(s) outside the sync window`);+ if (deps.opts.full) await reconcileCalendarWindow(deps, new Set(result.events.map(ev => ev.id)), window, summary);+}++/**+ * `--full`: remove calendar pages the complete window list no longer names,+ * limited to events starting inside the listed window (calendar-window.ts),+ * through the mass-delete guard and the sweep's own delete primitive.+ */+async function reconcileCalendarWindow(deps: GoogleSyncDeps, listedIds: ReadonlySet<string>, window: CalendarWindow,+ summary: GoogleSyncSummary): Promise<void> {+ const rows = await deps.engine.executeRaw<{ slug: string; source_path: string | null; event_id: string | null; start_iso: string | null }>(+ `SELECT slug, source_path, frontmatter->>'event_id' AS event_id, frontmatter->>'start' AS start_iso FROM pages+ WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE 'calendar/%' AND frontmatter->>'event_id' IS NOT NULL`,+ [deps.sourceId],+ );+ const stale = unlistedInWindow(rows, listedIds, window).filter(row => row.source_path !== null);+ if (stale.length === 0) return;+ const { massReconcileAllowed } = await import('../../commands/sync.ts');+ if (stale.length > 200 && !massReconcileAllowed()) {+ deps.log(`[google] mass-delete guard refused ${stale.length} deletes for source ${deps.sourceId}`);+ summary.status = 'partial';+ return;+ }+ for (const page of stale) await deletePageByRelPath(deps, page.source_path!, summary);}// ── Gmail sweep ──────────────────────────────────────────────────────────────diff --git a/src/core/google/types.ts b/src/core/google/types.tsindex 25ed63bb19..a1f3ad65aa 100644--- a/src/core/google/types.ts+++ b/src/core/google/types.ts@@ -99,6 +99,13 @@ export interface GoogleSourceState {* calendars and was therefore always primary's.*/calendar_id?: string | null;+ /**+ * Epoch ms the calendar has been listed through (calendar-window.ts). A+ * syncToken delta reports changed events only, so the sweep lists the+ * stretch past it once the window's ceiling moves a day; state without it+ * gets one bounded coverage list first.+ */+ calendar_horizon_ms?: number | null;contacts_sync_token: string | null;last_full_at: string | null;gmail_attachment_backfill?: {diff --git a/test/google-source-materialize.test.ts b/test/google-source-materialize.test.tsindex a36bef072a..e6de8c636a 100644--- a/test/google-source-materialize.test.ts+++ b/test/google-source-materialize.test.ts@@ -642,6 +642,77 @@ describe('google-source materialize', () => {}});+ test('calendar delta: instances starting beyond the horizon are skipped, near ones land, the token still advances', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-cal-horizon-'));+ const fx = emptyFx();+ calendarFixture(fx);+ const vault = makeVault();+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ await sweep(dir, fx, vault, {}, 'calendar');+ expect(readGoogleState(dir).calendar_sync_token).toBe('cal-sync-1');++ // A touched weekly series comes back through the syncToken delta as+ // EVERY expanded instance to the end of the series. Two arrive: one+ // next week, one three years out. Only the first may materialize.+ const inst = (id: string, startMs: number) => ({+ id,+ status: 'confirmed',+ summary: 'Weekly zephyr standup',+ start: { dateTime: new Date(startMs).toISOString() },+ end: { dateTime: new Date(startMs + 1_800_000).toISOString() },+ organizer: { email: '[email protected]' },+ attendees: [{ email: '[email protected]', self: true, responseStatus: 'accepted' }],+ htmlLink: `https://calendar.google.com/calendar/event?eid=${id}`,+ });+ fx.calendarDelta = [inst('evt0000000000w001', NOW_MS + 7 * 86_400_000), inst('evt0000000000w999', NOW_MS + 3 * 365 * 86_400_000)];+ const res = await sweep(dir, fx, vault, {}, 'calendar');+ expect(res.added).toBe(1);++ const meetings = await slugsWhere(`slug LIKE 'calendar/%'`);+ expect(meetings.length).toBe(2); // the original fixture meeting + the near instance+ expect(meetings.some((s) => s.includes('weekly-zephyr-standup'))).toBe(true);+ const farYear = new Date(NOW_MS + 3 * 365 * 86_400_000).getUTCFullYear();+ expect(meetings.some((s) => s.startsWith(`calendar/${farYear}/`))).toBe(false);+ // The delta was consumed: the token advances even though an instance was skipped.+ expect(readGoogleState(dir).calendar_sync_token).toBe('cal-sync-2');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('calendar delta: a cancelled skeleton (id + status, no dates) still retracts its own page and nothing else', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-cal-skeleton-'));+ const fx = emptyFx();+ calendarFixture(fx);+ const vault = makeVault();+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ const near = {+ id: 'evt0000000000s001', status: 'confirmed', summary: 'Zephyr design review',+ start: { dateTime: new Date(NOW_MS + 3 * 86_400_000).toISOString() },+ end: { dateTime: new Date(NOW_MS + 3 * 86_400_000 + 3_600_000).toISOString() },+ organizer: { email: '[email protected]' },+ attendees: [{ email: '[email protected]', self: true, responseStatus: 'accepted' }],+ };+ fx.calendarEvents = [...fx.calendarEvents, near];+ await sweep(dir, fx, vault, {}, 'calendar');+ const before = await slugsWhere(`slug LIKE 'calendar/%'`);+ expect(before.some((s) => s.includes('zephyr-design-review'))).toBe(true);++ fx.calendarDelta = [{ id: 'evt0000000000s001', status: 'cancelled' }];+ const res = await sweep(dir, fx, vault, {}, 'calendar');+ expect(res.deleted).toBe(1);+ expect(await slugsWhere(`slug LIKE 'calendar/%'`)).toEqual(before.filter((s) => !s.includes('zephyr-design-review')));+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+test('history 404 falls back to a bookmark window and re-anchors a fresh historyId', async () => {const dir = mkdtempSync(join(tmpdir(), 'gsrc-expired-'));const fx = emptyFx();diff --git a/test/google-source-reconcile.test.ts b/test/google-source-reconcile.test.tsindex be37f7985c..ac50c7a210 100644--- a/test/google-source-reconcile.test.ts+++ b/test/google-source-reconcile.test.ts@@ -105,6 +105,10 @@ interface FakeGoogle {calendarEvents: unknown[];calendarDelta: unknown[];calendarExpireSyncToken: boolean;+ /** Windowed (no syncToken) calendar lists answer HTTP 400. */+ calendarFailWindowed: boolean;+ /** Called as a windowed (no syncToken) calendar list is served. */+ onCalendarWindowed?: () => void;/** Counters so each windowed/full re-list mints a DISTINCT sync token. */calendarWindowedLists: number;contactsFullLists: number;@@ -127,6 +131,7 @@ function emptyFx(): FakeGoogle {calendarEvents: [],calendarDelta: [],calendarExpireSyncToken: false,+ calendarFailWindowed: false,calendarWindowedLists: 0,contactsFullLists: 0,calls: [],@@ -208,6 +213,8 @@ function buildFetch(fx: FakeGoogle): FetchImpl {if (fx.calendarExpireSyncToken) return json({ error: { code: 410, message: 'Sync token expired' } }, 410);return json({ items: fx.calendarDelta, nextSyncToken: 'cal-sync-delta' });}+ if (fx.calendarFailWindowed) return json({ error: { code: 400, message: 'Bad Request' } }, 400);+ fx.onCalendarWindowed?.();fx.calendarWindowedLists++;return json({ items: fx.calendarEvents, nextSyncToken: `cal-sync-w${fx.calendarWindowedLists}` });}@@ -791,8 +798,11 @@ describe('syncToken 410 recovery', () => {await insertGoogleSource(dirA);writeFileSync(googleStateFile(dirA), JSON.stringify(legacyState), 'utf-8');await sweep(dirA, fxA, makeVault(), {}, 'calendar');- expect(fxA.calendarWindowedLists).toBe(0);expect(fxA.calls.filter((c) => c.includes('/calendars/'))[0]).toContain('syncToken=cal-sync-legacy');+ // Legacy state has no calendar horizon either: one bounded [now, now + 60d] coverage list, never the window floor.+ expect(fxA.calendarWindowedLists).toBe(1);+ const coverageMin = Date.parse(calendarCallParams(fxA)[1].get('timeMin')!);+ expect(Math.abs(coverageMin - Date.now())).toBeLessThan(60_000);const stateA = readGoogleState(dirA);expect(stateA.calendar_sync_token).toBe('cal-sync-delta');expect(stateA.calendar_id).toBe('primary');@@ -915,6 +925,431 @@ describe('syncToken 410 recovery', () => {});});+// ── Calendar sync window ─────────────────────────────────────────────────────+// A syncToken request cannot carry timeMin/timeMax, and with singleEvents=true+// any change to a recurring series returns every expanded instance, years back+// and forward. The window [now - historyDays, now + 60d] is enforced by the+// sweep itself on every path.++const CAL_DAY = 86_400_000;++function calEvent(id: string, startMs: number, over: { summary?: string; durationMs?: number } = {}) {+ return {+ id,+ status: 'confirmed',+ summary: over.summary ?? 'Weekly zephyr sync',+ start: { dateTime: new Date(startMs).toISOString() },+ end: { dateTime: new Date(startMs + (over.durationMs ?? 3_600_000)).toISOString() },+ organizer: { email: '[email protected]' },+ attendees: [{ email: '[email protected]', self: true, responseStatus: 'accepted' }],+ };+}++async function calendarSlugs(): Promise<string[]> {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages WHERE source_id = 'gsrc' AND deleted_at IS NULL AND slug LIKE 'calendar/%' ORDER BY slug`,+ );+ return rows.map((r) => r.slug);+}++function calendarCallParams(fx: FakeGoogle): URLSearchParams[] {+ return fx.calls.filter((c) => c.includes('/calendars/')).map((c) => new URL(c, 'https://www.googleapis.com').searchParams);+}++/** Seed a calendar page as an earlier (pre-fix) sweep would have left it. */+async function seedCalendarPage(slug: string, eventId: string | null, startMs: number, createdAtMs: number): Promise<void> {+ await engine.putPage(+ slug,+ {+ type: 'meeting',+ title: 'Weekly zephyr sync',+ compiled_truth: 'A seeded meeting.',+ frontmatter: {+ ...(eventId ? { event_id: eventId } : {}),+ start: new Date(startMs).toISOString(),+ end: new Date(startMs + 3_600_000).toISOString(),+ },+ },+ { sourceId: 'gsrc' },+ );+ await engine.executeRaw(+ `UPDATE pages SET created_at = $1::timestamptz, source_path = $2 || '.md' WHERE source_id = 'gsrc' AND slug = $2`,+ [new Date(createdAtMs).toISOString(), slug],+ );+}++describe('calendar sync window', () => {+ test('an incremental delta imports only instances inside [now - historyDays, now + 60d]', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-calwin-'));+ const fx = emptyFx();+ const vault = makeVault();+ fx.calendarEvents = [calEvent('ser1_w01', NOW_MS + 1 * CAL_DAY)];+ fx.calendarDelta = [+ calEvent('ser1_past3y', NOW_MS - 3 * 365 * CAL_DAY),+ calEvent('ser1_past95d', NOW_MS - 95 * CAL_DAY),+ // Began before the floor, still running inside it: in window (the API's+ // timeMin also compares against the END time).+ calEvent('ser1_straddle', NOW_MS - 100 * CAL_DAY, { durationMs: 20 * CAL_DAY }),+ calEvent('ser1_in7d', NOW_MS + 7 * CAL_DAY),+ calEvent('ser1_fut75d', NOW_MS + 75 * CAL_DAY),+ calEvent('ser1_fut10y', NOW_MS + 10 * 365 * CAL_DAY),+ ];+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ expect((await sweep(dir, fx, vault, {}, 'calendar')).added).toBe(1);+ const { result: res2, err } = await capturedStderr(() => sweep(dir, fx, vault, {}, 'calendar'));+ expect(res2.status).not.toBe('partial');+ expect(res2.added).toBe(2);+ const slugs = await calendarSlugs();+ expect(slugs).toHaveLength(3);+ const years = slugs.map((s) => Number(s.split('/')[1]));+ expect(Math.min(...years)).toBeGreaterThanOrEqual(new Date(NOW_MS - 100 * CAL_DAY).getUTCFullYear());+ expect(Math.max(...years)).toBeLessThanOrEqual(new Date(NOW_MS + 60 * CAL_DAY).getUTCFullYear());+ expect(err).toContain('[google] calendar: skipped 4 event(s) outside the sync window');+ expect(readGoogleState(dir).calendar_sync_token).toBe('cal-sync-delta');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('an existing page moved past the horizon is deleted; aged-out history is left untouched', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-calmove-'));+ const fx = emptyFx();+ const vault = makeVault();+ fx.calendarEvents = [+ calEvent('evt_old', NOW_MS - 200 * CAL_DAY, { summary: 'Old planning' }),+ calEvent('evt_gone', NOW_MS - 250 * CAL_DAY, { summary: 'Gone retro' }),+ calEvent('evt_soon', NOW_MS + 10 * CAL_DAY, { summary: 'Soon review' }),+ ];+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ // Imported while the source kept 400 days of history.+ expect((await sweep(dir, fx, vault, {}, 'calendar', { cfg: { g_history_days: 400 } })).added).toBe(3);+ const before = await calendarSlugs();+ const oldSlug = before.find((s) => s.includes('old-planning'))!;+ const soonSlug = before.find((s) => s.includes('soon-review'))!;++ fx.calendarDelta = [+ calEvent('evt_old', NOW_MS - 200 * CAL_DAY, { summary: 'Old planning renamed' }),+ calEvent('evt_soon', NOW_MS + 200 * CAL_DAY, { summary: 'Soon review' }),+ // A cancelled series instance keeps its start; the cancellation still+ // deletes its page wherever the event sits in time.+ { ...calEvent('evt_gone', NOW_MS - 250 * CAL_DAY, { summary: 'Gone retro' }), status: 'cancelled' },+ ];+ const res2 = await sweep(dir, fx, vault, {}, 'calendar');+ expect(res2.deleted).toBe(2);+ expect(res2.added).toBe(0);+ expect(await calendarSlugs()).toEqual([oldSlug]);+ expect(existsSync(join(dir, `${soonSlug}.md`))).toBe(false);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('instances that enter the horizon are listed once per advance; the top-up never replaces the sync token', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-caltop-'));+ const fx = emptyFx();+ const vault = makeVault();+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const horizon1 = readGoogleState(dir).calendar_horizon_ms!;+ expect(Math.abs(horizon1 - (Date.now() + 60 * CAL_DAY))).toBeLessThan(60_000);++ // Ten days pass: the stored horizon lags now + 60d.+ const lagged = NOW_MS + 50 * CAL_DAY;+ writeFileSync(+ googleStateFile(dir),+ JSON.stringify({ ...readGoogleState(dir), calendar_horizon_ms: lagged }),+ 'utf-8',+ );+ fx.calls = [];+ fx.calendarEvents = [calEvent('ser2_fut55d', NOW_MS + 55 * CAL_DAY, { summary: 'Entering sync' })];+ const res2 = await sweep(dir, fx, vault, {}, 'calendar');+ expect(res2.added).toBe(1);+ const params = calendarCallParams(fx);+ expect(params).toHaveLength(2);+ expect(params[0].get('syncToken')).toBe('cal-sync-w1');+ expect(params[1].get('syncToken')).toBeNull();+ expect(params[1].get('timeMin')).toBe(new Date(lagged).toISOString());+ const state = readGoogleState(dir);+ expect(state.calendar_sync_token).toBe('cal-sync-delta');+ expect(state.calendar_horizon_ms!).toBeGreaterThan(lagged);++ // A sweep right after: the horizon has not moved a day, no top-up.+ fx.calls = [];+ await sweep(dir, fx, vault, {}, 'calendar');+ expect(calendarCallParams(fx)).toHaveLength(1);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('a failed horizon top-up marks the sweep partial, keeps the horizon, and retries next sweep', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-caltopfail-'));+ const fx = emptyFx();+ const vault = makeVault();+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const lagged = NOW_MS + 50 * CAL_DAY;+ writeFileSync(+ googleStateFile(dir),+ JSON.stringify({ ...readGoogleState(dir), calendar_horizon_ms: lagged }),+ 'utf-8',+ );+ fx.calendarEvents = [calEvent('ser3_fut55d', NOW_MS + 55 * CAL_DAY, { summary: 'Retried entry' })];+ fx.calendarFailWindowed = true;+ const res2 = await sweep(dir, fx, vault, {}, 'calendar');+ expect(res2.status).toBe('partial');+ expect(readGoogleState(dir).calendar_horizon_ms).toBe(lagged);+ expect(await calendarSlugs()).toHaveLength(0);++ fx.calendarFailWindowed = false;+ const res3 = await sweep(dir, fx, vault, {}, 'calendar');+ expect(res3.status).not.toBe('partial');+ expect(res3.added).toBe(1);+ expect(readGoogleState(dir).calendar_horizon_ms!).toBeGreaterThan(lagged);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('a sweep aborted during the horizon top-up keeps the horizon for the next sweep', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-caltopabort-'));+ const fx = emptyFx();+ const vault = makeVault();+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const lagged = NOW_MS + 50 * CAL_DAY;+ writeFileSync(+ googleStateFile(dir),+ JSON.stringify({ ...readGoogleState(dir), calendar_horizon_ms: lagged }),+ 'utf-8',+ );+ fx.calendarEvents = [calEvent('ser4_fut55d', NOW_MS + 55 * CAL_DAY, { summary: 'Aborted entry' })];+ const controller = new AbortController();+ fx.onCalendarWindowed = () => controller.abort();+ const res = await sweep(dir, fx, vault, { signal: controller.signal }, 'calendar');+ expect(res.status).toBe('partial');+ expect(readGoogleState(dir).calendar_horizon_ms).toBe(lagged);+ expect(await calendarSlugs()).toHaveLength(0);++ // An aborted --full skips the window reconcile too.+ await seedCalendarPage('calendar/2026/10/unlisted-kept', 'evt_unlisted_abort', NOW_MS + 5 * CAL_DAY, NOW_MS);+ const fullCtl = new AbortController();+ fx.onCalendarWindowed = () => fullCtl.abort();+ const resFull = await sweep(dir, fx, vault, { full: true, signal: fullCtl.signal }, 'calendar');+ expect(resFull.status).toBe('partial');+ expect(await calendarSlugs()).toEqual(['calendar/2026/10/unlisted-kept']);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('a 410 re-list covers the whole window: no top-up on top of it', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-cal410h-'));+ const fx = emptyFx();+ const vault = makeVault();+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const lagged = NOW_MS + 50 * CAL_DAY;+ writeFileSync(+ googleStateFile(dir),+ JSON.stringify({ ...readGoogleState(dir), calendar_horizon_ms: lagged }),+ 'utf-8',+ );+ fx.calls = [];+ fx.calendarExpireSyncToken = true;+ await sweep(dir, fx, vault, {}, 'calendar');+ expect(calendarCallParams(fx)).toHaveLength(2); // expired delta + windowed re-list+ expect(readGoogleState(dir).calendar_horizon_ms!).toBeGreaterThan(lagged);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('the horizon top-up lists the SECONDARY calendar the source is bound to', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-caltopsec-'));+ const fx = emptyFx();+ const vault = makeVault();+ const secondary = '[email protected]';+ const cfg = { g_calendar_id: secondary };+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ await sweep(dir, fx, vault, {}, 'calendar', { cfg });+ writeFileSync(+ googleStateFile(dir),+ JSON.stringify({ ...readGoogleState(dir), calendar_horizon_ms: NOW_MS + 50 * CAL_DAY }),+ 'utf-8',+ );+ fx.calls = [];+ await sweep(dir, fx, vault, {}, 'calendar', { cfg });+ const calendarCalls = fx.calls.filter((c) => c.includes('/calendars/'));+ expect(calendarCalls).toHaveLength(2);+ for (const c of calendarCalls) {+ expect(c).toContain(`/calendars/${encodeURIComponent(secondary)}/events`);+ }+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('legacy state without a horizon does one bounded [now, ceil] coverage list before advancing it', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-callegh-'));+ try {+ await insertGoogleSource(dir);+ writeFileSync(+ googleStateFile(dir),+ JSON.stringify({ ...readGoogleState(dir), calendar_sync_token: 'cal-sync-legacy', calendar_id: 'primary' }),+ 'utf-8',+ );+ await withHome(async () => {+ const fx = emptyFx();+ // Unchanged since the legacy list, entered the horizon since: only a coverage list can bring it.+ fx.calendarEvents = [calEvent('legacy_fut40d', NOW_MS + 40 * CAL_DAY, { summary: 'Entered horizon' })];+ const res = await sweep(dir, fx, makeVault(), {}, 'calendar');+ expect(res.added).toBe(1);+ const params = calendarCallParams(fx);+ expect(params).toHaveLength(2);+ expect(params[0].get('syncToken')).toBe('cal-sync-legacy');+ expect(params[1].get('syncToken')).toBeNull();+ expect(Math.abs(Date.parse(params[1].get('timeMin')!) - Date.now())).toBeLessThan(60_000);+ expect(Math.abs(Date.parse(params[1].get('timeMax')!) - (Date.now() + 60 * CAL_DAY))).toBeLessThan(60_000);+ const state = readGoogleState(dir);+ expect(state.calendar_sync_token).toBe('cal-sync-delta');+ expect(Math.abs(state.calendar_horizon_ms! - (Date.now() + 60 * CAL_DAY))).toBeLessThan(60_000);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('a failed legacy coverage list leaves the horizon unset, so the next sweep lists again', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-callegfail-'));+ try {+ await insertGoogleSource(dir);+ writeFileSync(+ googleStateFile(dir),+ JSON.stringify({ ...readGoogleState(dir), calendar_sync_token: 'cal-sync-legacy', calendar_id: 'primary' }),+ 'utf-8',+ );+ await withHome(async () => {+ const fx = emptyFx();+ fx.calendarFailWindowed = true;+ expect((await sweep(dir, fx, makeVault(), {}, 'calendar')).status).toBe('partial');+ expect(readGoogleState(dir).calendar_horizon_ms ?? null).toBeNull();+ fx.calendarFailWindowed = false;+ fx.calls = [];+ await sweep(dir, fx, makeVault(), {}, 'calendar');+ expect(calendarCallParams(fx)).toHaveLength(2);+ expect(typeof readGoogleState(dir).calendar_horizon_ms).toBe('number');+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('--full reconcile removes only in-window pages the window list no longer names', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-calrec-'));+ const fx = emptyFx();+ const vault = makeVault();+ fx.calendarEvents = [calEvent('evt_live', NOW_MS + 3 * CAL_DAY, { summary: 'Live sync' })];+ try {+ await insertGoogleSource(dir);+ // Cancelled (or deleted) since the last list: inside the window, no longer listed.+ await seedCalendarPage('calendar/2026/10/dropped-review', 'evt_dropped', NOW_MS + 5 * CAL_DAY, NOW_MS);+ await seedCalendarPage('calendar/2026/09/dropped-retro', 'evt_dropped_past', NOW_MS - 10 * CAL_DAY, NOW_MS - 11 * CAL_DAY);+ // Outside the listed window: never reconciled, whatever their age or origin.+ await seedCalendarPage('calendar/2026/03/aged-history', 'evt_hist', NOW_MS - 200 * CAL_DAY, NOW_MS - 199 * CAL_DAY);+ await seedCalendarPage('calendar/2036/09/overflow-future', 'ser_fut', NOW_MS + 10 * 365 * CAL_DAY, NOW_MS);+ // Hand-authored (no event_id): not the sweep's page.+ await seedCalendarPage('calendar/2026/10/manual-note', null, NOW_MS + 4 * CAL_DAY, NOW_MS);+ await withHome(async () => {+ const res = await sweep(dir, fx, vault, { full: true }, 'calendar');+ expect(res.status).not.toBe('partial');+ expect(res.deleted).toBe(2);+ const slugs = await calendarSlugs();+ expect(slugs).not.toContain('calendar/2026/10/dropped-review');+ expect(slugs).not.toContain('calendar/2026/09/dropped-retro');+ expect(slugs).toContain('calendar/2026/03/aged-history');+ expect(slugs).toContain('calendar/2036/09/overflow-future');+ expect(slugs).toContain('calendar/2026/10/manual-note');+ expect(slugs.some((s) => s.includes('live-sync'))).toBe(true);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('shrinking historyDays deletes nothing before the old floor on --full', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-calshrink-'));+ const fx = emptyFx();+ const vault = makeVault();+ fx.calendarEvents = [+ calEvent('evt_200d', NOW_MS - 200 * CAL_DAY, { summary: 'Old offsite' }),+ calEvent('evt_30d', NOW_MS - 30 * CAL_DAY, { summary: 'Recent review' }),+ ];+ try {+ await insertGoogleSource(dir);+ await withHome(async () => {+ expect((await sweep(dir, fx, vault, { full: true }, 'calendar', { cfg: { g_history_days: 400 } })).added).toBe(2);+ // The source now keeps 90 days; the -200d event is no longer in any list.+ fx.calendarEvents = [calEvent('evt_30d', NOW_MS - 30 * CAL_DAY, { summary: 'Recent review' })];+ const res = await sweep(dir, fx, vault, { full: true }, 'calendar');+ expect(res.deleted).toBe(0);+ const slugs = await calendarSlugs();+ expect(slugs.some((s) => s.includes('old-offsite'))).toBe(true);+ expect(slugs.some((s) => s.includes('recent-review'))).toBe(true);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test('--full calendar reconcile honours the mass-delete guard', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-calmass-'));+ const fx = emptyFx();+ const vault = makeVault();+ try {+ await insertGoogleSource(dir);+ for (let i = 0; i < 201; i++) {+ await seedCalendarPage(`calendar/2026/bulk/instance-${String(i).padStart(3, '0')}`, `ser_bulk_${i}`, NOW_MS + (1 + (i % 50)) * CAL_DAY, NOW_MS);+ }+ await withHome(async () => {+ const { result: res1, err } = await capturedStderr(() => sweep(dir, fx, vault, { full: true }, 'calendar'));+ expect(res1.deleted).toBe(0);+ expect(err).toContain('mass-delete guard refused 201 deletes');+ expect(res1.status).toBe('partial');+ expect(await calendarSlugs()).toHaveLength(201);++ await withEnv({ GBRAIN_ALLOW_MASS_RECONCILE: '1' }, async () => {+ expect((await sweep(dir, fx, vault, { full: true }, 'calendar')).deleted).toBe(201);+ });+ expect(await calendarSlugs()).toHaveLength(0);+ });+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});+// ── loops_extract enqueue completeness ───────────────────────────────────────describe('loops_extract enqueue completeness', () => {