Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(google): our own implementation of the #5511 fix (#5511)
time-attack5d505cc644c1
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.mdindex 4dac0dcfa9..52771bbce2 100644--- a/docs/architecture/key-files/google-and-loops.md+++ b/docs/architecture/key-files/google-and-loops.md@@ -19,12 +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. `GoogleSourceState.calendar_horizon_ms` records how far the calendar has been listed (calendar-window.ts); absent on legacy state.+- `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` is the ceiling of the last calendar list that reached it (calendar-window.ts); absent on state saved before it existed.- `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/calendar-window.ts` — which calendar events a google source keeps pages for: `[now - historyDays, now + 60d]`, checked by the sweep itself on every list because a syncToken delta cannot carry timeMin/timeMax. `CalendarSyncWindow` is built once per sweep: `side(start, end)` follows Google's rule (an event is `before` when it ends at or before the floor, `after` when it starts at or past the ceiling, unparseable dates stay `inside`); `coverageStartMs(horizon, listedWholeWindow)` says where the catch-up list for unchanged instances crossing the leading edge starts (none after a whole-window list, now for state without `calendar_horizon_ms`, the recorded horizon once the ceiling is a day past it); `startsInside` is the `--full` reconcile test. `planCalendarPage` maps one listed event to a page change (a cancellation removes its page anywhere, aged-out history is left as it is, a page past the horizon is removed, otherwise write after removing a copy at an older path). `unlistedCalendarPages` returns sweep pages (with an `event_id`) starting inside the window that a complete `--full` list did not name. `google-source.ts` performs the changes with `importRendered`/`deletePageByRelPath`, discards the catch-up list's sync token, advances `calendar_horizon_ms` only after a list reached the ceiling, and sends reconcile deletes through the >200 mass-delete guard (a refusal marks the run partial). Tests: `test/google-calendar-window.test.ts` (pure rules), `test/google-source-reconcile.test.ts` (calendar window suite).- `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), auto-submitted mail (RFC 3834 `Auto-Submitted` other than `no`, which also never closes a loop, so an auto-reply is not an answer), 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; a failed facts write is logged with slug, source and a bounded error, never the commitment text, and the loop row still lands), 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`, `Auto-Submitted`, 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. A judge response cut off at the 2048-token cap (`stopReason: length`) is retried once at 8192; still truncated, the job fails retryable (`truncated`) with the ceiling named. Non-length errors and refusals are never escalated.diff --git a/docs/guides/google-connect.md b/docs/guides/google-connect.mdindex a41d46c1d3..26bdaf8c20 100644--- a/docs/guides/google-connect.md+++ b/docs/guides/google-connect.md@@ -129,14 +129,15 @@ the 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.+Calendar pages cover events from `--history-days` ago up to 60 days from+now, and each sweep applies that range on its own. That matters for+incremental syncs: after any edit to a recurring series, Google sends back+the series' instances for years before and after, and only those inside the+range are kept. Because the 60-day edge moves forward daily, the sweep also+lists the days it has newly reached, so future instances of a series nobody+touched still appear. If a meeting moves beyond 60 days out, its page goes+away until the meeting is back within range. Meetings that have aged out of+the range keep their pages.`gbrain sync --source <id> --full` re-lists the whole window and removes thepages of events that start inside it but are no longer listed (cancelled ordiff --git a/src/core/google/calendar-window.ts b/src/core/google/calendar-window.tsindex c077a3015d..18eaacce3e 100644--- a/src/core/google/calendar-window.ts+++ b/src/core/google/calendar-window.ts@@ -1,100 +1,118 @@/**- * The calendar sync window: every calendar path materializes only events in- * `[now - historyDays, now + CALENDAR_HORIZON_DAYS]`.+ * Which calendar events a google source keeps pages for (#5442).*- * 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.+ * The source mirrors one rolling range: from `historyDays` back to+ * `CALENDAR_HORIZON_DAYS` ahead. Google can only apply that range to a+ * windowed list; a syncToken delta carries no timeMin/timeMax, and with+ * singleEvents=true a single edit to a recurring series brings back every+ * expanded instance of it, years in both directions. So the sweep checks each+ * listed event against the range itself, on every kind of list.*- * 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.+ * `CalendarSyncWindow` is computed once per sweep and answers three questions:+ * - which side of the range an event falls on (`side`), matching Google's own+ * rule: timeMin is compared with an event's end, timeMax with its start;+ * - what a delta cannot tell us: the range's leading edge moves forward every+ * day, and an unchanged instance that crosses it never appears in a delta.+ * `GoogleSourceState.calendar_horizon_ms` records how far ahead the calendar+ * was last listed, and `coverageStartMs` says where the next catch-up list+ * must begin;+ * - which existing pages a complete `--full` list has dropped+ * (`unlistedCalendarPages`). Only events starting inside the listed range+ * qualify, so pages older than the floor (for example after historyDays+ * shrinks) are never removed by a reconcile.+ *+ * `planCalendarPage` turns one listed event into a page change; google-source+ * performs it with its own write and delete primitives.*/import type { CalendarEventData } from './types.ts';-/** Days ahead of now the calendar keeps pages for (the windowed list's timeMax). */+/** How far ahead of now calendar pages are kept, in days. */export const CALENDAR_HORIZON_DAYS = 60;-const DAY_MS = 86_400_000;-export interface CalendarWindow { floorMs: number; ceilMs: number }+const DAY_MS = 24 * 60 * 60 * 1000;-export function calendarWindowAt(nowMs: number, historyDays: number): CalendarWindow {- return { floorMs: nowMs - historyDays * DAY_MS, ceilMs: nowMs + CALENDAR_HORIZON_DAYS * DAY_MS };-}+export type CalendarWindowSide = 'before' | 'inside' | 'after';-/** 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';-}+export class CalendarSyncWindow {+ readonly floorMs: number;+ readonly ceilMs: number;-/**- * 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;-}+ constructor(readonly nowMs: number, historyDays: number) {+ this.floorMs = nowMs - historyDays * DAY_MS;+ this.ceilMs = nowMs + CALENDAR_HORIZON_DAYS * DAY_MS;+ }-export interface CalendarApplyIo<R extends { relPath: string }> {- signal?: AbortSignal;- render: (ev: CalendarEventData) => R | null;- existingPath: (eventId: string) => Promise<string | null>;- fallbackPath: (ev: CalendarEventData) => string;- dropPage: (relPath: string) => Promise<void>;- importPage: (rendered: R) => Promise<void>;+ /** timeMin/timeMax for a windowed list that starts at `fromMs` (the floor unless given). */+ listBounds(fromMs: number = this.floorMs): { timeMinIso: string; timeMaxIso: string } {+ return { timeMinIso: new Date(fromMs).toISOString(), timeMaxIso: new Date(this.ceilMs).toISOString() };+ }++ /**+ * An event is `after` the range when it starts at or past the ceiling and+ * `before` it when it ends at or before the floor (its start stands in for an+ * end that does not parse). A date that does not parse never moves an event+ * out of the range, so a cancelled skeleton with no dates stays `inside`.+ */+ side(startIso: string, endIso: string): CalendarWindowSide {+ const start = Date.parse(startIso);+ if (start >= this.ceilMs) return 'after';+ const end = Date.parse(endIso);+ const finish = Number.isNaN(end) ? start : end;+ return finish <= this.floorMs ? 'before' : 'inside';+ }++ /**+ * Where the catch-up list for unchanged instances should start, or null when+ * none is due. A sweep that listed the whole window already saw them. State+ * with no recorded horizon (saved before it existed) is listed from now, as+ * its last full list is of unknown age; a recorded horizon is listed from+ * once the ceiling has moved at least a day past it.+ */+ coverageStartMs(horizonMs: number | null | undefined, listedWholeWindow: boolean): number | null {+ if (listedWholeWindow) return null;+ if (typeof horizonMs !== 'number') return this.nowMs;+ return this.ceilMs - horizonMs >= DAY_MS ? horizonMs : null;+ }++ /** Whether an event starting at `startIso` begins inside [floor, ceiling). */+ startsInside(startIso: string | null): boolean {+ const start = Date.parse(startIso ?? '');+ return start >= this.floorMs && start < this.ceilMs;+ }}+/** The page change one listed event calls for. */+export type CalendarPageChange =+ | { kind: 'write'; removeFirst: string | null }+ | { kind: 'remove'; relPath: string }+ | { kind: 'ignore' };+/**- * 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.+ * Decide the page change for one listed event.+ *+ * `targetPath` is where the event renders, or null for a cancellation.+ * `currentPath` is the page already holding this event id, if any. Ids are+ * stable while paths derive from the date and title. A cancellation removes+ * the event's page wherever the event sits in time. An event that ended+ * before the floor is ignored, so history imported while it was in range is+ * kept as it is. One that now starts past the ceiling loses its page; the+ * catch-up list brings it back once it is in range. Anything else is+ * written, after removing a copy at an older path.*/-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.dropPage(existingPath ?? io.fallbackPath(ev)); continue; }- if (placement === 'future') {- outside++;- if (existingPath) await io.dropPage(existingPath);- continue;- }- if (existingPath && existingPath !== rendered.relPath) await io.dropPage(existingPath);- await io.importPage(rendered);- }- return outside;+export function planCalendarPage(side: CalendarWindowSide, targetPath: string | null, currentPath: string | null,+ fallbackPath: string): CalendarPageChange {+ if (targetPath === null) return { kind: 'remove', relPath: currentPath ?? fallbackPath };+ if (side === 'before') return { kind: 'ignore' };+ if (side === 'after') return currentPath ? { kind: 'remove', relPath: currentPath } : { kind: 'ignore' };+ return { kind: 'write', removeFirst: currentPath !== null && currentPath !== targetPath ? currentPath : null };}-/** 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;- });+/**+ * Pages written by the sweep (they carry an event id) whose event starts+ * inside `window` but which a complete `--full` list of that window did not+ * name: deleted or cancelled upstream since the last list.+ */+export function unlistedCalendarPages<T extends { event_id: string | null; start_iso: string | null }>(pages: T[],+ listedIds: ReadonlySet<string>, window: CalendarSyncWindow): T[] {+ return pages.filter(page => page.event_id !== null && !listedIds.has(page.event_id) && window.startsInside(page.start_iso));}diff --git a/src/core/google/google-source.ts b/src/core/google/google-source.tsindex 05db4149cd..f5513b8d31 100644--- a/src/core/google/google-source.ts+++ b/src/core/google/google-source.ts@@ -33,7 +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 { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, unlistedCalendarPages } 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';@@ -61,6 +61,7 @@ import {import {ALL_GOOGLE_SERVICES,DEFAULT_CALENDAR_ID,+ type CalendarEventData,type GmailThreadData,type GoogleService,type GoogleSourceConfig,@@ -460,10 +461,9 @@ async function sweepCalendar(summary: GoogleSyncSummary,countedSlugs: Set<string>,): Promise<void> {- 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 } : {};+ const range = new CalendarSyncWindow(Date.now(), deps.cfg.historyDays);+ const list = (query: { syncToken: string } | { timeMinIso: string; timeMaxIso: string }) =>+ calendar.listEvents(deps.cfg.account, { calendarId: deps.cfg.calendarId, ...query, ...(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@@ -475,73 +475,86 @@ async function sweepCalendar();state.calendar_sync_token = null;}- let listedWindow = deps.opts.full || !state.calendar_sync_token;+ const deltaToken = deps.opts.full ? null : state.calendar_sync_token;+ let wholeWindow = deltaToken === null;let result;try {- result = await calendar.listEvents(deps.cfg.account, {- calendarId: deps.cfg.calendarId,- ...(listedWindow ? windowOpts : { syncToken: state.calendar_sync_token }),- ...signalOpts,- });+ result = await list(deltaToken === null ? range.listBounds() : { syncToken: deltaToken });} catch (e) {- if (e instanceof GoogleCursorExpiredError) {- deps.log('[google] calendar syncToken expired; windowed re-list');- state.calendar_sync_token = null;- listedWindow = true;- result = await calendar.listEvents(deps.cfg.account, { calendarId: deps.cfg.calendarId, ...windowOpts, ...signalOpts });- } else {- throw e;- }+ if (!(e instanceof GoogleCursorExpiredError)) throw e;+ deps.log('[google] calendar syncToken expired; windowed re-list');+ state.calendar_sync_token = null;+ wholeWindow = true;+ result = await list(range.listBounds());}- const io: CalendarApplyIo<NonNullable<ReturnType<typeof renderCalendarEventPage>>> = {- signal: deps.opts.signal,- render: renderCalendarEventPage,- existingPath: eventId => calendarPageRelPathByEventId(deps, eventId),- fallbackPath: calendarRelPath,- dropPage: 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;+ const tally = { outside: 0 };+ const sweepCtx = { activePack, summary, countedSlugs };+ if (!await applyCalendarList(deps, result.events, range, sweepCtx, tally)) 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;+ // A delta never names unchanged instances that crossed the leading edge+ // since the last list, so list that stretch on its own. This list's sync+ // token is discarded (the delta cursor stays authoritative), and the+ // horizon moves only once a list really reached the ceiling.+ const catchUpFrom = range.coverageStartMs(state.calendar_horizon_ms, wholeWindow);+ if (catchUpFrom !== null) {+ const caughtUp = await list(range.listBounds(catchUpFrom));+ if (!await applyCalendarList(deps, caughtUp.events, range, sweepCtx, tally)) return;+ }+ if (wholeWindow || catchUpFrom !== null) state.calendar_horizon_ms = range.ceilMs;+ if (tally.outside > 0) {+ deps.log(`[google] calendar: ${tally.outside} listed event(s) outside the sync window (${deps.cfg.historyDays} days back, ${CALENDAR_HORIZON_DAYS} ahead) were not imported`);}- 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);+ if (deps.opts.full) await reconcileCalendarWindow(deps, new Set(result.events.map(ev => ev.id)), range, 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.+ * 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.*/-async function reconcileCalendarWindow(deps: GoogleSyncDeps, listedIds: ReadonlySet<string>, window: CalendarWindow,+async function applyCalendarList(deps: GoogleSyncDeps, events: CalendarEventData[], range: CalendarSyncWindow,+ ctx: { activePack: ActivePack; summary: GoogleSyncSummary; countedSlugs: Set<string> }, tally: { outside: number }): Promise<boolean> {+ for (const ev of events) {+ if (deps.opts.signal?.aborted) return false;+ const page = renderCalendarEventPage(ev);+ const side = page ? range.side(ev.startIso, ev.endIso) : 'inside';+ if (side !== 'inside') tally.outside++;+ // Nothing is written or removed for an event that already ended before+ // the window, so skip the page lookup.+ if (side === 'before') continue;+ const change = planCalendarPage(side, page?.relPath ?? null, await calendarPageRelPathByEventId(deps, ev.id), calendarRelPath(ev));+ if (change.kind === 'remove') await deletePageByRelPath(deps, change.relPath, ctx.summary);+ if (change.kind !== 'write' || !page) continue;+ if (change.removeFirst) await deletePageByRelPath(deps, change.removeFirst, ctx.summary);+ await importRendered(deps, page.relPath, page.markdown, ctx.activePack, ctx.summary, ctx.countedSlugs);+ }+ return !deps.opts.signal?.aborted;+}++/**+ * `--full`: delete the sweep's calendar pages whose event starts inside the+ * listed window but that the complete list no longer names (cancelled or+ * deleted upstream). Nothing before the floor qualifies. More than 200 at+ * once needs GBRAIN_ALLOW_MASS_RECONCILE, and a refusal marks the run partial.+ */+async function reconcileCalendarWindow(deps: GoogleSyncDeps, listedIds: ReadonlySet<string>, range: CalendarSyncWindow,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+ const pages = await deps.engine.executeRaw<{ source_path: string | null; event_id: string | null; start_iso: string | null }>(+ `SELECT source_path, frontmatter->>'event_id' AS event_id, frontmatter->>'start' AS start_iso FROM pagesWHERE 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 gone = unlistedCalendarPages(pages, listedIds, range).flatMap(page => page.source_path === null ? [] : [page.source_path]);+ if (gone.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}`);+ if (gone.length > 200 && !massReconcileAllowed()) {+ deps.log(`[google] mass-delete guard refused ${gone.length} deletes for source ${deps.sourceId}`);summary.status = 'partial';return;}- for (const page of stale) await deletePageByRelPath(deps, page.source_path!, summary);+ for (const relPath of gone) await deletePageByRelPath(deps, relPath, summary);}// ── Gmail sweep ──────────────────────────────────────────────────────────────diff --git a/src/core/google/types.ts b/src/core/google/types.tsindex ee13a77e00..9a76831432 100644--- a/src/core/google/types.ts+++ b/src/core/google/types.ts@@ -100,10 +100,10 @@ export interface GoogleSourceState {*/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.+ * Ceiling (epoch ms) of the last calendar list that reached the window's+ * leading edge. Deltas omit unchanged events, so once the edge is a day+ * past this value the sweep lists the gap (calendar-window.ts). Missing on+ * state saved before it existed, which is listed from now instead.*/calendar_horizon_ms?: number | null;contacts_sync_token: string | null;diff --git a/test/google-calendar-window.test.ts b/test/google-calendar-window.test.tsnew file mode 100644index 0000000000..d63ea168aa--- /dev/null+++ b/test/google-calendar-window.test.ts@@ -0,0 +1,92 @@+/**+ * Pure rules of the calendar sync window (src/core/google/calendar-window.ts).+ *+ * Protects the boundary semantics the sweep relies on (#5442): Google's+ * timeMin is compared with an event's END and timeMax with its START, so an+ * event touching either edge lands on a fixed side, and dates that do not+ * parse never push an event out of the window. Also pins when a catch-up list+ * is due, the --full reconcile scope, and the page change each listed event+ * calls for. The sweep-level behavior is in test/google-source-reconcile.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, unlistedCalendarPages } from '../src/core/google/calendar-window.ts';++const DAY = 86_400_000;+const NOW = Date.UTC(2026, 9, 6, 12, 0, 0);+const win = new CalendarSyncWindow(NOW, 30);+const iso = (ms: number) => new Date(ms).toISOString();++describe('CalendarSyncWindow', () => {+ test('spans historyDays back to the 60-day horizon', () => {+ expect(CALENDAR_HORIZON_DAYS).toBe(60);+ expect(win.floorMs).toBe(NOW - 30 * DAY);+ expect(win.ceilMs).toBe(NOW + 60 * DAY);+ expect(win.listBounds()).toEqual({ timeMinIso: iso(NOW - 30 * DAY), timeMaxIso: iso(NOW + 60 * DAY) });+ expect(win.listBounds(NOW + 10 * DAY).timeMinIso).toBe(iso(NOW + 10 * DAY));+ });++ test('side compares the end with the floor and the start with the ceiling, edges included', () => {+ expect(win.side(iso(win.floorMs - DAY), iso(win.floorMs))).toBe('before');+ expect(win.side(iso(win.floorMs - DAY), iso(win.floorMs + 1))).toBe('inside');+ expect(win.side(iso(win.ceilMs - 1), iso(win.ceilMs + DAY))).toBe('inside');+ expect(win.side(iso(win.ceilMs), iso(win.ceilMs + DAY))).toBe('after');+ });++ test('unparseable dates never move an event out of the window', () => {+ expect(win.side('', '')).toBe('inside');+ expect(win.side('not-a-date', iso(win.floorMs - DAY))).toBe('before');+ expect(win.side(iso(win.floorMs - 2 * DAY), 'not-a-date')).toBe('before');+ expect(win.side(iso(NOW), 'not-a-date')).toBe('inside');+ });++ test('a catch-up list is due for missing horizons and day-old ones, never after a whole-window list', () => {+ expect(win.coverageStartMs(null, false)).toBe(NOW);+ expect(win.coverageStartMs(undefined, false)).toBe(NOW);+ expect(win.coverageStartMs(win.ceilMs - DAY, false)).toBe(win.ceilMs - DAY);+ expect(win.coverageStartMs(win.ceilMs - DAY + 1, false)).toBeNull();+ expect(win.coverageStartMs(null, true)).toBeNull();+ expect(win.coverageStartMs(win.ceilMs - 30 * DAY, true)).toBeNull();+ });++ test('startsInside is [floor, ceiling) on the start alone', () => {+ expect(win.startsInside(iso(win.floorMs))).toBe(true);+ expect(win.startsInside(iso(win.floorMs - 1))).toBe(false);+ expect(win.startsInside(iso(win.ceilMs - 1))).toBe(true);+ expect(win.startsInside(iso(win.ceilMs))).toBe(false);+ expect(win.startsInside(null)).toBe(false);+ });+});++describe('planCalendarPage', () => {+ test('cancellations remove the page wherever the event sits, falling back to the rendered path', () => {+ expect(planCalendarPage('after', null, 'calendar/a.md', 'calendar/b.md')).toEqual({ kind: 'remove', relPath: 'calendar/a.md' });+ expect(planCalendarPage('inside', null, null, 'calendar/b.md')).toEqual({ kind: 'remove', relPath: 'calendar/b.md' });+ });++ test('outside the window: history is left alone, a page past the horizon is removed', () => {+ expect(planCalendarPage('before', 'calendar/new.md', 'calendar/old.md', 'x')).toEqual({ kind: 'ignore' });+ expect(planCalendarPage('after', 'calendar/new.md', 'calendar/old.md', 'x')).toEqual({ kind: 'remove', relPath: 'calendar/old.md' });+ expect(planCalendarPage('after', 'calendar/new.md', null, 'x')).toEqual({ kind: 'ignore' });+ });++ test('inside the window: write, removing a copy at another path first', () => {+ expect(planCalendarPage('inside', 'calendar/new.md', 'calendar/old.md', 'x')).toEqual({ kind: 'write', removeFirst: 'calendar/old.md' });+ expect(planCalendarPage('inside', 'calendar/new.md', 'calendar/new.md', 'x')).toEqual({ kind: 'write', removeFirst: null });+ expect(planCalendarPage('inside', 'calendar/new.md', null, 'x')).toEqual({ kind: 'write', removeFirst: null });+ });+});++describe('unlistedCalendarPages', () => {+ test('keeps only sweep pages that start inside the window and were not listed', () => {+ const page = (event_id: string | null, startMs: number) => ({ event_id, start_iso: iso(startMs) });+ const pages = [+ page('listed', NOW + DAY),+ page('dropped', NOW + 2 * DAY),+ page('aged', win.floorMs - DAY),+ page('far', win.ceilMs + DAY),+ page(null, NOW + 3 * DAY),+ { event_id: 'undated', start_iso: null },+ ];+ expect(unlistedCalendarPages(pages, new Set(['listed']), win).map((p) => p.event_id)).toEqual(['dropped']);+ });+});diff --git a/test/google-source-materialize.test.ts b/test/google-source-materialize.test.tsindex e6de8c636a..a36bef072a 100644--- a/test/google-source-materialize.test.ts+++ b/test/google-source-materialize.test.ts@@ -642,77 +642,6 @@ 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 ac50c7a210..b71721c951 100644--- a/test/google-source-reconcile.test.ts+++ b/test/google-source-reconcile.test.ts@@ -105,10 +105,11 @@ 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;+ /**+ * Sees every timeMin/timeMax (non-delta) calendar list before it is served;+ * returning 'fail' answers that list with HTTP 400.+ */+ calendarRangeHook?: (query: URLSearchParams) => 'fail' | void;/** Counters so each windowed/full re-list mints a DISTINCT sync token. */calendarWindowedLists: number;contactsFullLists: number;@@ -131,7 +132,6 @@ function emptyFx(): FakeGoogle {calendarEvents: [],calendarDelta: [],calendarExpireSyncToken: false,- calendarFailWindowed: false,calendarWindowedLists: 0,contactsFullLists: 0,calls: [],@@ -213,8 +213,7 @@ 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?.();+ if (fx.calendarRangeHook?.(u.searchParams) === 'fail') return json({ error: { code: 400, message: 'Bad Request' } }, 400);fx.calendarWindowedLists++;return json({ items: fx.calendarEvents, nextSyncToken: `cal-sync-w${fx.calendarWindowedLists}` });}@@ -801,7 +800,7 @@ describe('syncToken 410 recovery', () => {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')!);+ const coverageMin = Date.parse(calendarQueries(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');@@ -925,428 +924,341 @@ 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 } = {}) {+// ── Calendar window (#5442) ──────────────────────────────────────────────────+// The source keeps pages for events from historyDays back to 60 days ahead.+// Google applies that range only to windowed lists: a syncToken delta has no+// timeMin/timeMax, and with singleEvents=true a touched recurring series comes+// back as every expanded instance. These cases pin the sweep's own filter on+// every path, the catch-up list for instances crossing the leading edge, and+// the --full reconcile scope.+//+// The fake serves fx.calendarEvents for every timeMin/timeMax list and+// fx.calendarDelta for every delta, without filtering, exactly like the+// unfiltered delta Google returns.++const DAY = 86_400_000;++/** A confirmed one-hour meeting `startOffsetDays` from NOW_MS. */+function meeting(id: string, startOffsetDays: number, opts: { title?: string; lengthMs?: number; status?: string } = {}) {+ const startMs = NOW_MS + startOffsetDays * DAY;return {id,- status: 'confirmed',- summary: over.summary ?? 'Weekly zephyr sync',+ status: opts.status ?? 'confirmed',+ summary: opts.title ?? `Zephyr meeting ${id}`,start: { dateTime: new Date(startMs).toISOString() },- end: { dateTime: new Date(startMs + (over.durationMs ?? 3_600_000)).toISOString() },+ end: { dateTime: new Date(startMs + (opts.lengthMs ?? 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`,+/** Live calendar pages keyed by event id (pages without one keyed by slug). */+async function calendarPages(): Promise<Map<string, { slug: string; title: string }>> {+ const rows = await engine.executeRaw<{ slug: string; title: string; event_id: string | null }>(+ `SELECT slug, title, frontmatter->>'event_id' AS event_id FROM pages+ WHERE source_id = 'gsrc' AND deleted_at IS NULL AND slug LIKE 'calendar/%'`,);- return rows.map((r) => r.slug);+ return new Map(rows.map((r) => [r.event_id ?? r.slug, { slug: r.slug, title: r.title }]));}-function calendarCallParams(fx: FakeGoogle): URLSearchParams[] {+/** Query strings of the calendar list calls the sweep made, in order. */+function calendarQueries(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> {+function storeHorizon(dir: string, horizonMs: number | null): void {+ writeFileSync(googleStateFile(dir), JSON.stringify({ ...readGoogleState(dir), calendar_horizon_ms: horizonMs }), 'utf-8');+}++const near = (actualMs: number, expectedMs: number, toleranceMs = 120_000): boolean => Math.abs(actualMs - expectedMs) < toleranceMs;++/** A page the sweep would have written for `eventId` (or a hand-made one when null), at slug.md. */+async function seedMeetingPage(slug: string, eventId: string | null, startOffsetDays: number): Promise<void> {+ const startMs = NOW_MS + startOffsetDays * DAY;await engine.putPage(slug,{type: 'meeting',- title: 'Weekly zephyr sync',- compiled_truth: 'A seeded meeting.',+ title: `Seeded ${slug.split('/').pop()}`,+ compiled_truth: 'Seeded for the calendar window tests.',frontmatter: {- ...(eventId ? { event_id: eventId } : {}),+ ...(eventId === null ? {} : { 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],- );+ await engine.executeRaw(`UPDATE pages SET source_path = slug || '.md' WHERE source_id = 'gsrc' AND slug = $1`, [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 });- }+/** Runs `body` against a fresh google source directory with an isolated GBRAIN_HOME. */+async function withCalendarSource(body: (h: { dir: string; fx: FakeGoogle; vault: FakeVault }) => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gsrc-calwindow-'));+ try {+ await insertGoogleSource(dir);+ await withHome(() => body({ dir, fx: emptyFx(), vault: makeVault() }));+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++describe('calendar window (#5442)', () => {+ test('a delta full of series instances materializes only those inside the window', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ fx.calendarEvents = [meeting('seed_tomorrow', 1)];+ await sweep(dir, fx, vault, {}, 'calendar');++ fx.calendarDelta = [+ meeting('inst_4y_ago', -4 * 365),+ meeting('inst_ended_before_floor', -91),+ // Starts before the 90-day floor but ends after it: inside, as Google's timeMin compares the end.+ meeting('inst_spans_floor', -95, { lengthMs: 10 * DAY }),+ meeting('inst_next_week', 7),+ meeting('inst_day_59', 59),+ meeting('inst_day_61', 61),+ meeting('inst_8y_ahead', 8 * 365),+ ];+ const { result, err } = await capturedStderr(() => sweep(dir, fx, vault, {}, 'calendar'));++ expect(result.status).not.toBe('partial');+ expect(result.added).toBe(3);+ expect([...(await calendarPages()).keys()].sort()).toEqual(['inst_day_59', 'inst_next_week', 'inst_spans_floor', 'seed_tomorrow']);+ expect(err).toContain('[google] calendar: 4 listed event(s) outside the sync window (90 days back, 60 ahead) were not imported');+ expect(readGoogleState(dir).calendar_sync_token).toBe('cal-sync-delta');+ });});- 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('negative control: a delta with only in-window changes logs no skips and imports them all', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ await sweep(dir, fx, vault, {}, 'calendar');+ fx.calendarDelta = [meeting('only_soon', 2), meeting('only_recent', -2)];+ const { result, err } = await capturedStderr(() => sweep(dir, fx, vault, {}, 'calendar'));+ expect(result.added).toBe(2);+ expect(err).not.toContain('outside the sync window');+ });});- 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);+ test('a move past the horizon removes the page; a change to aged-out history leaves its page as it was; a cancellation always removes', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ fx.calendarEvents = [meeting('old_offsite', -150, { title: 'Old offsite' }), meeting('old_cancelled', -160), meeting('next_review', 12)];+ expect((await sweep(dir, fx, vault, {}, 'calendar', { cfg: { g_history_days: 365 } })).added).toBe(3);+ const before = await calendarPages();++ fx.calendarDelta = [+ meeting('old_offsite', -150, { title: 'Old offsite (renamed)' }),+ meeting('old_cancelled', -160, { status: 'cancelled' }),+ meeting('next_review', 120),+ ];+ const result = await sweep(dir, fx, vault, {}, 'calendar');++ expect(result.added).toBe(0);+ expect(result.deleted).toBe(2);+ const after = await calendarPages();+ expect([...after.keys()]).toEqual(['old_offsite']);+ expect(after.get('old_offsite')).toEqual(before.get('old_offsite')!);+ expect(existsSync(join(dir, `${before.get('next_review')!.slug}.md`))).toBe(false);+ });+ });- // 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);+ test('a cancelled skeleton (id and status only) removes its own page and nothing else', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ fx.calendarEvents = [meeting('keep_me', 3), meeting('drop_me', 4)];+ await sweep(dir, fx, vault, {}, 'calendar');+ fx.calendarDelta = [{ id: 'drop_me', status: 'cancelled' }];+ const result = await sweep(dir, fx, vault, {}, 'calendar');+ expect(result.deleted).toBe(1);+ expect([...(await calendarPages()).keys()]).toEqual(['keep_me']);+ });+ });- // 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 lagging horizon gets one catch-up list from the horizon to the ceiling; the delta token stays the cursor', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ await sweep(dir, fx, vault, {}, 'calendar');+ expect(calendarQueries(fx)).toHaveLength(1);+ expect(near(readGoogleState(dir).calendar_horizon_ms!, Date.now() + 60 * DAY)).toBe(true);++ const lagging = NOW_MS + 48 * DAY;+ storeHorizon(dir, lagging);+ fx.calls = [];+ fx.calendarEvents = [meeting('crossed_edge', 52, { title: 'Crossed the edge' })];+ const result = await sweep(dir, fx, vault, {}, 'calendar');++ expect(result.added).toBe(1);+ const [delta, catchUp, ...rest] = calendarQueries(fx);+ expect(rest).toHaveLength(0);+ expect(delta.get('syncToken')).toBe('cal-sync-w1');+ expect(catchUp.get('syncToken')).toBeNull();+ expect(catchUp.get('timeMin')).toBe(new Date(lagging).toISOString());+ expect(near(Date.parse(catchUp.get('timeMax')!), Date.now() + 60 * DAY)).toBe(true);+ const state = readGoogleState(dir);+ expect(state.calendar_sync_token).toBe('cal-sync-delta');+ expect(near(state.calendar_horizon_ms!, Date.now() + 60 * DAY)).toBe(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 horizon less than a day behind is neither listed nor advanced, so short gaps add up to a catch-up list', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const ceiling = NOW_MS + 60 * DAY;++ const hoursBehind = ceiling - 20 * 3_600_000;+ storeHorizon(dir, hoursBehind);+ fx.calls = [];+ await sweep(dir, fx, vault, {}, 'calendar');+ expect(calendarQueries(fx)).toHaveLength(1);+ expect(readGoogleState(dir).calendar_horizon_ms).toBe(hoursBehind);++ const dayBehind = ceiling - 26 * 3_600_000;+ storeHorizon(dir, dayBehind);+ fx.calls = [];+ await sweep(dir, fx, vault, {}, 'calendar');+ const queries = calendarQueries(fx);+ expect(queries).toHaveLength(2);+ expect(queries[1].get('timeMin')).toBe(new Date(dayBehind).toISOString());+ expect(readGoogleState(dir).calendar_horizon_ms!).toBeGreaterThan(ceiling - 60_000);+ });});- 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 failed catch-up list marks the sweep partial and keeps the horizon; the next sweep catches up', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const lagging = NOW_MS + 45 * DAY;+ storeHorizon(dir, lagging);+ fx.calendarEvents = [meeting('late_arrival', 50)];+ fx.calendarRangeHook = () => 'fail';++ const failed = await sweep(dir, fx, vault, {}, 'calendar');+ expect(failed.status).toBe('partial');+ expect(readGoogleState(dir).calendar_horizon_ms).toBe(lagging);+ expect((await calendarPages()).size).toBe(0);++ fx.calendarRangeHook = undefined;+ const retried = await sweep(dir, fx, vault, {}, 'calendar');+ expect(retried.status).not.toBe('partial');+ expect([...(await calendarPages()).keys()]).toEqual(['late_arrival']);+ expect(readGoogleState(dir).calendar_horizon_ms!).toBeGreaterThan(lagging);+ });});- 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('an abort during the catch-up list keeps the horizon, and an aborted --full deletes nothing', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const lagging = NOW_MS + 45 * DAY;+ storeHorizon(dir, lagging);+ fx.calendarEvents = [meeting('never_lands', 50)];+ const stop = new AbortController();+ fx.calendarRangeHook = () => { stop.abort(); };++ const aborted = await sweep(dir, fx, vault, { signal: stop.signal }, 'calendar');+ expect(aborted.status).toBe('partial');+ expect(readGoogleState(dir).calendar_horizon_ms).toBe(lagging);+ expect((await calendarPages()).size).toBe(0);++ await seedMeetingPage('calendar/seeded/unlisted-but-aborted', 'unlisted_evt', 6);+ const stopFull = new AbortController();+ fx.calendarRangeHook = () => { stopFull.abort(); };+ const abortedFull = await sweep(dir, fx, vault, { full: true, signal: stopFull.signal }, 'calendar');+ expect(abortedFull.status).toBe('partial');+ expect([...(await calendarPages()).keys()]).toEqual(['unlisted_evt']);+ });});- 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('an expired token re-lists the whole window, which counts as caught up', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ await sweep(dir, fx, vault, {}, 'calendar');+ const lagging = NOW_MS + 30 * DAY;+ storeHorizon(dir, lagging);+ fx.calls = [];+ fx.calendarExpireSyncToken = true;+ await sweep(dir, fx, vault, {}, 'calendar');+ const [expired, relist, ...rest] = calendarQueries(fx);+ expect(rest).toHaveLength(0);+ expect(expired.get('syncToken')).toBe('cal-sync-w1');+ expect(near(Date.parse(relist.get('timeMin')!), Date.now() - 90 * DAY)).toBe(true);+ expect(readGoogleState(dir).calendar_horizon_ms!).toBeGreaterThan(lagging);+ });});- 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('the catch-up list reads the secondary calendar the source is bound to', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ const team = '[email protected]';+ await sweep(dir, fx, vault, {}, 'calendar', { cfg: { g_calendar_id: team } });+ storeHorizon(dir, NOW_MS + 40 * DAY);+ fx.calls = [];+ await sweep(dir, fx, vault, {}, 'calendar', { cfg: { g_calendar_id: team } });+ const paths = fx.calls.filter((c) => c.includes('/calendars/')).map((c) => new URL(c, 'https://www.googleapis.com').pathname);+ expect(paths).toEqual([0, 1].map(() => `/calendar/v3/calendars/${encodeURIComponent(team)}/events`));+ });});- 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);+ test('state saved before horizons existed lists [now, ceiling] once; a failed list leaves it unset for a retry', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {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 });- }+ fx.calendarEvents = [meeting('unchanged_since_legacy', 35)];+ fx.calendarRangeHook = () => 'fail';+ expect((await sweep(dir, fx, vault, {}, 'calendar')).status).toBe('partial');+ expect(readGoogleState(dir).calendar_horizon_ms ?? null).toBeNull();++ fx.calendarRangeHook = undefined;+ fx.calls = [];+ const result = await sweep(dir, fx, vault, {}, 'calendar');+ expect(result.added).toBe(1);+ const [, coverage] = calendarQueries(fx);+ expect(near(Date.parse(coverage.get('timeMin')!), Date.now())).toBe(true);+ expect(near(Date.parse(coverage.get('timeMax')!), Date.now() + 60 * DAY)).toBe(true);+ expect(near(readGoogleState(dir).calendar_horizon_ms!, Date.now() + 60 * DAY)).toBe(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('--full deletes in-window pages the list no longer names and keeps every page outside that scope', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ fx.calendarEvents = [meeting('still_listed', 2)];+ await seedMeetingPage('calendar/seeded/upcoming-cancelled', 'gone_upcoming', 8);+ await seedMeetingPage('calendar/seeded/recent-deleted', 'gone_recent', -20);+ await seedMeetingPage('calendar/seeded/before-floor', 'history_evt', -180);+ await seedMeetingPage('calendar/seeded/beyond-horizon', 'far_evt', 9 * 365);+ await seedMeetingPage('calendar/seeded/hand-written', null, 5);++ const result = await sweep(dir, fx, vault, { full: true }, 'calendar');++ expect(result.status).not.toBe('partial');+ expect(result.deleted).toBe(2);+ expect([...(await calendarPages()).keys()].sort()).toEqual(+ ['calendar/seeded/hand-written', 'far_evt', 'history_evt', 'still_listed'].sort(),+ );+ });});- 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 after historyDays shrinks keeps pages from the old, wider window', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ fx.calendarEvents = [meeting('wide_window_only', -250), meeting('both_windows', -40)];+ expect((await sweep(dir, fx, vault, { full: true }, 'calendar', { cfg: { g_history_days: 365 } })).added).toBe(2);+ fx.calendarEvents = [meeting('both_windows', -40)];+ const result = await sweep(dir, fx, vault, { full: true }, 'calendar');+ expect(result.deleted).toBe(0);+ expect([...(await calendarPages()).keys()].sort()).toEqual(['both_windows', 'wide_window_only']);+ });});- 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);+ test('--full refuses more than 200 calendar deletions without GBRAIN_ALLOW_MASS_RECONCILE and reports partial', async () => {+ await withCalendarSource(async ({ dir, fx, vault }) => {+ for (let i = 0; i < 205; i++) await seedMeetingPage(`calendar/seeded/bulk-${i}`, `bulk_${i}`, 1 + (i % 40));- 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 });- }+ const { result: refused, err } = await capturedStderr(() => sweep(dir, fx, vault, { full: true }, 'calendar'));+ expect(refused.status).toBe('partial');+ expect(refused.deleted).toBe(0);+ expect(err).toContain('mass-delete guard refused 205 deletes for source gsrc');+ expect((await calendarPages()).size).toBe(205);++ const allowed = await withEnv({ GBRAIN_ALLOW_MASS_RECONCILE: '1' }, () => sweep(dir, fx, vault, { full: true }, 'calendar'));+ expect(allowed.deleted).toBe(205);+ expect((await calendarPages()).size).toBe(0);+ });});});