@mulmoclaude/core 1.10.0 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/assets/helps/error-recovery.md +85 -0
  2. package/assets/helps/google-calendar-collection.md +41 -18
  3. package/dist/collection/core/schemaZ.d.ts +10 -1
  4. package/dist/collection/registry/server/index.cjs +2 -2
  5. package/dist/collection/registry/server/index.js +2 -2
  6. package/dist/collection/server/index.cjs +2 -2
  7. package/dist/collection/server/index.js +2 -2
  8. package/dist/collection-watchers/index.cjs +2 -2
  9. package/dist/collection-watchers/index.js +2 -2
  10. package/dist/{discovery-_fjsluLx.js → discovery-B4CZvrXR.js} +11 -3
  11. package/dist/{discovery-_fjsluLx.js.map → discovery-B4CZvrXR.js.map} +1 -1
  12. package/dist/{discovery-DYcR83qx.cjs → discovery-NRy3tyUA.cjs} +11 -3
  13. package/dist/{discovery-DYcR83qx.cjs.map → discovery-NRy3tyUA.cjs.map} +1 -1
  14. package/dist/feeds/server/index.cjs +2 -2
  15. package/dist/feeds/server/index.js +2 -2
  16. package/dist/google/calendar.d.ts +9 -0
  17. package/dist/google/calendarLock.d.ts +16 -0
  18. package/dist/google/calendarPushState.d.ts +1 -1
  19. package/dist/google/collectionProjection.d.ts +18 -0
  20. package/dist/google/collectionPush.d.ts +62 -0
  21. package/dist/google/collectionSync.d.ts +51 -23
  22. package/dist/google/index.cjs +833 -567
  23. package/dist/google/index.cjs.map +1 -1
  24. package/dist/google/index.d.ts +4 -2
  25. package/dist/google/index.js +825 -568
  26. package/dist/google/index.js.map +1 -1
  27. package/dist/google/pushPlan.d.ts +1 -1
  28. package/dist/{server-l4TZ5Lbf.cjs → server-7U-3DE2e.cjs} +2 -2
  29. package/dist/{server-l4TZ5Lbf.cjs.map → server-7U-3DE2e.cjs.map} +1 -1
  30. package/dist/{server-BlIrtGKl.js → server-DdyIvFhz.js} +2 -2
  31. package/dist/{server-BlIrtGKl.js.map → server-DdyIvFhz.js.map} +1 -1
  32. package/package.json +4 -4
@@ -5,7 +5,7 @@ const require_text = require("../text-CaAh9ZSO.cjs");
5
5
  const require_atomic = require("../atomic-C_7YpMiM.cjs");
6
6
  const require_utils_fetch = require("../utils/fetch.cjs");
7
7
  const require_calendarGrid = require("../calendarGrid-CaS9er8i.cjs");
8
- const require_discovery = require("../discovery-DYcR83qx.cjs");
8
+ const require_discovery = require("../discovery-NRy3tyUA.cjs");
9
9
  let node_fs = require("node:fs");
10
10
  let node_path = require("node:path");
11
11
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
@@ -625,7 +625,9 @@ var toEventSummary = (value) => {
625
625
  end: eventTime$1(record.end),
626
626
  htmlLink: stringField(record, "htmlLink"),
627
627
  status: stringField(record, "status"),
628
- colorId: stringField(record, "colorId")
628
+ colorId: stringField(record, "colorId"),
629
+ description: stringField(record, "description"),
630
+ location: stringField(record, "location")
629
631
  };
630
632
  };
