Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(google): --full reconciles calendar pages past the horizon; per-source g_future_days (#5442)

garrytan10b09ac1d243
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index 09e637745a..0f49f09511 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -24,7 +24,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `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` — 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/calendar-window.ts` — which calendar events a google source keeps pages for: `[now - historyDays, now + futureDays]` (`g_future_days`, 1..3650, default `CALENDAR_HORIZON_DAYS` = 60; the parsed `futureDays` leaf exists only when the key is set, so an unset knob leaves every existing source's connector identity unchanged), 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` and `startsAfter` are the `--full` reconcile tests. `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; `staleCalendarPages` adds the sweep pages starting at or past the ceiling, which no windowed list can name (#5442), and is what the `--full` reconcile deletes through. `people-calendar-sweep.ts` (the contacts and calendar sweeps, peeled from `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.md
index 26bdaf8c20..3a1a367919 100644
--- a/docs/guides/google-connect.md
+++ b/docs/guides/google-connect.md
@@ -130,7 +130,8 @@ the brain until you remove them — they are not reconciled automatically.
## Calendar window
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
+now (`--future-days`, the `g_future_days` config key, 1..3650, moves that
+horizon per source), 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
@@ -141,12 +142,14 @@ the range 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.
+deleted since), and the pages this source wrote for events that start at or
+past the horizon (instances a series edit imported years ahead before the
+window existed, or under a wider `g_future_days`). It never removes a page
+whose event starts before the window, so shrinking `--history-days` keeps
+your history, and it never touches a calendar page you wrote by hand. More
+than 200 removals in one run are refused, nothing is removed, and the run is
+reported partial; if that many are genuinely gone, run it once with
+`GBRAIN_ALLOW_MASS_RECONCILE=1`.
**Say to your agent:** *"re-sync my calendar from scratch"* (your agent runs
`gbrain sync --source <id> --full`).
diff --git a/src/core/google/calendar-window.ts b/src/core/google/calendar-window.ts
index 18eaacce3e..cb4d5c71ee 100644
--- a/src/core/google/calendar-window.ts
+++ b/src/core/google/calendar-window.ts
@@ -2,7 +2,7 @@
* Which calendar events a google source keeps pages for (#5442).
*
* The source mirrors one rolling range: from `historyDays` back to
- * `CALENDAR_HORIZON_DAYS` ahead. Google can only apply that range to a
+ * `futureDays` ahead (`g_future_days`, default `CALENDAR_HORIZON_DAYS`). 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
@@ -16,18 +16,22 @@
* `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.
+ * - which existing pages a complete `--full` list should drop
+ * (`staleCalendarPages`): sweep pages whose event starts inside the listed
+ * range but was not listed, and sweep pages whose event starts at or past
+ * the ceiling (a windowed list never names those, so they are only ever
+ * reconciled here). 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';
-/** How far ahead of now calendar pages are kept, in days. */
+/** How far ahead of now calendar pages are kept, in days, unless `g_future_days` says otherwise. */
export const CALENDAR_HORIZON_DAYS = 60;
+/** The largest `g_future_days` a source may ask for. */
+export const CALENDAR_FUTURE_DAYS_MAX = 3650;
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -37,9 +41,9 @@ export class CalendarSyncWindow {
readonly floorMs: number;
readonly ceilMs: number;
- constructor(readonly nowMs: number, historyDays: number) {
+ constructor(readonly nowMs: number, historyDays: number, readonly futureDays: number = CALENDAR_HORIZON_DAYS) {
this.floorMs = nowMs - historyDays * DAY_MS;
- this.ceilMs = nowMs + CALENDAR_HORIZON_DAYS * DAY_MS;
+ this.ceilMs = nowMs + futureDays * DAY_MS;
}
/** timeMin/timeMax for a windowed list that starts at `fromMs` (the floor unless given). */
@@ -79,6 +83,11 @@ export class CalendarSyncWindow {
const start = Date.parse(startIso ?? '');
return start >= this.floorMs && start < this.ceilMs;
}
+
+ /** Whether an event starting at `startIso` begins at or past the ceiling (an unparseable start never does). */
+ startsAfter(startIso: string | null): boolean {
+ return Date.parse(startIso ?? '') >= this.ceilMs;
+ }
}
/** The page change one listed event calls for. */
@@ -116,3 +125,17 @@ export function unlistedCalendarPages<T extends { event_id: string | null; start
listedIds: ReadonlySet<string>, window: CalendarSyncWindow): T[] {
return pages.filter(page => page.event_id !== null && !listedIds.has(page.event_id) && window.startsInside(page.start_iso));
}
+
+/**
+ * Every sweep page a complete `--full` list should remove: the unlisted
+ * in-window pages above, plus sweep pages whose event starts at or past the
+ * ceiling (#5442). A windowed list cannot name an event past its timeMax, so
+ * pages written beyond the horizon (before the window existed, or under a
+ * wider `g_future_days`) are reconciled here and nowhere else. Pages without
+ * an event id (hand-written) are never touched.
+ */
+export function staleCalendarPages<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
+ && (window.startsAfter(page.start_iso) || (!listedIds.has(page.event_id) && window.startsInside(page.start_iso))));
+}
diff --git a/src/core/google/people-calendar-sweep.ts b/src/core/google/people-calendar-sweep.ts
index 3b026c7e5d..e8d83d3ab3 100644
--- a/src/core/google/people-calendar-sweep.ts
+++ b/src/core/google/people-calendar-sweep.ts
@@ -7,7 +7,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, unlistedCalendarPages } from './calendar-window.ts';
+import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, staleCalendarPages } from './calendar-window.ts';
import { CalendarClient, GoogleCursorExpiredError, PeopleClient } from './google-clients.ts';
import { calendarRelPath, personSlugFromContact, renderCalendarEventPage, renderPersonPage } from './google-render.ts';
import { DEFAULT_CALENDAR_ID, type CalendarEventData, type GoogleSourceState } from './types.ts';
@@ -145,7 +145,7 @@ export async function sweepCalendar(
summary: GoogleSyncSummary,
countedSlugs: Set<string>,
): Promise<void> {
- const range = new CalendarSyncWindow(Date.now(), deps.cfg.historyDays);
+ const range = new CalendarSyncWindow(Date.now(), deps.cfg.historyDays, deps.cfg.futureDays ?? CALENDAR_HORIZON_DAYS);
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
@@ -189,7 +189,7 @@ export async function sweepCalendar(
}
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`);
+ deps.log(`[google] calendar: ${tally.outside} listed event(s) outside the sync window (${deps.cfg.historyDays} days back, ${range.futureDays} ahead) were not imported`);
}
if (deps.opts.full) await reconcileCalendarWindow(deps, new Set(result.events.map(ev => ev.id)), range, summary);
}
@@ -221,8 +221,10 @@ async function applyCalendarList(deps: GoogleSyncDeps, events: CalendarEventData
/**
* `--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.
+ * deleted upstream), and the sweep's pages whose event starts at or past the
+ * horizon (#5442: a windowed list never names those). Nothing before the
+ * floor qualifies. More than 200 at once needs GBRAIN_ALLOW_MASS_RECONCILE,
+ * and a refusal aborts the whole cleanup and marks the run partial.
*/
async function reconcileCalendarWindow(deps: GoogleSyncDeps, listedIds: ReadonlySet<string>, range: CalendarSyncWindow,
summary: GoogleSyncSummary): Promise<void> {
@@ -231,7 +233,7 @@ async function reconcileCalendarWindow(deps: GoogleSyncDeps, listedIds: Readonly
WHERE source_id = $1 AND deleted_at IS NULL AND slug LIKE 'calendar/%' AND frontmatter->>'event_id' IS NOT NULL`,
[deps.sourceId],
);
- const gone = unlistedCalendarPages(pages, listedIds, range).flatMap(page => page.source_path === null ? [] : [page.source_path]);
+ const gone = staleCalendarPages(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 (gone.length > 200 && !massReconcileAllowed()) {
diff --git a/src/core/google/source-config.ts b/src/core/google/source-config.ts
index 8a8b2383a3..47c3a26dbf 100644
--- a/src/core/google/source-config.ts
+++ b/src/core/google/source-config.ts
@@ -1,5 +1,6 @@
/** Parse a Google connector source's `sources.config`. Dependency-light so migrations and the connector identity can import it. */
import { ALL_GOOGLE_SERVICES, DEFAULT_CALENDAR_ID, type GoogleService, type GoogleSourceConfig } from './types.ts';
+import { CALENDAR_FUTURE_DAYS_MAX } from './calendar-window.ts';
export function parseGoogleSourceConfig(
config: Record<string, unknown>,
@@ -20,6 +21,13 @@ export function parseGoogleSourceConfig(
config.g_history_days > 0
? Math.min(3650, Math.floor(config.g_history_days))
: 90;
+ const futureDays =
+ typeof config.g_future_days === 'number' &&
+ Number.isFinite(config.g_future_days) &&
+ config.g_future_days >= 1 &&
+ config.g_future_days <= CALENDAR_FUTURE_DAYS_MAX
+ ? Math.floor(config.g_future_days)
+ : undefined;
const calendarId =
typeof config.g_calendar_id === 'string' && config.g_calendar_id.trim().length > 0
? config.g_calendar_id.trim()
@@ -32,6 +40,7 @@ export function parseGoogleSourceConfig(
account,
services: services.length > 0 ? services : [...ALL_GOOGLE_SERVICES],
historyDays,
+ ...(futureDays !== undefined ? { futureDays } : {}),
calendarId,
dir,
access,
diff --git a/src/core/google/types.ts b/src/core/google/types.ts
index 9a76831432..849d6911da 100644
--- a/src/core/google/types.ts
+++ b/src/core/google/types.ts
@@ -20,6 +20,13 @@ export interface GoogleSourceConfig {
services: GoogleService[];
/** Backfill/reconcile window in days (default 90). */
historyDays: number;
+ /**
+ * How far ahead calendar pages are kept, in days (`g_future_days`, 1..3650).
+ * Present only when the source sets it, so an unset knob leaves every
+ * existing source's connector identity unchanged; the sweep falls back to
+ * CALENDAR_HORIZON_DAYS.
+ */
+ futureDays?: number;
/** Calendar swept by this source (default DEFAULT_CALENDAR_ID). One calendar per
* source so each keeps its own sync token — point a second source at a
* secondary calendar id to ingest it too. */
diff --git a/src/core/persistence/connector-identity.ts b/src/core/persistence/connector-identity.ts
index 112b9bd46f..fa1304d37e 100644
--- a/src/core/persistence/connector-identity.ts
+++ b/src/core/persistence/connector-identity.ts
@@ -36,7 +36,7 @@ const underAuto = (config: GitHubSourceConfig): LeafClass => config.scope === 'a
*/
export const CONNECTOR_LEAF_RULES: { google: Record<string, LeafClass>; github: Record<string, Rule> } = {
google: {
- account: 'identity', services: 'identity', historyDays: 'identity', calendarId: 'identity', dir: 'identity',
+ account: 'identity', services: 'identity', historyDays: 'identity', futureDays: 'identity', calendarId: 'identity', dir: 'identity',
access: 'excluded', tokenCommand: 'excluded', tokenEnv: 'excluded',
},
github: {
diff --git a/test/google-calendar-window.test.ts b/test/google-calendar-window.test.ts
index d63ea168aa..40197301b0 100644
--- a/test/google-calendar-window.test.ts
+++ b/test/google-calendar-window.test.ts
@@ -9,7 +9,7 @@
* 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';
+import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow, planCalendarPage, staleCalendarPages, unlistedCalendarPages } from '../src/core/google/calendar-window.ts';
const DAY = 86_400_000;
const NOW = Date.UTC(2026, 9, 6, 12, 0, 0);
@@ -90,3 +90,32 @@ describe('unlistedCalendarPages', () => {
expect(unlistedCalendarPages(pages, new Set(['listed']), win).map((p) => p.event_id)).toEqual(['dropped']);
});
});
+
+describe('future horizon (#5442)', () => {
+ test('startsAfter is true from the ceiling on, and never for an unparseable start', () => {
+ expect(win.startsAfter(iso(win.ceilMs))).toBe(true);
+ expect(win.startsAfter(iso(win.ceilMs + DAY))).toBe(true);
+ expect(win.startsAfter(iso(win.ceilMs - 1))).toBe(false);
+ expect(win.startsAfter(null)).toBe(false);
+ expect(win.startsAfter('not a date')).toBe(false);
+ });
+
+ test('futureDays moves the ceiling; the default stays CALENDAR_HORIZON_DAYS', () => {
+ expect(new CalendarSyncWindow(NOW, 30, 180).ceilMs).toBe(NOW + 180 * DAY);
+ expect(new CalendarSyncWindow(NOW, 30).ceilMs).toBe(NOW + CALENDAR_HORIZON_DAYS * DAY);
+ });
+
+ test('staleCalendarPages: unlisted inside the window, or any sweep page past the ceiling; never history or hand-written pages', () => {
+ 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('at_ceiling', win.ceilMs),
+ page(null, win.ceilMs + 3 * DAY),
+ { event_id: 'undated', start_iso: null },
+ ];
+ expect(staleCalendarPages(pages, new Set(['listed', 'far']), win).map((p) => p.event_id).sort()).toEqual(['at_ceiling', 'dropped', 'far']);
+ });
+});
diff --git a/test/google-source-config.test.ts b/test/google-source-config.test.ts
index 6f830ec36b..3454d8f682 100644
--- a/test/google-source-config.test.ts
+++ b/test/google-source-config.test.ts
@@ -12,6 +12,7 @@
import { describe, expect, test } from 'bun:test';
import { parseGoogleSourceConfig } from '../src/core/google/google-source.ts';
+import { CALENDAR_HORIZON_DAYS, CalendarSyncWindow } from '../src/core/google/calendar-window.ts';
const DIR = '/tmp/gbrain-test-google-dir';
const base = { kind: 'google', g_account: '[email protected]', g_services: 'calendar' };
@@ -55,3 +56,23 @@ describe('parseGoogleSourceConfig — calendar selection', () => {
expect(cfg.access).toBe('vault');
});
});
+
+describe('parseGoogleSourceConfig — g_future_days (#5442)', () => {
+ test('is absent by default (existing sources keep their connector identity) and the window then reaches 60 days ahead', () => {
+ const cfg = parseGoogleSourceConfig({ ...base }, DIR);
+ expect(cfg.futureDays).toBeUndefined();
+ expect(new CalendarSyncWindow(0, 1, cfg.futureDays ?? CALENDAR_HORIZON_DAYS).ceilMs).toBe(60 * 86_400_000);
+ });
+
+ test('accepts 1..3650 whole days and floors fractions', () => {
+ expect(parseGoogleSourceConfig({ ...base, g_future_days: 1 }, DIR).futureDays).toBe(1);
+ expect(parseGoogleSourceConfig({ ...base, g_future_days: 180.9 }, DIR).futureDays).toBe(180);
+ expect(parseGoogleSourceConfig({ ...base, g_future_days: 3650 }, DIR).futureDays).toBe(3650);
+ });
+
+ test('ignores zero, negative, too large, NaN or non-numeric values (the default horizon applies)', () => {
+ for (const bad of [0, -5, 5000, Number.NaN, '90', null, undefined, {}]) {
+ expect(parseGoogleSourceConfig({ ...base, g_future_days: bad }, DIR).futureDays).toBeUndefined();
+ }
+ });
+});
diff --git a/test/google-source-reconcile.test.ts b/test/google-source-reconcile.test.ts
index 2aee02f5a3..5e4b79e2c1 100644
--- a/test/google-source-reconcile.test.ts
+++ b/test/google-source-reconcile.test.ts
@@ -1227,13 +1227,58 @@ describe('calendar window (#5442)', () => {
const result = await sweep(dir, fx, vault, { full: true }, 'calendar');
expect(result.status).not.toBe('partial');
- expect(result.deleted).toBe(2);
+ // P4.2 (#5442, contract change): a sweep page past the horizon is now reconciled too,
+ // so `far_evt` goes with the two unlisted in-window pages; history and hand-written stay.
+ expect(result.deleted).toBe(3);
expect([...(await calendarPages()).keys()].sort()).toEqual(
- ['calendar/seeded/hand-written', 'far_evt', 'history_evt', 'still_listed'].sort(),
+ ['calendar/seeded/hand-written', 'history_evt', 'still_listed'].sort(),
);
});
});
+ test('--full removes sweep pages that start at or past the horizon and keeps pages inside it (#5442)', async () => {
+ await withCalendarSource(async ({ dir, fx, vault }) => {
+ fx.calendarEvents = [meeting('soon', 30), meeting('inside_59', 59)];
+ expect((await sweep(dir, fx, vault, {}, 'calendar')).added).toBe(2);
+ await seedMeetingPage('calendar/seeded/overflow-400', 'overflow_400', 400);
+ await seedMeetingPage('calendar/seeded/overflow-at-ceiling', 'overflow_60', 60);
+ await seedMeetingPage('calendar/seeded/hand-far', null, 400);
+
+ 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-far', 'inside_59', 'soon'].sort());
+ });
+ });
+
+ test('--full with g_future_days widens the horizon: pages inside the wider window stay (#5442)', async () => {
+ await withCalendarSource(async ({ dir, fx, vault }) => {
+ fx.calendarEvents = [meeting('soon', 30), meeting('day_120', 120)];
+ expect((await sweep(dir, fx, vault, {}, 'calendar', { cfg: { g_future_days: 180 } })).added).toBe(2);
+ await seedMeetingPage('calendar/seeded/day-400', 'day_400', 400);
+
+ const result = await sweep(dir, fx, vault, { full: true }, 'calendar', { cfg: { g_future_days: 180 } });
+
+ expect(result.deleted).toBe(1);
+ expect([...(await calendarPages()).keys()].sort()).toEqual(['day_120', 'soon']);
+ const listed = calendarQueries(fx).find((q) => q.has('timeMax'))!;
+ expect(near(Date.parse(listed.get('timeMax')!), NOW_MS + 180 * DAY)).toBe(true);
+ });
+ });
+
+ test('--full refuses more than 200 past-horizon deletions through the mass-delete guard and reports partial (#5442)', async () => {
+ await withCalendarSource(async ({ dir, fx, vault }) => {
+ for (let i = 0; i < 201; i++) await seedMeetingPage(`calendar/seeded/future-${i}`, `future_${i}`, 365 + i);
+
+ 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 201 deletes for source gsrc');
+ expect((await calendarPages()).size).toBe(201);
+ });
+ });
+
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)];