631
633
  var toCalendarSummary = (value) => {
@@ -667,6 +669,7 @@ async function createCalendarEvent(accessToken, input) {
667
669
  const body = {
668
670
  summary: input.summary,
669
671
  description: input.description,
672
+ location: input.location,
670
673
  ...resolveEventSpan(input),
671
674
  ...input.colorId ? { colorId: input.colorId } : {},
672
675
  ...input.eventId ? { id: input.eventId } : {}
@@ -691,6 +694,7 @@ var eventEnd = (key, structured, flat) => {
691
694
  var buildEventPatch = (input) => ({
692
695
  ...input.summary !== void 0 ? { summary: input.summary } : {},
693
696
  ...input.description !== void 0 ? { description: input.description } : {},
697
+ ...input.location !== void 0 ? { location: input.location } : {},
694
698
  ...eventEnd("start", input.start, input.startDateTime),
695
699
  ...eventEnd("end", input.end, input.endDateTime),
696
700
  ...input.colorId ? { colorId: input.colorId } : {}
@@ -881,7 +885,9 @@ var toShadowEvent = (event) => ({
881
885
  summary: event.summary,
882
886
  start: event.start,
883
887
  end: event.end,
884
- colorId: event.colorId
888
+ colorId: event.colorId,
889
+ description: event.description,
890
+ location: event.location
885
891
  });
886
892
  async function readState(workspaceRoot) {
887
893
  const stored = await readJsonOrNull(calendarPushStatePath(workspaceRoot));
@@ -924,14 +930,142 @@ async function clearCalendarShadow(calendarId, workspaceRoot) {
924
930
  await updateState((events) => Object.fromEntries(Object.entries(events).filter(([key]) => key !== dropped)), workspaceRoot);
925
931
  }
926
932
  //#endregion
933
+ //#region src/google/calendarLock.ts
934
+ /** Serialise `run` against whatever is already running for `key`.
935
+ *
936
+ * `locks` is passed in so the queuing rule is testable without module state;
937
+ * the key is dropped once nothing is queued behind it, so the map cannot grow
938
+ * an entry per calendar forever. A failed predecessor still releases the
939
+ * queue — `then(run, run)`. */
940
+ async function withKeyedLock(locks, key, run) {
941
+ const result = (locks.get(key) ?? Promise.resolve()).then(run, run);
942
+ const tail = result.then(() => void 0, () => void 0);
943
+ locks.set(key, tail);
944
+ try {
945
+ return await result;
946
+ } finally {
947
+ if (locks.get(key) === tail) locks.delete(key);
948
+ }
949
+ }
950
+ /** In-flight work per canonical calendar id. Module state on purpose: the
951
+ * scheduler, the create trigger and the Refresh button are three doors into
952
+ * the same calendar (CodeRabbit review #2566). */
953
+ var calendarLocks = /* @__PURE__ */ new Map();
954
+ /** Serialise anything that touches ONE calendar's sync state.
955
+ *
956
+ * Shared with the push path (#2598), not only the pull doors: a push that
957
+ * overtakes an in-flight pull would record a baseline for events the pull is
958
+ * still writing, so the next push would diff against a future it never saw.
959
+ *
960
+ * NOT reentrant — a holder must call the lock-free form of whatever it drives,
961
+ * or it waits on itself forever. */
962
+ async function withCalendarLock(calendarId, run) {
963
+ return await withKeyedLock(calendarLocks, canonicalCalendarId(calendarId), run);
964
+ }
965
+ //#endregion
966
+ //#region src/google/pushDateTime.ts
967
+ /** RFC3339 zone designator: `Z`, `+09:00`, `-0500`. */
968
+ var ZONE_SUFFIX_RE$1 = /(?:Z|[+-]\d{2}:?\d{2})$/;
969
+ var FRACTIONAL_SECONDS_RE$1 = /\.\d+$/;
970
+ var TWO_DIGITS_RE = /^\d{2}$/;
971
+ var CLOCK_SEPARATOR = ":";
972
+ var DATE_TIME_SEPARATOR = "T";
973
+ var MIN_CLOCK_SEGMENTS = 2;
974
+ var MAX_CLOCK_SEGMENTS = 3;
975
+ var WHOLE_MINUTE_SECONDS = "00";
976
+ var MAX_SECONDS = 59;
977
+ /** Whether `value` is a real calendar day (`2026-02-30` is not).
978
+ *
979
+ * Delegated to the parser the record lint, the calendar grid and the day view
980
+ * already share, so the push agrees with the rest of the app on what a valid
981
+ * stored date IS — and rejects an impossible one here instead of turning it
982
+ * into an opaque Google 400. */
983
+ var isCalendarDate = (value) => require_calendarGrid.parseIsoDate(value) !== null;
984
+ /** A value Google already accepts verbatim, as the event time to send, or null.
985
+ *
986
+ * Reached when the schema maps `start` onto a `string` field: `projectValue`
987
+ * normalises only `datetime` fields, so that column holds Google's own text,
988
+ * zone and all. The civil part is still validated — matching a trailing `Z` is
989
+ * not evidence that the rest is a date-time. */
990
+ function rawGoogleTime(value) {
991
+ if (isCalendarDate(value)) return { date: value };
992
+ const zone = value.match(ZONE_SUFFIX_RE$1)?.[0];
993
+ if (zone === void 0) return null;
994
+ return require_calendarGrid.parseIsoDateTime(value.slice(0, value.length - zone.length).replace(FRACTIONAL_SECONDS_RE$1, "")) === null ? null : { dateTime: value };
995
+ }
996
+ /** Google's own all-day `end` is EXCLUSIVE — a single day on the 12th ends on
997
+ * the 13th. The pull stores that as `2026-05-13T00:00` and this takes the date
998
+ * part straight back, so the exclusive end round-trips untouched. Looks
999
+ * off-by-one; adjusting it would shorten every all-day event by a day. */
1000
+ function allDayFrom(datePart) {
1001
+ return { date: datePart };
1002
+ }
1003
+ /** Split `HH:MM[:SS]` into RFC3339's always-three segments, or null.
1004
+ *
1005
+ * Split rather than one regex: expressing the optional seconds as `(?::(\d{2}))?`
1006
+ * nests a quantifier inside a quantified group, which the ReDoS lint rejects. */
1007
+ function clockSegments(clockPart) {
1008
+ const segments = clockPart.split(CLOCK_SEPARATOR);
1009
+ if (segments.length < MIN_CLOCK_SEGMENTS || segments.length > MAX_CLOCK_SEGMENTS) return null;
1010
+ if (!segments.every((segment) => TWO_DIGITS_RE.test(segment))) return null;
1011
+ const [hours, minutes, seconds] = segments;
1012
+ if (seconds !== void 0 && Number(seconds) > MAX_SECONDS) return null;
1013
+ return [
1014
+ hours,
1015
+ minutes,
1016
+ seconds ?? WHOLE_MINUTE_SECONDS
1017
+ ].join(CLOCK_SEPARATOR);
1018
+ }
1019
+ /** `YYYY-MM-DDTHH:MM[:SS]` → its date and its RFC3339 clock, or null.
1020
+ *
1021
+ * Validity comes from the shared strict parser, so an out-of-range clock or an
1022
+ * impossible day is refused here rather than sent to Google. */
1023
+ function parseStoredDateTime(value) {
1024
+ if (require_calendarGrid.parseIsoDateTime(value) === null) return null;
1025
+ const [datePart, clockPart, ...extra] = value.split(DATE_TIME_SEPARATOR);
1026
+ if (datePart === void 0 || clockPart === void 0 || extra.length > 0) return null;
1027
+ const clock = clockSegments(clockPart);
1028
+ return clock === null ? null : {
1029
+ datePart,
1030
+ clock
1031
+ };
1032
+ }
1033
+ /** The zone designator to re-attach, or null when `previous` carries none. */
1034
+ function zoneSuffixOf(previous) {
1035
+ if (previous === void 0) return null;
1036
+ return previous.match(ZONE_SUFFIX_RE$1)?.[0] ?? null;
1037
+ }
1038
+ /** Build the event time to send for one field.
1039
+ *
1040
+ * `previous` is the value Google last reported for this event, absent for a
1041
+ * locally-created record. Returns null when `local` is neither a stored
1042
+ * datetime nor a raw Google value — the caller reports that record rather than
1043
+ * letting this invent a time Google would silently accept. */
1044
+ function toGoogleEventTime(local, previous, calendarTimeZone) {
1045
+ if (typeof local !== "string") return null;
1046
+ const trimmed = local.trim();
1047
+ if (trimmed.length === 0) return null;
1048
+ const raw = rawGoogleTime(trimmed);
1049
+ if (raw !== null) return raw;
1050
+ const parts = parseStoredDateTime(trimmed);
1051
+ if (parts === null) return null;
1052
+ if (previous !== void 0 && isCalendarDate(previous)) return allDayFrom(parts.datePart);
1053
+ const zone = zoneSuffixOf(previous);
1054
+ const dateTime = `${parts.datePart}${DATE_TIME_SEPARATOR}${parts.clock}`;
1055
+ return zone === null ? {
1056
+ dateTime,
1057
+ timeZone: calendarTimeZone
1058
+ } : { dateTime: `${dateTime}${zone}` };
1059
+ }
1060
+ //#endregion
927
1061
  //#region src/google/collectionDateTime.ts
928
1062
  /** All-day events carry no clock; midnight is where the day view places them. */
929
1063
  var ALL_DAY_CLOCK = "00:00";
930
1064
  var DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
931
1065
  /** RFC3339 zone designator: `Z`, `+09:00`, `-0500`. */
932
- var ZONE_SUFFIX_RE$1 = /(?:Z|[+-]\d{2}:?\d{2})$/;
1066
+ var ZONE_SUFFIX_RE = /(?:Z|[+-]\d{2}:?\d{2})$/;
933
1067
  /** Fractional seconds have no place in the collection datetime shape. */
934
- var FRACTIONAL_SECONDS_RE$1 = /\.\d+$/;
1068
+ var FRACTIONAL_SECONDS_RE = /\.\d+$/;
935
1069
  /** Normalise one Google Calendar time value for storage in a `datetime` field.
936
1070
  * Anything that isn't a recognisable Google shape (empty string, non-string,
937
1071
  * free text) is returned untouched — the record lint should report it rather
@@ -941,12 +1075,10 @@ function toCollectionDateTime(value) {
941
1075
  const trimmed = value.trim();
942
1076
  if (DATE_ONLY_RE.test(trimmed)) return `${trimmed}T${ALL_DAY_CLOCK}`;
943
1077
  if (!trimmed.includes("T")) return value;
944
- return trimmed.replace(ZONE_SUFFIX_RE$1, "").replace(FRACTIONAL_SECONDS_RE$1, "");
1078
+ return trimmed.replace(ZONE_SUFFIX_RE, "").replace(FRACTIONAL_SECONDS_RE, "");
945
1079
  }
946
1080
  //#endregion
947
- //#region src/google/collectionSync.ts
948
- var GOOGLE_CALENDAR_SYNC_TASK_ID = "system:google-calendar-sync";
949
- var DEFAULT_SYNC_INTERVAL_MS = 3600 * 1e3;
1081
+ //#region src/google/collectionProjection.ts
950
1082
  var DATETIME_FIELD_TYPE = "datetime";
951
1083
  /** Own-property lookup, mirroring what the record lint reads: a spec reachable
952
1084
  * only through the prototype chain is not a DECLARED field, so it must not
@@ -971,482 +1103,75 @@ function toCollectionRecord(event, map, primaryKey, fields) {
971
1103
  [primaryKey]: event.id
972
1104
  };
973
1105
  }
974
- function classifyWrite(eventId, kind) {
975
- if (kind === "ok") return { kind: "written" };
976
- if (kind === "invalid-id") return {
977
- kind: "unwritable",
978
- message: `write ${eventId}: invalid-id`
979
- };
980
- return {
981
- kind: "error",
982
- message: `write ${eventId}: ${kind}`
983
- };
984
- }
985
- function classifyDelete(eventId, kind) {
986
- if (kind === "ok") return { kind: "removed" };
987
- if (kind === "not-found") return { kind: "skipped" };
988
- if (kind === "invalid-id") return {
989
- kind: "unwritable",
990
- message: `delete ${eventId}: invalid-id`
991
- };
1106
+ /** Google's mapped values laid over whatever the record already holds.
1107
+ *
1108
+ * A record file is written whole (`writeItem`), so projecting alone would drop
1109
+ * every column the map does not name — a collection cannot then carry a local
1110
+ * note next to a mirrored event, because the next pull that touches that event
1111
+ * silently deletes it. The projection still wins on the fields it covers: those
1112
+ * are Google's to own. */
1113
+ function mergeIntoExisting(existing, projected) {
992
1114
  return {
993
- kind: "error",
994
- message: `delete ${eventId}: ${kind}`
1115
+ ...existing ?? {},
1116
+ ...projected
995
1117
  };
996
1118
  }
997
- async function applyEvent(collection, event, workspaceRoot) {
998
- const { schema } = collection;
999
- try {
1000
- const store = require_discovery.storeFor(collection, { workspaceRoot });
1001
- if (!store.write || !store.delete) return {
1002
- kind: "unwritable",
1003
- message: `collection '${collection.slug}' is read-only`
1004
- };
1005
- if (event.status === "cancelled") {
1006
- const deleted = await store.delete(event.id);
1007
- return classifyDelete(event.id, deleted.kind);
1008
- }
1009
- const record = toCollectionRecord(event, schema.googleCalendar?.map ?? {}, schema.primaryKey, schema.fields);
1010
- const written = await store.write(event.id, record);
1011
- return classifyWrite(event.id, written.kind);
1012
- } catch (error) {
1013
- return {
1014
- kind: "error",
1015
- message: `apply ${event.id}: ${String(error)}`
1016
- };
1017
- }
1119
+ //#endregion
1120
+ //#region src/google/pushPlan.ts
1121
+ /** The event fields Google lets a caller write. `htmlLink` and `status` are
1122
+ * read-only, so a record column mapped to either is ignored here rather than
1123
+ * rejected — the mapping was authored for the pull, and a push has no business
1124
+ * invalidating it. */
1125
+ var PUSHABLE_SOURCE_FIELDS = [
1126
+ "summary",
1127
+ "start",
1128
+ "end",
1129
+ "colorId",
1130
+ "description",
1131
+ "location"
1132
+ ];
1133
+ var isPushableSource = (source) => PUSHABLE_SOURCE_FIELDS.includes(source);
1134
+ /** The subset of a schema's `map` a push can act on: collection field → event field. */
1135
+ function pushableMap(map) {
1136
+ return Object.fromEntries(Object.entries(map).filter((entry) => isPushableSource(entry[1])));
1018
1137
  }
1019
- async function restartFullSync(accessToken, calendarId, workspaceRoot) {
1020
- await clearCalendarSyncToken(calendarId, workspaceRoot);
1021
- await clearCalendarShadow(calendarId, workspaceRoot);
1022
- return await syncCalendarEvents(accessToken, { calendarId });
1138
+ /** Event field → the record column feeding it. The schema authors the map the
1139
+ * other way round (for the pull); a push looks up by event field. Two columns
1140
+ * mapped to one event field is already ambiguous for the pull — last wins. */
1141
+ function bySourceField(map) {
1142
+ return Object.fromEntries(Object.entries(map).map(([field, source]) => [source, field]));
1023
1143
  }
1024
- /** Serialise `run` against whatever is already running for `key`.
1144
+ /** Google accepts a caller-chosen event id of 5-1024 base32hex characters. A
1145
+ * record id outside that (a semantic id like `team-standup`) cannot be used,
1146
+ * and v1 reports it instead of re-keying the record — see the plan. */
1147
+ var CLIENT_EVENT_ID_RE = /^[0-9a-v]{5,1024}$/;
1148
+ var isClientSettableEventId = (eventId) => CLIENT_EVENT_ID_RE.test(eventId);
1149
+ /** A field's value as comparable/sendable text.
1025
1150
  *
1026
- * `locks` is passed in so the queuing rule is testable without module state;
1027
- * the key is dropped once nothing is queued behind it, so the map cannot grow
1028
- * an entry per calendar forever. A failed predecessor still releases the
1029
- * queue — `then(run, run)`. */
1030
- async function withKeyedLock(locks, key, run) {
1031
- const result = (locks.get(key) ?? Promise.resolve()).then(run, run);
1032
- const tail = result.then(() => void 0, () => void 0);
1033
- locks.set(key, tail);
1034
- try {
1035
- return await result;
1036
- } finally {
1037
- if (locks.get(key) === tail) locks.delete(key);
1038
- }
1039
- }
1040
- /** In-flight sync per canonical calendar id. Module state on purpose: the
1041
- * scheduler, the create trigger and the Refresh button are three doors into
1042
- * the same calendar (CodeRabbit review #2566). */
1043
- var calendarLocks = /* @__PURE__ */ new Map();
1044
- /** Sync ONE calendar and fan its events out to every collection bound to it.
1151
+ * Absent, null and `""` all collapse to `""`: Google reports an inherited colour
1152
+ * as `""` while the record file may omit the key entirely, and treating those as
1153
+ * different would report a local edit on every single push.
1045
1154
  *
1046
- * The fan-out is not an optimisation, it is correctness: the sync token is
1047
- * keyed by `calendarId`, so syncing collection-by-collection would let the
1048
- * first collection advance the shared token and leave every later collection
1049
- * on the same calendar reading an already-consumed window — silently missing
1050
- * those events forever. Fetch once, apply to all, then advance the token.
1051
- * (Codex + CodeRabbit review on #2184.)
1155
+ * A non-primitive is JSON-encoded rather than left to `String`, whose
1156
+ * `[object Object]` would make two DIFFERENT objects compare equal — a
1157
+ * silently-skipped edit. */
1158
+ var fieldText = (value) => {
1159
+ if (value === void 0 || value === null) return "";
1160
+ if (typeof value === "string") return value;
1161
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
1162
+ return JSON.stringify(value) ?? "";
1163
+ };
1164
+ /** A stored datetime with no seconds — what the collection's own date-time input
1165
+ * produces. Google's values always carry seconds, so the pull writes them and a
1166
+ * hand-typed value does not. */
1167
+ var SECONDLESS_DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/;
1168
+ var WHOLE_MINUTE = ":00";
1169
+ /** Field text with `…T09:30` and `…T09:30:00` collapsed to one spelling.
1052
1170
  *
1053
- * Queued per calendar for the same reason the fan-out exists: two passes over
1054
- * one calendar (a Refresh click landing during the scheduled run) would each
1055
- * load the SAME stored token and walk the same window. That is idempotent —
1056
- * writes are upserts by event id — but it is a wasted full walk. Queued, the
1057
- * second pass resumes from the token the first just stored and fetches only
1058
- * what is genuinely new. */
1059
- /** Serialise anything that touches ONE calendar's sync state.
1060
- *
1061
- * Shared with the push path (#2598), not only the pull doors: a push that
1062
- * overtakes an in-flight pull would record a baseline for events the pull is
1063
- * still writing, so the next push would diff against a future it never saw. */
1064
- async function withCalendarLock(calendarId, run) {
1065
- return await withKeyedLock(calendarLocks, canonicalCalendarId(calendarId), run);
1066
- }
1067
- async function syncCalendarGroup(calendarId, collections, workspaceRoot) {
1068
- return await withCalendarLock(calendarId, () => syncCalendarGroupNow(calendarId, collections, workspaceRoot));
1069
- }
1070
- async function syncCalendarGroupNow(calendarId, collections, workspaceRoot) {
1071
- const accessToken = await getGoogleAccessToken();
1072
- const first = await syncCalendarEvents(accessToken, {
1073
- calendarId,
1074
- syncToken: await loadCalendarSyncToken(calendarId, workspaceRoot) ?? void 0
1075
- });
1076
- const result = first.fullResyncRequired ? await restartFullSync(accessToken, calendarId, workspaceRoot) : first;
1077
- const results = [];
1078
- for (const collection of collections) results.push(await applyEventsToCollection(collection, result.events, workspaceRoot));
1079
- const unwritable = results.flatMap((entry) => entry.unwritable);
1080
- if (unwritable.length > 0) log.warn("google", "skipping calendar events that can never be stored", {
1081
- calendarId,
1082
- unwritable
1083
- });
1084
- const failed = results.flatMap((entry) => entry.errors);
1085
- if (failed.length > 0) {
1086
- log.warn("google", "holding back calendar sync token after failed writes", {
1087
- calendarId,
1088
- failed: failed.length
1089
- });
1090
- return results;
1091
- }
1092
- await saveCalendarShadow(calendarId, shadowUpdates(result.events), workspaceRoot);
1093
- if (result.nextSyncToken) await advanceToken(calendarId, result.nextSyncToken, collections, workspaceRoot);
1094
- return results;
1095
- }
1096
- /** The baseline this window establishes: what Google now says per event, and
1097
- * `null` for a cancelled one so a recreate cannot resume from a dead baseline. */
1098
- function shadowUpdates(events) {
1099
- return Object.fromEntries(events.map((event) => [event.id, event.status === "cancelled" ? null : toShadowEvent(event)]));
1100
- }
1101
- /** Save the window's token unless every collection that consumed it was deleted
1102
- * while the sync was in flight.
1103
- *
1104
- * The sync opens with a `discoverCollections()` snapshot, so a delete landing
1105
- * mid-run has already cleared this calendar's token by the time we get here
1106
- * (`releaseOrphanedCalendarToken`). Saving anyway would resurrect exactly the
1107
- * orphan the delete removed, and the next collection on this calendar would
1108
- * resume from a token describing records it never received (#2428).
1109
- *
1110
- * One survivor is enough: it still needs the incremental position. */
1111
- async function advanceToken(calendarId, nextSyncToken, collections, workspaceRoot) {
1112
- if (!await anySyncedCollectionSurvives(collections)) {
1113
- log.info("google", "not advancing the sync token — every collection on this calendar was deleted mid-sync", { calendarId });
1114
- return;
1115
- }
1116
- await saveCalendarSyncToken(calendarId, nextSyncToken, workspaceRoot);
1117
- }
1118
- async function pathExists(absPath) {
1119
- try {
1120
- await (0, node_fs_promises.stat)(absPath);
1121
- return true;
1122
- } catch {
1123
- return false;
1124
- }
1125
- }
1126
- /** Liveness of the collections a sync just wrote to, checked against the skill
1127
- * dir `deleteCollection` removes. `exists` is injected so the rule is testable
1128
- * without a filesystem. An empty group has no survivor by definition. */
1129
- async function anySyncedCollectionSurvives(collections, exists = pathExists) {
1130
- return (await Promise.all(collections.map((collection) => exists(collection.skillDir)))).some(Boolean);
1131
- }
1132
- async function applyEventsToCollection(collection, events, workspaceRoot) {
1133
- const outcomes = [];
1134
- for (const event of events) outcomes.push(await applyEvent(collection, event, workspaceRoot));
1135
- return {
1136
- slug: collection.slug,
1137
- written: outcomes.filter((outcome) => outcome.kind === "written").length,
1138
- removed: outcomes.filter((outcome) => outcome.kind === "removed").length,
1139
- unwritable: outcomes.flatMap((outcome) => outcome.kind === "unwritable" ? [outcome.message] : []),
1140
- errors: outcomes.flatMap((outcome) => outcome.kind === "error" ? [outcome.message] : [])
1141
- };
1142
- }
1143
- /** A refresh token is what lets the scheduler run unattended; without one
1144
- * there is nothing to sync with. */
1145
- async function isGoogleLinked() {
1146
- return Boolean((await loadGoogleTokens())?.refresh_token);
1147
- }
1148
- /** Group the declaring collections by the calendar they read, so each calendar
1149
- * is fetched exactly once.
1150
- *
1151
- * Keyed by the CANONICAL id, not the declared one: an omitted `calendarId` and
1152
- * an explicit `"primary"` address the same calendar and therefore share one
1153
- * sync token, so grouping them apart would let one group advance the token out
1154
- * from under the other — the very loss this grouping exists to prevent
1155
- * (Codex review #2184). */
1156
- function groupByCalendar(collections) {
1157
- const groups = /* @__PURE__ */ new Map();
1158
- for (const collection of collections) {
1159
- const key = canonicalCalendarId(collection.schema.googleCalendar?.calendarId);
1160
- groups.set(key, [...groups.get(key) ?? [], collection]);
1161
- }
1162
- return groups;
1163
- }
1164
- /** The canonical calendar whose sync token nothing needs any more, or null.
1165
- *
1166
- * Sync tokens are keyed by calendar, NOT by collection, so a deleted
1167
- * collection's token outlives it. Recreating a collection on the same calendar
1168
- * then resumes from that token and receives only the delta — the new
1169
- * collection never gets the history (#2428).
1170
- *
1171
- * Returns null while ANY remaining collection still reads that calendar:
1172
- * clearing a live calendar's token costs a full re-walk on the next sync. The
1173
- * comparison is on the CANONICAL id for the same reason `groupByCalendar` is —
1174
- * an omitted `calendarId` and an explicit `"primary"` are one calendar. */
1175
- function orphanedCalendarId(deleted, remaining) {
1176
- if (!deleted.googleCalendar) return null;
1177
- const key = canonicalCalendarId(deleted.googleCalendar.calendarId);
1178
- return remaining.some((other) => other.googleCalendar && canonicalCalendarId(other.googleCalendar.calendarId) === key) ? null : key;
1179
- }
1180
- /** Drop the sync token of a just-deleted collection's calendar, unless another
1181
- * collection still reads it. Call AFTER the delete lands — the check reads the
1182
- * collections that survive it.
1183
- *
1184
- * Returns the cleared calendar id, or null when nothing was cleared. Never
1185
- * throws: a failed cleanup must not fail the delete it follows. */
1186
- async function releaseOrphanedCalendarToken(deleted, workspaceRoot) {
1187
- try {
1188
- if (!deleted.googleCalendar) return null;
1189
- const orphaned = orphanedCalendarId(deleted, (await require_discovery.discoverCollections({ workspaceRoot })).map((collection) => collection.schema));
1190
- if (orphaned === null) return null;
1191
- await clearCalendarSyncToken(orphaned, workspaceRoot);
1192
- await clearCalendarShadow(orphaned, workspaceRoot);
1193
- log.info("google", "cleared the sync token of a calendar no collection reads any more", { calendarId: orphaned });
1194
- return orphaned;
1195
- } catch (error) {
1196
- log.warn("google", "could not release the deleted collection's calendar sync token", { error: String(error) });
1197
- return null;
1198
- }
1199
- }
1200
- /** Every declaring collection, grouped by the calendar it reads. */
1201
- async function declaringGroups(workspaceRoot) {
1202
- return groupByCalendar((await require_discovery.discoverCollections({ workspaceRoot })).filter((collection) => collection.schema.googleCalendar));
1203
- }
1204
- /** Whether a background sync of these groups may run at all.
1205
- *
1206
- * Authoring the collection before linking the account is an expected state,
1207
- * not a failure. Checking once here keeps it a quiet skip instead of an
1208
- * access-token throw per calendar, every hour, until the user links (#2188).
1209
- * A user-triggered sync answers differently — it says so out loud. */
1210
- async function backgroundSyncAllowed(groups) {
1211
- if (groups.size === 0) return false;
1212
- if (await isGoogleLinked()) return true;
1213
- log.info("google", "skipping calendar sync — no Google account linked on this host", { calendars: groups.size });
1214
- return false;
1215
- }
1216
- /** Run each group, isolating failures per calendar — one unreachable calendar
1217
- * (or a revoked grant) must not stop the others. */
1218
- async function runCalendarGroups(groups, workspaceRoot) {
1219
- const results = [];
1220
- for (const [calendarId, collections] of groups) try {
1221
- results.push(...await syncCalendarGroup(calendarId, collections, workspaceRoot));
1222
- } catch (error) {
1223
- log.warn("google", "calendar sync failed", {
1224
- calendarId,
1225
- error: String(error)
1226
- });
1227
- results.push(...collections.map((collection) => ({
1228
- slug: collection.slug,
1229
- written: 0,
1230
- removed: 0,
1231
- unwritable: [],
1232
- errors: [String(error)]
1233
- })));
1234
- }
1235
- return results;
1236
- }
1237
- /** Sync every collection that declares `googleCalendar`. */
1238
- async function syncDueCalendarCollections(workspaceRoot) {
1239
- const groups = await declaringGroups(workspaceRoot);
1240
- return await backgroundSyncAllowed(groups) ? await runCalendarGroups(groups, workspaceRoot) : [];
1241
- }
1242
- /** The groups whose calendar has never synced. A missing token IS the "created
1243
- * since the last sync" signal — nothing else distinguishes a new collection
1244
- * from an edited one on the write path this feeds (#2427).
1245
- *
1246
- * Self-silencing by construction: the first sync stores a token, so a calendar
1247
- * matches at most once. `loadToken` is injected so the rule is testable without
1248
- * a workspace on disk. */
1249
- async function unsyncedGroups(groups, loadToken) {
1250
- const checked = await Promise.all([...groups].map(async (entry) => await loadToken(entry[0]) === null ? entry : null));
1251
- return new Map(checked.filter((entry) => entry !== null));
1252
- }
1253
- /** Sync only the calendars that have never synced — the first sync for a
1254
- * just-created collection, which otherwise stays empty until the hourly
1255
- * scheduler run (#2427). Cheap and safe to call on every config write. */
1256
- async function syncNewCalendarCollections(workspaceRoot) {
1257
- const pending = await unsyncedGroups(await declaringGroups(workspaceRoot), (calendarId) => loadCalendarSyncToken(calendarId, workspaceRoot));
1258
- if (!await backgroundSyncAllowed(pending)) return [];
1259
- log.info("google", "running the first sync for newly declared calendars", { calendars: [...pending.keys()] });
1260
- return await runCalendarGroups(pending, workspaceRoot);
1261
- }
1262
- var liveManualSyncDeps = {
1263
- loadGroups: declaringGroups,
1264
- isLinked: isGoogleLinked,
1265
- runGroups: runCalendarGroups
1266
- };
1267
- /** Sync the calendar ONE collection reads, on demand (the Refresh button).
1268
- *
1269
- * Deliberately syncs the whole group, not just `slug`: the sync token is keyed
1270
- * by calendar, so consuming a window for one collection would leave the others
1271
- * on that calendar reading an already-consumed one. Returns every result of the
1272
- * group so the caller can report the requested slug's own counts.
1273
- *
1274
- * "Does this collection sync at all" is answered BEFORE "is Google linked":
1275
- * telling someone to link their account for a collection that never declared a
1276
- * calendar sends them fixing the wrong thing. */
1277
- async function syncCalendarForCollection(slug, workspaceRoot, deps = liveManualSyncDeps) {
1278
- const owning = [...await deps.loadGroups(workspaceRoot)].filter(([, collections]) => collections.some((collection) => collection.slug === slug));
1279
- if (owning.length === 0) return { kind: "not-a-calendar" };
1280
- if (!await deps.isLinked()) return { kind: "not-linked" };
1281
- return {
1282
- kind: "synced",
1283
- results: await deps.runGroups(new Map(owning), workspaceRoot)
1284
- };
1285
- }
1286
- /** Scheduler registration, shaped like `feedRefreshTaskDef` so hosts wire it
1287
- * with a single line. */
1288
- function googleCalendarSyncTaskDef(opts) {
1289
- return {
1290
- id: GOOGLE_CALENDAR_SYNC_TASK_ID,
1291
- name: "Google Calendar sync",
1292
- description: "Pulls changed Google Calendar events into any collection declaring `googleCalendar`, without invoking the LLM.",
1293
- schedule: {
1294
- type: _receptron_task_scheduler.SCHEDULE_TYPES.interval,
1295
- intervalMs: opts?.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS
1296
- },
1297
- missedRunPolicy: _receptron_task_scheduler.MISSED_RUN_POLICIES.runOnce,
1298
- run: () => syncDueCalendarCollections(opts?.workspaceRoot ?? require_discovery.getWorkspaceRoot()).then(() => {})
1299
- };
1300
- }
1301
- //#endregion
1302
- //#region src/google/pushDateTime.ts
1303
- /** RFC3339 zone designator: `Z`, `+09:00`, `-0500`. */
1304
- var ZONE_SUFFIX_RE = /(?:Z|[+-]\d{2}:?\d{2})$/;
1305
- var FRACTIONAL_SECONDS_RE = /\.\d+$/;
1306
- var TWO_DIGITS_RE = /^\d{2}$/;
1307
- var CLOCK_SEPARATOR = ":";
1308
- var DATE_TIME_SEPARATOR = "T";
1309
- var MIN_CLOCK_SEGMENTS = 2;
1310
- var MAX_CLOCK_SEGMENTS = 3;
1311
- var WHOLE_MINUTE_SECONDS = "00";
1312
- var MAX_SECONDS = 59;
1313
- /** Whether `value` is a real calendar day (`2026-02-30` is not).
1314
- *
1315
- * Delegated to the parser the record lint, the calendar grid and the day view
1316
- * already share, so the push agrees with the rest of the app on what a valid
1317
- * stored date IS — and rejects an impossible one here instead of turning it
1318
- * into an opaque Google 400. */
1319
- var isCalendarDate = (value) => require_calendarGrid.parseIsoDate(value) !== null;
1320
- /** A value Google already accepts verbatim, as the event time to send, or null.
1321
- *
1322
- * Reached when the schema maps `start` onto a `string` field: `projectValue`
1323
- * normalises only `datetime` fields, so that column holds Google's own text,
1324
- * zone and all. The civil part is still validated — matching a trailing `Z` is
1325
- * not evidence that the rest is a date-time. */
1326
- function rawGoogleTime(value) {
1327
- if (isCalendarDate(value)) return { date: value };
1328
- const zone = value.match(ZONE_SUFFIX_RE)?.[0];
1329
- if (zone === void 0) return null;
1330
- return require_calendarGrid.parseIsoDateTime(value.slice(0, value.length - zone.length).replace(FRACTIONAL_SECONDS_RE, "")) === null ? null : { dateTime: value };
1331
- }
1332
- /** Google's own all-day `end` is EXCLUSIVE — a single day on the 12th ends on
1333
- * the 13th. The pull stores that as `2026-05-13T00:00` and this takes the date
1334
- * part straight back, so the exclusive end round-trips untouched. Looks
1335
- * off-by-one; adjusting it would shorten every all-day event by a day. */
1336
- function allDayFrom(datePart) {
1337
- return { date: datePart };
1338
- }
1339
- /** Split `HH:MM[:SS]` into RFC3339's always-three segments, or null.
1340
- *
1341
- * Split rather than one regex: expressing the optional seconds as `(?::(\d{2}))?`
1342
- * nests a quantifier inside a quantified group, which the ReDoS lint rejects. */
1343
- function clockSegments(clockPart) {
1344
- const segments = clockPart.split(CLOCK_SEPARATOR);
1345
- if (segments.length < MIN_CLOCK_SEGMENTS || segments.length > MAX_CLOCK_SEGMENTS) return null;
1346
- if (!segments.every((segment) => TWO_DIGITS_RE.test(segment))) return null;
1347
- const [hours, minutes, seconds] = segments;
1348
- if (seconds !== void 0 && Number(seconds) > MAX_SECONDS) return null;
1349
- return [
1350
- hours,
1351
- minutes,
1352
- seconds ?? WHOLE_MINUTE_SECONDS
1353
- ].join(CLOCK_SEPARATOR);
1354
- }
1355
- /** `YYYY-MM-DDTHH:MM[:SS]` → its date and its RFC3339 clock, or null.
1356
- *
1357
- * Validity comes from the shared strict parser, so an out-of-range clock or an
1358
- * impossible day is refused here rather than sent to Google. */
1359
- function parseStoredDateTime(value) {
1360
- if (require_calendarGrid.parseIsoDateTime(value) === null) return null;
1361
- const [datePart, clockPart, ...extra] = value.split(DATE_TIME_SEPARATOR);
1362
- if (datePart === void 0 || clockPart === void 0 || extra.length > 0) return null;
1363
- const clock = clockSegments(clockPart);
1364
- return clock === null ? null : {
1365
- datePart,
1366
- clock
1367
- };
1368
- }
1369
- /** The zone designator to re-attach, or null when `previous` carries none. */
1370
- function zoneSuffixOf(previous) {
1371
- if (previous === void 0) return null;
1372
- return previous.match(ZONE_SUFFIX_RE)?.[0] ?? null;
1373
- }
1374
- /** Build the event time to send for one field.
1375
- *
1376
- * `previous` is the value Google last reported for this event, absent for a
1377
- * locally-created record. Returns null when `local` is neither a stored
1378
- * datetime nor a raw Google value — the caller reports that record rather than
1379
- * letting this invent a time Google would silently accept. */
1380
- function toGoogleEventTime(local, previous, calendarTimeZone) {
1381
- if (typeof local !== "string") return null;
1382
- const trimmed = local.trim();
1383
- if (trimmed.length === 0) return null;
1384
- const raw = rawGoogleTime(trimmed);
1385
- if (raw !== null) return raw;
1386
- const parts = parseStoredDateTime(trimmed);
1387
- if (parts === null) return null;
1388
- if (previous !== void 0 && isCalendarDate(previous)) return allDayFrom(parts.datePart);
1389
- const zone = zoneSuffixOf(previous);
1390
- const dateTime = `${parts.datePart}${DATE_TIME_SEPARATOR}${parts.clock}`;
1391
- return zone === null ? {
1392
- dateTime,
1393
- timeZone: calendarTimeZone
1394
- } : { dateTime: `${dateTime}${zone}` };
1395
- }
1396
- //#endregion
1397
- //#region src/google/pushPlan.ts
1398
- /** The event fields Google lets a caller write. `htmlLink` and `status` are
1399
- * read-only, so a record column mapped to either is ignored here rather than
1400
- * rejected — the mapping was authored for the pull, and a push has no business
1401
- * invalidating it. */
1402
- var PUSHABLE_SOURCE_FIELDS = [
1403
- "summary",
1404
- "start",
1405
- "end",
1406
- "colorId"
1407
- ];
1408
- var isPushableSource = (source) => PUSHABLE_SOURCE_FIELDS.includes(source);
1409
- /** The subset of a schema's `map` a push can act on: collection field → event field. */
1410
- function pushableMap(map) {
1411
- return Object.fromEntries(Object.entries(map).filter((entry) => isPushableSource(entry[1])));
1412
- }
1413
- /** Event field → the record column feeding it. The schema authors the map the
1414
- * other way round (for the pull); a push looks up by event field. Two columns
1415
- * mapped to one event field is already ambiguous for the pull — last wins. */
1416
- function bySourceField(map) {
1417
- return Object.fromEntries(Object.entries(map).map(([field, source]) => [source, field]));
1418
- }
1419
- /** Google accepts a caller-chosen event id of 5-1024 base32hex characters. A
1420
- * record id outside that (a semantic id like `team-standup`) cannot be used,
1421
- * and v1 reports it instead of re-keying the record — see the plan. */
1422
- var CLIENT_EVENT_ID_RE = /^[0-9a-v]{5,1024}$/;
1423
- var isClientSettableEventId = (eventId) => CLIENT_EVENT_ID_RE.test(eventId);
1424
- /** A field's value as comparable/sendable text.
1425
- *
1426
- * Absent, null and `""` all collapse to `""`: Google reports an inherited colour
1427
- * as `""` while the record file may omit the key entirely, and treating those as
1428
- * different would report a local edit on every single push.
1429
- *
1430
- * A non-primitive is JSON-encoded rather than left to `String`, whose
1431
- * `[object Object]` would make two DIFFERENT objects compare equal — a
1432
- * silently-skipped edit. */
1433
- var fieldText = (value) => {
1434
- if (value === void 0 || value === null) return "";
1435
- if (typeof value === "string") return value;
1436
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
1437
- return JSON.stringify(value) ?? "";
1438
- };
1439
- /** A stored datetime with no seconds — what the collection's own date-time input
1440
- * produces. Google's values always carry seconds, so the pull writes them and a
1441
- * hand-typed value does not. */
1442
- var SECONDLESS_DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/;
1443
- var WHOLE_MINUTE = ":00";
1444
- /** Field text with `…T09:30` and `…T09:30:00` collapsed to one spelling.
1445
- *
1446
- * Without this, a record the user typed a time into never stops looking edited:
1447
- * the push writes it, Google answers with seconds, the baseline projection keeps
1448
- * them, and the seconds-less record then differs from its own baseline on every
1449
- * later push — re-PATCHing the same event on every click, forever.
1171
+ * Without this, a record the user typed a time into never stops looking edited:
1172
+ * the push writes it, Google answers with seconds, the baseline projection keeps
1173
+ * them, and the seconds-less record then differs from its own baseline on every
1174
+ * later push — re-PATCHing the same event on every click, forever.
1450
1175
  *
1451
1176
  * A value that carries a zone offset (a `start` mapped onto a `string` field) is
1452
1177
  * left alone: it is Google's own text on both sides already. */
@@ -1593,6 +1318,16 @@ function eventTime(ctx, record, source, previous) {
1593
1318
  time
1594
1319
  };
1595
1320
  }
1321
+ /** `description` / `location` for a create — omitted when empty, since there is
1322
+ * nothing to state about an event that carries neither. */
1323
+ var optionalText = (ctx, record) => {
1324
+ const description = fieldText(localValue(ctx, record, "description"));
1325
+ const location = fieldText(localValue(ctx, record, "location"));
1326
+ return {
1327
+ ...description ? { description } : {},
1328
+ ...location ? { location } : {}
1329
+ };
1330
+ };
1596
1331
  async function createFromRecord(ctx, eventId, record) {
1597
1332
  if (!isClientSettableEventId(eventId)) return {
1598
1333
  kind: "skipped",
@@ -1617,10 +1352,21 @@ async function createFromRecord(ctx, eventId, record) {
1617
1352
  summary: fieldText(localValue(ctx, record, "summary")),
1618
1353
  start: start.time,
1619
1354
  end: end.time,
1355
+ ...optionalText(ctx, record),
1620
1356
  ...colorId ? { colorId } : {}
1621
1357
  })
1622
1358
  };
1623
1359
  }
1360
+ /** The free-text fields of a patch, each only when the local edit touched it.
1361
+ * Unlike `colorId`, `""` is a real value here — Google clears the field. */
1362
+ var textPatch = (ctx, record, changed) => {
1363
+ const touched = [
1364
+ "summary",
1365
+ "description",
1366
+ "location"
1367
+ ].filter((source) => changed.includes(source));
1368
+ return Object.fromEntries(touched.map((source) => [source, fieldText(localValue(ctx, record, source))]));
1369
+ };
1624
1370
  /** Only the fields the local edit touched — PATCH semantics, so an untouched
1625
1371
  * attendee list / recurrence rule is left alone. */
1626
1372
  function buildPatch(ctx, record, changed, shadow) {
@@ -1641,7 +1387,7 @@ function buildPatch(ctx, record, changed, shadow) {
1641
1387
  return {
1642
1388
  ok: true,
1643
1389
  patch: {
1644
- ...changed.includes("summary") ? { summary: fieldText(localValue(ctx, record, "summary")) } : {},
1390
+ ...textPatch(ctx, record, changed),
1645
1391
  ...changed.includes("colorId") ? { colorId } : {},
1646
1392
  ...Object.fromEntries(resolved.flatMap((entry) => entry.result.ok ? [[entry.source, entry.result.time]] : []))
1647
1393
  }
@@ -1708,111 +1454,622 @@ async function createOrAdopt(ctx, eventId, record) {
1708
1454
  };
1709
1455
  }
1710
1456
  }
1711
- /** A 403 on a write is a permissions answer, but `googleApiError` appends the
1712
- * "is the API enabled for the Cloud project?" hint to every 403 — true for a
1713
- * disabled API, misleading here. Reached when the up-front role check could not
1714
- * run because the calendar is not in the user's list, which is exactly when the
1715
- * user needs the real reason. */
1716
- function writeFailure(eventId, error) {
1717
- if (isGoogleApiError(error) && error.status === 403) return {
1718
- kind: "skipped",
1719
- message: `${eventId}: Google refused the write — you may not have permission to change events on this calendar`
1720
- };
1721
- return {
1722
- kind: "error",
1723
- message: `${eventId}: ${String(error)}`
1724
- };
1725
- }
1726
- async function pushRecord(ctx, eventId, record) {
1457
+ /** A 403 on a write is a permissions answer, but `googleApiError` appends the
1458
+ * "is the API enabled for the Cloud project?" hint to every 403 — true for a
1459
+ * disabled API, misleading here. Reached when the up-front role check could not
1460
+ * run because the calendar is not in the user's list, which is exactly when the
1461
+ * user needs the real reason. */
1462
+ function writeFailure(eventId, error) {
1463
+ if (isGoogleApiError(error) && error.status === 403) return {
1464
+ kind: "skipped",
1465
+ message: `${eventId}: Google refused the write — you may not have permission to change events on this calendar`
1466
+ };
1467
+ return {
1468
+ kind: "error",
1469
+ message: `${eventId}: ${String(error)}`
1470
+ };
1471
+ }
1472
+ async function pushRecord(ctx, eventId, record) {
1473
+ try {
1474
+ const shadow = ctx.shadow[eventId];
1475
+ const plan = planRecord(eventId, record, shadow, ctx.map, ctx.primaryKey, ctx.fields);
1476
+ if (plan.kind === "unchanged") return { kind: "unchanged" };
1477
+ if (plan.kind === "create" || shadow === void 0) return await createOrAdopt(ctx, eventId, record);
1478
+ return await updateFromRecord(ctx, eventId, record, plan.fields, shadow);
1479
+ } catch (error) {
1480
+ return writeFailure(eventId, error);
1481
+ }
1482
+ }
1483
+ /** The baseline an outcome establishes, so the next push sees the record as
1484
+ * unchanged instead of pushing it again. Empty for anything that wrote nothing
1485
+ * and had no baseline to repair. */
1486
+ function pushedShadow(outcomes) {
1487
+ const written = outcomes.flatMap((outcome) => "event" in outcome && outcome.event !== void 0 ? [outcome.event] : []);
1488
+ return Object.fromEntries(written.map((event) => [event.id, toShadowEvent(event)]));
1489
+ }
1490
+ /** See `unpushedIds` on the result for why `skipped` is not in this set. */
1491
+ var UNPUSHED_KINDS = ["conflict", "error"];
1492
+ /** Whether this outcome leaves a local edit that only exists locally, so the
1493
+ * pull must not overwrite the record and the baseline must not advance. */
1494
+ var isUnpushed = (kind) => UNPUSHED_KINDS.includes(kind);
1495
+ function tally(slug, attempts, localDeletes) {
1496
+ const outcomes = attempts.map((attempt) => attempt.outcome);
1497
+ const count = (kind) => outcomes.filter((outcome) => outcome.kind === kind).length;
1498
+ return {
1499
+ slug,
1500
+ created: count("created"),
1501
+ updated: count("updated"),
1502
+ conflicts: count("conflict"),
1503
+ localDeletes,
1504
+ skipped: outcomes.flatMap((outcome) => outcome.kind === "skipped" ? [outcome.message] : []),
1505
+ errors: outcomes.flatMap((outcome) => outcome.kind === "error" ? [outcome.message] : []),
1506
+ unpushedIds: attempts.filter((attempt) => isUnpushed(attempt.outcome.kind)).map((attempt) => attempt.eventId)
1507
+ };
1508
+ }
1509
+ /** Record ids whose local value no longer matches the baseline — edits that have
1510
+ * not reached Google.
1511
+ *
1512
+ * Pure, and deliberately built from `planRecord`, so it answers with exactly the
1513
+ * records a push WOULD have acted on. A private re-implementation would drift
1514
+ * from the push and protect the wrong set. */
1515
+ function locallyEditedIds(records, shadow, map, primaryKey, fields) {
1516
+ return records.map((record) => ({
1517
+ eventId: fieldText(record[primaryKey]),
1518
+ record
1519
+ })).filter(({ eventId, record }) => planRecord(eventId, record, shadow[eventId], map, primaryKey, fields).kind !== "unchanged").map(({ eventId }) => eventId);
1520
+ }
1521
+ /** The same set, read from the workspace.
1522
+ *
1523
+ * Needed when a push cannot run AT ALL — a calendar whose role degraded to
1524
+ * reader, a revoked grant, an IO failure. The pull still runs, since reading
1525
+ * needs no write access, and would overwrite exactly these records while
1526
+ * advancing their baseline past the edit (CodeRabbit review #2666). Computed
1527
+ * from the stored baseline alone, so it works precisely when Google is the
1528
+ * thing that is unreachable. */
1529
+ async function unsentLocalEdits(collection, workspaceRoot) {
1530
+ const { schema } = collection;
1531
+ const shadow = await loadCalendarShadow(schema.googleCalendar?.calendarId, workspaceRoot);
1532
+ return locallyEditedIds(await require_discovery.storeFor(collection, { workspaceRoot }).list(), shadow, pushableMap(schema.googleCalendar?.map ?? {}), schema.primaryKey, schema.fields);
1533
+ }
1534
+ /** Push one collection WITHOUT taking the calendar lock.
1535
+ *
1536
+ * The caller must already hold it. The scheduled push→pull cycle
1537
+ * (`collectionSync.ts`) runs inside the lock it took for the pull, and the lock
1538
+ * is not reentrant — going through `pushCalendarForCollection` there would make
1539
+ * the sync wait on itself forever. */
1540
+ async function pushCollectionNow(collection, workspaceRoot, deps = liveDeps) {
1541
+ const { schema, slug } = collection;
1542
+ const calendarId = schema.googleCalendar?.calendarId;
1543
+ const accessToken = await deps.accessToken();
1544
+ const meta = await deps.calendarMeta(accessToken, calendarId);
1545
+ if (isDeniedAccessRole(meta.accessRole)) return {
1546
+ kind: "read-only",
1547
+ accessRole: meta.accessRole ?? ""
1548
+ };
1549
+ const map = pushableMap(schema.googleCalendar?.map ?? {});
1550
+ const shadow = await loadCalendarShadow(calendarId, workspaceRoot);
1551
+ const records = await require_discovery.storeFor(collection, { workspaceRoot }).list();
1552
+ const ctx = {
1553
+ accessToken,
1554
+ calendarId,
1555
+ timeZone: meta.timeZone,
1556
+ map,
1557
+ bySource: bySourceField(map),
1558
+ primaryKey: schema.primaryKey,
1559
+ fields: schema.fields,
1560
+ shadow
1561
+ };
1562
+ const attempts = [];
1563
+ for (const record of records) {
1564
+ const eventId = fieldText(record[schema.primaryKey]);
1565
+ const outcome = await pushRecord(ctx, eventId, record);
1566
+ attempts.push({
1567
+ eventId,
1568
+ outcome
1569
+ });
1570
+ await saveCalendarShadow(calendarId, pushedShadow([outcome]), workspaceRoot);
1571
+ }
1572
+ const result = tally(slug, attempts, locallyDeletedIds(shadow, records.map((record) => fieldText(record[schema.primaryKey]))).length);
1573
+ if (result.errors.length > 0) log.warn("google", "calendar push finished with errors", {
1574
+ slug,
1575
+ errors: result.errors.length
1576
+ });
1577
+ return {
1578
+ kind: "pushed",
1579
+ result
1580
+ };
1581
+ }
1582
+ /** Push ONE collection's records to the calendar it declares.
1583
+ *
1584
+ * "Does this collection sync at all" is answered before "is Google linked", for
1585
+ * the reason `syncCalendarForCollection` gives: telling someone to link their
1586
+ * account for a collection that never declared a calendar sends them fixing the
1587
+ * wrong thing. */
1588
+ async function pushCalendarForCollection(slug, workspaceRoot, deps = liveDeps) {
1589
+ try {
1590
+ const collection = await deps.findCollection(slug, workspaceRoot);
1591
+ if (collection === null) return { kind: "not-a-calendar" };
1592
+ if (!await deps.isLinked()) return { kind: "not-linked" };
1593
+ return await withCalendarLock(collection.schema.googleCalendar?.calendarId, () => pushCollectionNow(collection, workspaceRoot, deps));
1594
+ } catch (error) {
1595
+ log.warn("google", "calendar push could not start", {
1596
+ slug,
1597
+ error: String(error)
1598
+ });
1599
+ return {
1600
+ kind: "failed",
1601
+ message: String(error)
1602
+ };
1603
+ }
1604
+ }
1605
+ //#endregion
1606
+ //#region src/google/collectionSync.ts
1607
+ var GOOGLE_CALENDAR_SYNC_TASK_ID = "system:google-calendar-sync";
1608
+ var DEFAULT_SYNC_INTERVAL_MS = 3600 * 1e3;
1609
+ function classifyWrite(eventId, kind) {
1610
+ if (kind === "ok") return { kind: "written" };
1611
+ if (kind === "invalid-id") return {
1612
+ kind: "unwritable",
1613
+ message: `write ${eventId}: invalid-id`
1614
+ };
1615
+ return {
1616
+ kind: "error",
1617
+ message: `write ${eventId}: ${kind}`
1618
+ };
1619
+ }
1620
+ function classifyDelete(eventId, kind) {
1621
+ if (kind === "ok") return { kind: "removed" };
1622
+ if (kind === "not-found") return { kind: "skipped" };
1623
+ if (kind === "invalid-id") return {
1624
+ kind: "unwritable",
1625
+ message: `delete ${eventId}: invalid-id`
1626
+ };
1627
+ return {
1628
+ kind: "error",
1629
+ message: `delete ${eventId}: ${kind}`
1630
+ };
1631
+ }
1632
+ async function applyEvent(collection, event, workspaceRoot) {
1633
+ const { schema } = collection;
1634
+ try {
1635
+ const store = require_discovery.storeFor(collection, { workspaceRoot });
1636
+ if (!store.write || !store.delete) return {
1637
+ kind: "unwritable",
1638
+ message: `collection '${collection.slug}' is read-only`
1639
+ };
1640
+ if (event.status === "cancelled") {
1641
+ const deleted = await store.delete(event.id);
1642
+ return classifyDelete(event.id, deleted.kind);
1643
+ }
1644
+ const record = toCollectionRecord(event, schema.googleCalendar?.map ?? {}, schema.primaryKey, schema.fields);
1645
+ const written = await store.write(event.id, mergeIntoExisting(await store.read(event.id), record));
1646
+ return classifyWrite(event.id, written.kind);
1647
+ } catch (error) {
1648
+ return {
1649
+ kind: "error",
1650
+ message: `apply ${event.id}: ${String(error)}`
1651
+ };
1652
+ }
1653
+ }
1654
+ /** The events of a window a pull may act on.
1655
+ *
1656
+ * A record the push just refused to send is edited on BOTH sides. Writing
1657
+ * Google's value over it destroys the local edit the push declined to resolve,
1658
+ * so the local one stands. Single-sourced because the record write and the
1659
+ * baseline write must agree exactly on which events they skip — disagreeing is
1660
+ * what would silently overwrite Google on the next push (#2620). */
1661
+ function pullableEvents(events, unpushed) {
1662
+ return events.filter((event) => !unpushed.has(event.id));
1663
+ }
1664
+ /** Report what an automatic push did, since nobody is watching a scheduled run.
1665
+ * A conflict or an error means that record now diverges from Google until
1666
+ * someone resolves it, which must not be silent. */
1667
+ function reportAutoPush(slug, result) {
1668
+ const { created, updated, conflicts, skipped, errors, unpushedIds } = result;
1669
+ if (created + updated > 0) log.info("google", "auto-pushed local calendar edits", {
1670
+ slug,
1671
+ created,
1672
+ updated
1673
+ });
1674
+ if (unpushedIds.length > 0) log.warn("google", "records the auto push could not send — the pull will leave them alone", {
1675
+ slug,
1676
+ conflicts,
1677
+ unpushedIds
1678
+ });
1679
+ if (skipped.length > 0) log.warn("google", "records the auto push skipped", {
1680
+ slug,
1681
+ skipped
1682
+ });
1683
+ if (errors.length > 0) log.warn("google", "auto push errors", {
1684
+ slug,
1685
+ errors
1686
+ });
1687
+ }
1688
+ var NOTHING_UNPUSHED = /* @__PURE__ */ new Set();
1689
+ /** A collection whose protection is unknown must not be pulled this run.
1690
+ *
1691
+ * Reported through the retryable `errors` channel rather than as a special case:
1692
+ * that already holds the sync token AND skips the baseline save, so the window
1693
+ * simply replays next run with nothing lost. Failing OPEN here — pulling with no
1694
+ * protection — would overwrite the very edits this exists to protect; the read
1695
+ * that failed is no evidence that the pull's own writes would fail too, so they
1696
+ * would land (CodeRabbit review #2666). */
1697
+ var PROTECTION_UNKNOWN = "could not work out which records to protect after a failed push";
1698
+ /** What ONE collection's pull must leave alone: only what ITS OWN push failed to
1699
+ * send.
1700
+ *
1701
+ * Scoped per collection because a calendar can back several of them, and a
1702
+ * conflict in one says nothing about the others. Sharing one set across the
1703
+ * group starved a collection that never even declares `autoPush`: it cannot
1704
+ * conflict, yet a neighbour's conflict froze its records — and the sync token
1705
+ * still advanced, so Google never resent them (Codex review #2666). */
1706
+ var unpushedFor = (unpushed, slug) => {
1707
+ const protection = unpushed.get(slug);
1708
+ return protection === void 0 ? NOTHING_UNPUSHED : protection;
1709
+ };
1710
+ /** What the calendar's BASELINE must leave alone: the union over every
1711
+ * collection.
1712
+ *
1713
+ * Deliberately not per collection, unlike the records above. `.push-state.json`
1714
+ * holds ONE baseline per calendar, shared by every collection on it, so there is
1715
+ * no per-collection baseline to hold back. Advancing it while any collection
1716
+ * still has an unresolved conflict is the failure that silently overwrites
1717
+ * Google on the next push, and holding it back only ever means "keep reporting
1718
+ * the conflict" — so the union is the safe side of an asymmetry the shared
1719
+ * storage forces.
1720
+ *
1721
+ * A `null` (unknown) entry contributes nothing, because that collection reports
1722
+ * a retryable error instead — which stops the baseline being saved at all. */
1723
+ var allUnpushed = (unpushed) => new Set([...unpushed.values()].flatMap((ids) => ids === null ? [] : [...ids]));
1724
+ /** What a collection's pull must protect when its push did not run AT ALL.
1725
+ *
1726
+ * Registering nothing here was a silent data loss of exactly the kind this
1727
+ * feature exists to prevent: a calendar whose role degrades to reader refuses
1728
+ * the whole push, yet the pull still runs — reading needs no write access — and
1729
+ * overwrote every unsent local edit while advancing its baseline past it, so the
1730
+ * next push could not even report the conflict (CodeRabbit review #2666).
1731
+ *
1732
+ * Protects the edited records rather than all of them, so an unchanged record
1733
+ * keeps syncing normally. `null` when even that could not be worked out — the
1734
+ * caller then refuses to pull the collection at all, because failing open here
1735
+ * destroys exactly what this protects. */
1736
+ async function protectUnsentEdits(collection, workspaceRoot) {
1737
+ try {
1738
+ const edited = await unsentLocalEdits(collection, workspaceRoot);
1739
+ if (edited.length > 0) log.warn("google", "protecting local edits a failed push could not send", {
1740
+ slug: collection.slug,
1741
+ edited
1742
+ });
1743
+ return new Set(edited);
1744
+ } catch (error) {
1745
+ log.warn("google", PROTECTION_UNKNOWN, {
1746
+ slug: collection.slug,
1747
+ error: String(error)
1748
+ });
1749
+ return null;
1750
+ }
1751
+ }
1752
+ /** Push every `autoPush` collection in this group, and answer with the records
1753
+ * whose local edit did not reach Google, keyed by collection.
1754
+ *
1755
+ * MUST run inside the calendar lock the caller already holds — hence
1756
+ * `pushCollectionNow` rather than `pushCalendarForCollection`, which would take
1757
+ * the same non-reentrant lock and wait on itself forever.
1758
+ *
1759
+ * A failed push must not stop the pull: the pull is what keeps the collection
1760
+ * fresh, and a revoked write grant is no reason to freeze reading. */
1761
+ async function pushAutoCollections(collections, workspaceRoot) {
1762
+ const unpushed = /* @__PURE__ */ new Map();
1763
+ for (const collection of collections.filter((entry) => entry.schema.googleCalendar?.autoPush)) try {
1764
+ const outcome = await pushCollectionNow(collection, workspaceRoot);
1765
+ if (outcome.kind === "pushed") {
1766
+ reportAutoPush(collection.slug, outcome.result);
1767
+ unpushed.set(collection.slug, new Set(outcome.result.unpushedIds));
1768
+ continue;
1769
+ }
1770
+ log.warn("google", "auto push did not run", {
1771
+ slug: collection.slug,
1772
+ reason: outcome.kind
1773
+ });
1774
+ unpushed.set(collection.slug, await protectUnsentEdits(collection, workspaceRoot));
1775
+ } catch (error) {
1776
+ log.warn("google", "auto push failed — pulling anyway", {
1777
+ slug: collection.slug,
1778
+ error: String(error)
1779
+ });
1780
+ unpushed.set(collection.slug, await protectUnsentEdits(collection, workspaceRoot));
1781
+ }
1782
+ return unpushed;
1783
+ }
1784
+ async function restartFullSync(accessToken, calendarId, workspaceRoot) {
1785
+ await clearCalendarSyncToken(calendarId, workspaceRoot);
1786
+ await clearCalendarShadow(calendarId, workspaceRoot);
1787
+ return await syncCalendarEvents(accessToken, { calendarId });
1788
+ }
1789
+ /** Sync ONE calendar and fan its events out to every collection bound to it.
1790
+ *
1791
+ * The fan-out is not an optimisation, it is correctness: the sync token is
1792
+ * keyed by `calendarId`, so syncing collection-by-collection would let the
1793
+ * first collection advance the shared token and leave every later collection
1794
+ * on the same calendar reading an already-consumed window — silently missing
1795
+ * those events forever. Fetch once, apply to all, then advance the token.
1796
+ * (Codex + CodeRabbit review on #2184.)
1797
+ *
1798
+ * Queued per calendar for the same reason the fan-out exists: two passes over
1799
+ * one calendar (a Refresh click landing during the scheduled run) would each
1800
+ * load the SAME stored token and walk the same window. That is idempotent —
1801
+ * writes are upserts by event id — but it is a wasted full walk. Queued, the
1802
+ * second pass resumes from the token the first just stored and fetches only
1803
+ * what is genuinely new. */
1804
+ async function syncCalendarGroup(calendarId, collections, workspaceRoot) {
1805
+ return await withCalendarLock(calendarId, () => syncCalendarGroupNow(calendarId, collections, workspaceRoot));
1806
+ }
1807
+ async function syncCalendarGroupNow(calendarId, collections, workspaceRoot) {
1808
+ const unpushed = await pushAutoCollections(collections, workspaceRoot);
1809
+ const accessToken = await getGoogleAccessToken();
1810
+ const first = await syncCalendarEvents(accessToken, {
1811
+ calendarId,
1812
+ syncToken: await loadCalendarSyncToken(calendarId, workspaceRoot) ?? void 0
1813
+ });
1814
+ const result = first.fullResyncRequired ? await restartFullSync(accessToken, calendarId, workspaceRoot) : first;
1815
+ const results = await applyWindowToGroup(collections, result.events, workspaceRoot, unpushed);
1816
+ if (windowFullyLanded(calendarId, results)) {
1817
+ await saveCalendarShadow(calendarId, shadowUpdates(result.events, allUnpushed(unpushed)), workspaceRoot);
1818
+ if (result.nextSyncToken) await advanceToken(calendarId, result.nextSyncToken, collections, workspaceRoot);
1819
+ }
1820
+ return results;
1821
+ }
1822
+ /** Apply one window to every collection on the calendar, honouring what each
1823
+ * one's own push protected. A collection whose protection could not be worked
1824
+ * out is not pulled at all — it reports a retryable error instead, which holds
1825
+ * the token and the baseline back for the whole group. */
1826
+ async function applyWindowToGroup(collections, events, workspaceRoot, unpushed) {
1827
+ const results = [];
1828
+ for (const collection of collections) {
1829
+ const protection = unpushedFor(unpushed, collection.slug);
1830
+ results.push(protection === null ? {
1831
+ slug: collection.slug,
1832
+ written: 0,
1833
+ removed: 0,
1834
+ unwritable: [],
1835
+ errors: [PROTECTION_UNKNOWN]
1836
+ } : await applyEventsToCollection(collection, events, workspaceRoot, protection));
1837
+ }
1838
+ return results;
1839
+ }
1840
+ /** Whether the token and baseline may advance past this window.
1841
+ *
1842
+ * Google never resends a window, so advancing past a failed write would lose
1843
+ * those events for good; holding the token back just replays them next run
1844
+ * (writes are idempotent). An `unwritable` event can never succeed, so it does
1845
+ * NOT hold the token — but it is logged loudly, since it will silently never
1846
+ * appear in the collection. */
1847
+ function windowFullyLanded(calendarId, results) {
1848
+ results.filter((entry) => entry.unwritable.length > 0).forEach((entry) => log.warn("google", "skipping calendar events that can never be stored", {
1849
+ calendarId,
1850
+ slug: entry.slug,
1851
+ unwritable: entry.unwritable
1852
+ }));
1853
+ const failed = results.filter((entry) => entry.errors.length > 0);
1854
+ failed.forEach((entry) => log.warn("google", "holding back calendar sync token after failed writes", {
1855
+ calendarId,
1856
+ slug: entry.slug,
1857
+ errors: entry.errors
1858
+ }));
1859
+ return failed.length === 0;
1860
+ }
1861
+ /** The baseline this window establishes: what Google now says per event, and
1862
+ * `null` for a cancelled one so a recreate cannot resume from a dead baseline.
1863
+ *
1864
+ * An event whose record the push could not send is left OUT, and that omission
1865
+ * is load-bearing. Advancing its baseline to Google's new value while the record
1866
+ * keeps the local one would make the next push read a plain one-sided edit —
1867
+ * no conflict to detect any more — and quietly overwrite Google. Held back, the
1868
+ * baseline stays older than both sides, so the conflict keeps being reported
1869
+ * until someone resolves it (#2620). */
1870
+ function shadowUpdates(events, unpushed = /* @__PURE__ */ new Set()) {
1871
+ const carried = pullableEvents(events, unpushed);
1872
+ return Object.fromEntries(carried.map((event) => [event.id, event.status === "cancelled" ? null : toShadowEvent(event)]));
1873
+ }
1874
+ /** Save the window's token unless every collection that consumed it was deleted
1875
+ * while the sync was in flight.
1876
+ *
1877
+ * The sync opens with a `discoverCollections()` snapshot, so a delete landing
1878
+ * mid-run has already cleared this calendar's token by the time we get here
1879
+ * (`releaseOrphanedCalendarToken`). Saving anyway would resurrect exactly the
1880
+ * orphan the delete removed, and the next collection on this calendar would
1881
+ * resume from a token describing records it never received (#2428).
1882
+ *
1883
+ * One survivor is enough: it still needs the incremental position. */
1884
+ async function advanceToken(calendarId, nextSyncToken, collections, workspaceRoot) {
1885
+ if (!await anySyncedCollectionSurvives(collections)) {
1886
+ log.info("google", "not advancing the sync token — every collection on this calendar was deleted mid-sync", { calendarId });
1887
+ return;
1888
+ }
1889
+ await saveCalendarSyncToken(calendarId, nextSyncToken, workspaceRoot);
1890
+ }
1891
+ async function pathExists(absPath) {
1727
1892
  try {
1728
- const shadow = ctx.shadow[eventId];
1729
- const plan = planRecord(eventId, record, shadow, ctx.map, ctx.primaryKey, ctx.fields);
1730
- if (plan.kind === "unchanged") return { kind: "unchanged" };
1731
- if (plan.kind === "create" || shadow === void 0) return await createOrAdopt(ctx, eventId, record);
1732
- return await updateFromRecord(ctx, eventId, record, plan.fields, shadow);
1733
- } catch (error) {
1734
- return writeFailure(eventId, error);
1893
+ await (0, node_fs_promises.stat)(absPath);
1894
+ return true;
1895
+ } catch {
1896
+ return false;
1735
1897
  }
1736
1898
  }
1737
- /** The baseline an outcome establishes, so the next push sees the record as
1738
- * unchanged instead of pushing it again. Empty for anything that wrote nothing
1739
- * and had no baseline to repair. */
1740
- function pushedShadow(outcomes) {
1741
- const written = outcomes.flatMap((outcome) => "event" in outcome && outcome.event !== void 0 ? [outcome.event] : []);
1742
- return Object.fromEntries(written.map((event) => [event.id, toShadowEvent(event)]));
1899
+ /** Liveness of the collections a sync just wrote to, checked against the skill
1900
+ * dir `deleteCollection` removes. `exists` is injected so the rule is testable
1901
+ * without a filesystem. An empty group has no survivor by definition. */
1902
+ async function anySyncedCollectionSurvives(collections, exists = pathExists) {
1903
+ return (await Promise.all(collections.map((collection) => exists(collection.skillDir)))).some(Boolean);
1743
1904
  }
1744
- function tally(slug, outcomes, localDeletes) {
1745
- const count = (kind) => outcomes.filter((outcome) => outcome.kind === kind).length;
1905
+ async function applyEventsToCollection(collection, events, workspaceRoot, unpushed) {
1906
+ const outcomes = [];
1907
+ for (const event of pullableEvents(events, unpushed)) outcomes.push(await applyEvent(collection, event, workspaceRoot));
1746
1908
  return {
1747
- slug,
1748
- created: count("created"),
1749
- updated: count("updated"),
1750
- conflicts: count("conflict"),
1751
- localDeletes,
1752
- skipped: outcomes.flatMap((outcome) => outcome.kind === "skipped" ? [outcome.message] : []),
1909
+ slug: collection.slug,
1910
+ written: outcomes.filter((outcome) => outcome.kind === "written").length,
1911
+ removed: outcomes.filter((outcome) => outcome.kind === "removed").length,
1912
+ unwritable: outcomes.flatMap((outcome) => outcome.kind === "unwritable" ? [outcome.message] : []),
1753
1913
  errors: outcomes.flatMap((outcome) => outcome.kind === "error" ? [outcome.message] : [])
1754
1914
  };
1755
1915
  }
1756
- async function pushNow(collection, workspaceRoot, deps) {
1757
- const { schema, slug } = collection;
1758
- const calendarId = schema.googleCalendar?.calendarId;
1759
- const accessToken = await deps.accessToken();
1760
- const meta = await deps.calendarMeta(accessToken, calendarId);
1761
- if (isDeniedAccessRole(meta.accessRole)) return {
1762
- kind: "read-only",
1763
- accessRole: meta.accessRole ?? ""
1764
- };
1765
- const map = pushableMap(schema.googleCalendar?.map ?? {});
1766
- const shadow = await loadCalendarShadow(calendarId, workspaceRoot);
1767
- const records = await require_discovery.storeFor(collection, { workspaceRoot }).list();
1768
- const ctx = {
1769
- accessToken,
1770
- calendarId,
1771
- timeZone: meta.timeZone,
1772
- map,
1773
- bySource: bySourceField(map),
1774
- primaryKey: schema.primaryKey,
1775
- fields: schema.fields,
1776
- shadow
1777
- };
1778
- const outcomes = [];
1779
- for (const record of records) {
1780
- const outcome = await pushRecord(ctx, fieldText(record[schema.primaryKey]), record);
1781
- outcomes.push(outcome);
1782
- await saveCalendarShadow(calendarId, pushedShadow([outcome]), workspaceRoot);
1916
+ /** A refresh token is what lets the scheduler run unattended; without one
1917
+ * there is nothing to sync with. */
1918
+ async function isGoogleLinked() {
1919
+ return Boolean((await loadGoogleTokens())?.refresh_token);
1920
+ }
1921
+ /** Group the declaring collections by the calendar they read, so each calendar
1922
+ * is fetched exactly once.
1923
+ *
1924
+ * Keyed by the CANONICAL id, not the declared one: an omitted `calendarId` and
1925
+ * an explicit `"primary"` address the same calendar and therefore share one
1926
+ * sync token, so grouping them apart would let one group advance the token out
1927
+ * from under the other — the very loss this grouping exists to prevent
1928
+ * (Codex review #2184). */
1929
+ function groupByCalendar(collections) {
1930
+ const groups = /* @__PURE__ */ new Map();
1931
+ for (const collection of collections) {
1932
+ const key = canonicalCalendarId(collection.schema.googleCalendar?.calendarId);
1933
+ groups.set(key, [...groups.get(key) ?? [], collection]);
1783
1934
  }
1784
- const result = tally(slug, outcomes, locallyDeletedIds(shadow, records.map((record) => fieldText(record[schema.primaryKey]))).length);
1785
- if (result.errors.length > 0) log.warn("google", "calendar push finished with errors", {
1786
- slug,
1787
- errors: result.errors.length
1788
- });
1789
- return {
1790
- kind: "pushed",
1791
- result
1792
- };
1935
+ return groups;
1793
1936
  }
1794
- /** Push ONE collection's records to the calendar it declares.
1937
+ /** The canonical calendar whose sync token nothing needs any more, or null.
1795
1938
  *
1796
- * "Does this collection sync at all" is answered before "is Google linked", for
1797
- * the reason `syncCalendarForCollection` gives: telling someone to link their
1798
- * account for a collection that never declared a calendar sends them fixing the
1799
- * wrong thing. */
1800
- async function pushCalendarForCollection(slug, workspaceRoot, deps = liveDeps) {
1939
+ * Sync tokens are keyed by calendar, NOT by collection, so a deleted
1940
+ * collection's token outlives it. Recreating a collection on the same calendar
1941
+ * then resumes from that token and receives only the delta — the new
1942
+ * collection never gets the history (#2428).
1943
+ *
1944
+ * Returns null while ANY remaining collection still reads that calendar:
1945
+ * clearing a live calendar's token costs a full re-walk on the next sync. The
1946
+ * comparison is on the CANONICAL id for the same reason `groupByCalendar` is —
1947
+ * an omitted `calendarId` and an explicit `"primary"` are one calendar. */
1948
+ function orphanedCalendarId(deleted, remaining) {
1949
+ if (!deleted.googleCalendar) return null;
1950
+ const key = canonicalCalendarId(deleted.googleCalendar.calendarId);
1951
+ return remaining.some((other) => other.googleCalendar && canonicalCalendarId(other.googleCalendar.calendarId) === key) ? null : key;
1952
+ }
1953
+ /** Drop the sync token of a just-deleted collection's calendar, unless another
1954
+ * collection still reads it. Call AFTER the delete lands — the check reads the
1955
+ * collections that survive it.
1956
+ *
1957
+ * Returns the cleared calendar id, or null when nothing was cleared. Never
1958
+ * throws: a failed cleanup must not fail the delete it follows. */
1959
+ async function releaseOrphanedCalendarToken(deleted, workspaceRoot) {
1801
1960
  try {
1802
- const collection = await deps.findCollection(slug, workspaceRoot);
1803
- if (collection === null) return { kind: "not-a-calendar" };
1804
- if (!await deps.isLinked()) return { kind: "not-linked" };
1805
- return await withCalendarLock(collection.schema.googleCalendar?.calendarId, () => pushNow(collection, workspaceRoot, deps));
1961
+ if (!deleted.googleCalendar) return null;
1962
+ const orphaned = orphanedCalendarId(deleted, (await require_discovery.discoverCollections({ workspaceRoot })).map((collection) => collection.schema));
1963
+ if (orphaned === null) return null;
1964
+ await clearCalendarSyncToken(orphaned, workspaceRoot);
1965
+ await clearCalendarShadow(orphaned, workspaceRoot);
1966
+ log.info("google", "cleared the sync token of a calendar no collection reads any more", { calendarId: orphaned });
1967
+ return orphaned;
1806
1968
  } catch (error) {
1807
- log.warn("google", "calendar push could not start", {
1808
- slug,
1969
+ log.warn("google", "could not release the deleted collection's calendar sync token", { error: String(error) });
1970
+ return null;
1971
+ }
1972
+ }
1973
+ /** Every declaring collection, grouped by the calendar it reads. */
1974
+ async function declaringGroups(workspaceRoot) {
1975
+ return groupByCalendar((await require_discovery.discoverCollections({ workspaceRoot })).filter((collection) => collection.schema.googleCalendar));
1976
+ }
1977
+ /** Whether a background sync of these groups may run at all.
1978
+ *
1979
+ * Authoring the collection before linking the account is an expected state,
1980
+ * not a failure. Checking once here keeps it a quiet skip instead of an
1981
+ * access-token throw per calendar, every hour, until the user links (#2188).
1982
+ * A user-triggered sync answers differently — it says so out loud. */
1983
+ async function backgroundSyncAllowed(groups) {
1984
+ if (groups.size === 0) return false;
1985
+ if (await isGoogleLinked()) return true;
1986
+ log.info("google", "skipping calendar sync — no Google account linked on this host", { calendars: groups.size });
1987
+ return false;
1988
+ }
1989
+ /** Run each group, isolating failures per calendar — one unreachable calendar
1990
+ * (or a revoked grant) must not stop the others. */
1991
+ async function runCalendarGroups(groups, workspaceRoot) {
1992
+ const results = [];
1993
+ for (const [calendarId, collections] of groups) try {
1994
+ results.push(...await syncCalendarGroup(calendarId, collections, workspaceRoot));
1995
+ } catch (error) {
1996
+ log.warn("google", "calendar sync failed", {
1997
+ calendarId,
1809
1998
  error: String(error)
1810
1999
  });
1811
- return {
1812
- kind: "failed",
1813
- message: String(error)
1814
- };
2000
+ results.push(...collections.map((collection) => ({
2001
+ slug: collection.slug,
2002
+ written: 0,
2003
+ removed: 0,
2004
+ unwritable: [],
2005
+ errors: [String(error)]
2006
+ })));
1815
2007
  }
2008
+ return results;
2009
+ }
2010
+ /** Sync every collection that declares `googleCalendar`. */
2011
+ async function syncDueCalendarCollections(workspaceRoot) {
2012
+ const groups = await declaringGroups(workspaceRoot);
2013
+ return await backgroundSyncAllowed(groups) ? await runCalendarGroups(groups, workspaceRoot) : [];
2014
+ }
2015
+ /** The groups whose calendar has never synced. A missing token IS the "created
2016
+ * since the last sync" signal — nothing else distinguishes a new collection
2017
+ * from an edited one on the write path this feeds (#2427).
2018
+ *
2019
+ * Self-silencing by construction: the first sync stores a token, so a calendar
2020
+ * matches at most once. `loadToken` is injected so the rule is testable without
2021
+ * a workspace on disk. */
2022
+ async function unsyncedGroups(groups, loadToken) {
2023
+ const checked = await Promise.all([...groups].map(async (entry) => await loadToken(entry[0]) === null ? entry : null));
2024
+ return new Map(checked.filter((entry) => entry !== null));
2025
+ }
2026
+ /** Sync only the calendars that have never synced — the first sync for a
2027
+ * just-created collection, which otherwise stays empty until the hourly
2028
+ * scheduler run (#2427). Cheap and safe to call on every config write. */
2029
+ async function syncNewCalendarCollections(workspaceRoot) {
2030
+ const pending = await unsyncedGroups(await declaringGroups(workspaceRoot), (calendarId) => loadCalendarSyncToken(calendarId, workspaceRoot));
2031
+ if (!await backgroundSyncAllowed(pending)) return [];
2032
+ log.info("google", "running the first sync for newly declared calendars", { calendars: [...pending.keys()] });
2033
+ return await runCalendarGroups(pending, workspaceRoot);
2034
+ }
2035
+ var liveManualSyncDeps = {
2036
+ loadGroups: declaringGroups,
2037
+ isLinked: isGoogleLinked,
2038
+ runGroups: runCalendarGroups
2039
+ };
2040
+ /** Sync the calendar ONE collection reads, on demand (the Refresh button).
2041
+ *
2042
+ * Deliberately syncs the whole group, not just `slug`: the sync token is keyed
2043
+ * by calendar, so consuming a window for one collection would leave the others
2044
+ * on that calendar reading an already-consumed one. Returns every result of the
2045
+ * group so the caller can report the requested slug's own counts.
2046
+ *
2047
+ * "Does this collection sync at all" is answered BEFORE "is Google linked":
2048
+ * telling someone to link their account for a collection that never declared a
2049
+ * calendar sends them fixing the wrong thing. */
2050
+ async function syncCalendarForCollection(slug, workspaceRoot, deps = liveManualSyncDeps) {
2051
+ const owning = [...await deps.loadGroups(workspaceRoot)].filter(([, collections]) => collections.some((collection) => collection.slug === slug));
2052
+ if (owning.length === 0) return { kind: "not-a-calendar" };
2053
+ if (!await deps.isLinked()) return { kind: "not-linked" };
2054
+ return {
2055
+ kind: "synced",
2056
+ results: await deps.runGroups(new Map(owning), workspaceRoot)
2057
+ };
2058
+ }
2059
+ /** Scheduler registration, shaped like `feedRefreshTaskDef` so hosts wire it
2060
+ * with a single line. */
2061
+ function googleCalendarSyncTaskDef(opts) {
2062
+ return {
2063
+ id: GOOGLE_CALENDAR_SYNC_TASK_ID,
2064
+ name: "Google Calendar sync",
2065
+ description: "Pulls changed Google Calendar events into any collection declaring `googleCalendar`, without invoking the LLM.",
2066
+ schedule: {
2067
+ type: _receptron_task_scheduler.SCHEDULE_TYPES.interval,
2068
+ intervalMs: opts?.intervalMs ?? DEFAULT_SYNC_INTERVAL_MS
2069
+ },
2070
+ missedRunPolicy: _receptron_task_scheduler.MISSED_RUN_POLICIES.runOnce,
2071
+ run: () => syncDueCalendarCollections(opts?.workspaceRoot ?? require_discovery.getWorkspaceRoot()).then(() => {})
2072
+ };
1816
2073
  }
1817
2074
  //#endregion
1818
2075
  //#region src/google/tasks.ts
@@ -2023,7 +2280,9 @@ exports.HTTP_CONFLICT = HTTP_CONFLICT;
2023
2280
  exports.HTTP_FORBIDDEN = HTTP_FORBIDDEN;
2024
2281
  exports.HTTP_PRECONDITION_FAILED = HTTP_PRECONDITION_FAILED;
2025
2282
  exports.MAX_LIST_RESULTS = MAX_LIST_RESULTS;
2283
+ exports.PROTECTION_UNKNOWN = PROTECTION_UNKNOWN;
2026
2284
  exports.PUSHABLE_SOURCE_FIELDS = PUSHABLE_SOURCE_FIELDS;
2285
+ exports.allUnpushed = allUnpushed;
2027
2286
  exports.anySyncedCollectionSurvives = anySyncedCollectionSurvives;
2028
2287
  exports.assertSafeMimeType = assertSafeMimeType;
2029
2288
  exports.authorizeGoogle = authorizeGoogle;
@@ -2077,6 +2336,7 @@ exports.isDeniedAccessRole = isDeniedAccessRole;
2077
2336
  exports.isGoogleApiError = isGoogleApiError;
2078
2337
  exports.isIsoDateTimeWithOffset = isIsoDateTimeWithOffset;
2079
2338
  exports.isTextMimeType = isTextMimeType;
2339
+ exports.isUnpushed = isUnpushed;
2080
2340
  exports.legacyGoogleTokenPath = legacyGoogleTokenPath;
2081
2341
  exports.listCalendarEvents = listCalendarEvents;
2082
2342
  exports.listCalendars = listCalendars;
@@ -2089,13 +2349,17 @@ exports.loadClientSecret = loadClientSecret;
2089
2349
  exports.loadGoogleTokens = loadGoogleTokens;
2090
2350
  exports.locallyChangedFields = locallyChangedFields;
2091
2351
  exports.locallyDeletedIds = locallyDeletedIds;
2352
+ exports.locallyEditedIds = locallyEditedIds;
2092
2353
  exports.mayAdoptExisting = mayAdoptExisting;
2093
2354
  exports.mergeGoogleTokens = mergeGoogleTokens;
2355
+ exports.mergeIntoExisting = mergeIntoExisting;
2094
2356
  exports.mergeShadow = mergeShadow;
2095
2357
  exports.orphanedCalendarId = orphanedCalendarId;
2096
2358
  exports.pickBoundary = pickBoundary;
2097
2359
  exports.planRecord = planRecord;
2360
+ exports.pullableEvents = pullableEvents;
2098
2361
  exports.pushCalendarForCollection = pushCalendarForCollection;
2362
+ exports.pushCollectionNow = pushCollectionNow;
2099
2363
  exports.pushableMap = pushableMap;
2100
2364
  exports.readDriveFile = readDriveFile;
2101
2365
  exports.releaseOrphanedCalendarToken = releaseOrphanedCalendarToken;
@@ -2120,6 +2384,8 @@ exports.toTaskListSummary = toTaskListSummary;
2120
2384
  exports.toTaskSummary = toTaskSummary;
2121
2385
  exports.uncompleteTask = uncompleteTask;
2122
2386
  exports.unlinkGoogle = unlinkGoogle;
2387
+ exports.unpushedFor = unpushedFor;
2388
+ exports.unsentLocalEdits = unsentLocalEdits;
2123
2389
  exports.unsyncedGroups = unsyncedGroups;
2124
2390
  exports.updateCalendarEvent = updateCalendarEvent;
2125
2391
  exports.updateTask = updateTask;