Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions backend/src/calendar/assertOwnerAvailable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
import { formatBerlinDate, ownerCalendarOverlay } from './ownerCalendarOverlay';

export class OwnerAvailabilityError extends Error {
constructor(message: string, public statusCode: 409 | 503) { super(message); this.name = 'OwnerAvailabilityError'; }
}

/** Fresh read at the last boundary before any calendar write, including retries. */
export async function assertOwnerAvailable(client: DynamoDBDocumentClient | undefined, startIso: string, endIso: string, existingEventIds: Record<string,string> = {}): Promise<void> {
const from = formatBerlinDate(startIso), to = formatBerlinDate(endIso);
const projection = await ownerCalendarOverlay({ client, includeAll: true, excludeEventIds: existingEventIds }).project(from, to);
if (projection.connection.state !== 'connected') throw new OwnerAvailabilityError(`Cannot book: owner freebusy unavailable. ${projection.connection.reason || ''}`, 503);
const start = Date.parse(startIso), end = Date.parse(endIso);
const conflicts = projection.items.filter(item => item.startsAt && item.endsAt
? Date.parse(item.startsAt) < end && Date.parse(item.endsAt) > start
: item.startDate <= to && item.endDate >= from);
if (conflicts.length) throw new OwnerAvailabilityError(`Cannot book: owner calendar conflict: ${conflicts.map(item => item.label).join('; ')}. Use dataops calendar day ${from} to review.`, 409);
}
5 changes: 3 additions & 2 deletions backend/src/calendar/cardInvite.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { assertOwnerAvailable } from './assertOwnerAvailable';
import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
import type { Card, CardCalendarInvite, TaskStatus } from '../types';
import { getCardConsistent, updateCard, updateCardAdditive } from '../db/cards';
Expand Down Expand Up @@ -332,6 +333,7 @@ export async function syncCardInvite(
}, deps.calendarIds),
};
}
await assertOwnerAvailable(client, invite?.startIso || interval.startIso, interval.endIso, eventIds);
const reserved = await updateCard(client, card.id, {
expectedVersion: card.version,
patch: { eventTime: pending, guestEmails: silentLumaEvent ? [] : guests },
Expand Down Expand Up @@ -613,8 +615,7 @@ export async function adoptEventDate(
): Promise<{ card: Card; movedTasks: number }> {
if (!card.eventTime || card.eventTime.sync !== 'synced') return { card, movedTasks: 0 };
const date = todayIn(card.eventTime.timeZone, new Date(card.eventTime.startIso));
const followed = !card.anchorDate || (previous && card.anchorDate === todayIn(previous.timeZone, new Date(previous.startIso)));
if (!followed || card.anchorDate === date) return { card, movedTasks: 0 };
if (card.anchorDate === date) return { card, movedTasks: 0 };
const updated = await updateCardAdditive(client, card, () => ({ anchorDate: date }));
const { updatedCount } = await redateCardTemplateTasks(client, { ...updated, anchorDate: date }, {
reason: `Adopted event date ${date}`,
Expand Down
3 changes: 3 additions & 0 deletions backend/src/calendar/holdGoogleSync.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { assertOwnerAvailable, OwnerAvailabilityError } from './assertOwnerAvailable';
/**
* Google mirroring for calendar holds, per SOP
* `sop.events.calendar.creating-tentative-event-on-google-calendar`.
Expand Down Expand Up @@ -207,6 +208,7 @@ async function syncEvents(
if (calendars.includes('primary') || calendars.includes(HOLD_ORGANIZER)) {
return deferred('Hold calendars must name personal calendars explicitly; primary is the Orin organizer calendar.');
}
await assertOwnerAvailable(undefined, event.startIso, event.endIso, eventIds);
// Stable opaque UID enables recovery after partial writes without leaking the hold id.
const uid = `${createHash('sha256').update(event.eventKey).digest('hex')}@google.com`;
const body = eventBody(event);
Expand Down Expand Up @@ -281,6 +283,7 @@ async function syncEvents(
}
return { state: 'synced', eventIds };
} catch (error) {
if (error instanceof OwnerAvailabilityError) throw error;
const reason = error instanceof Error && error.message.startsWith('Google ')
? error.message : 'Google Calendar sync could not complete; retry the hold after checking the Orin connection.';
return deferred(reason);
Expand Down
73 changes: 73 additions & 0 deletions backend/src/calendar/ownerAvailability.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { OWNER_PERSONAL_CALENDAR } from '../identity/operatingIdentities';

const GOOGLE = 'https://www.googleapis.com/calendar/v3';
export type AvailabilityEvent = {
id?: string; summary?: string; status?: string; transparency?: string; htmlLink?: string;
start?: { date?: string; dateTime?: string }; end?: { date?: string; dateTime?: string };
calendarId?: string;
};

/** Only placeholders, never named lunches, meetings, routines or hard No blocks. */
export function isSoftEvent(event: AvailabilityEvent): boolean {
return /^(lunch|lunchtime|lunch break|обед|dtc event block|datatalks\.club event|dtc event|dtc buffer)$/i.test((event.summary || '').trim());
}

function bounds(event: AvailabilityEvent): [number, number] {
return [Date.parse(event.start?.dateTime || `${event.start?.date}T00:00:00Z`), Date.parse(event.end?.dateTime || `${event.end?.date}T00:00:00Z`)];
}

/** Read every calendar on the owner's account, including hidden calendars and every page.
* Freebusy closes gaps from private/redacted events; only fully explained busy time can be softened.
*/
export async function readOwnerAvailability(run: typeof fetch, token: string, from: string, to: string): Promise<AvailabilityEvent[]> {
const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
async function request(path: string, body?: unknown): Promise<any> {
const response = await run(`${GOOGLE}${path}`, { headers, signal: AbortSignal.timeout(15000), ...(body ? { method: 'POST', body: JSON.stringify(body) } : {}) });
if (!response.ok) throw new Error(`Owner calendar availability returned HTTP ${response.status}; no time can be booked`);
return response.json();
}
const primary = await request('/calendars/primary');
if (primary.id?.toLowerCase() !== OWNER_PERSONAL_CALENDAR) throw new Error('Availability requires Alexey’s Google Calendar connection; the organizer connection cannot enumerate his calendars');
const calendars = new Set<string>([OWNER_PERSONAL_CALENDAR]);
let page: string | undefined;
do {
const data = await request(`/users/me/calendarList?showHidden=true&maxResults=250${page ? `&pageToken=${encodeURIComponent(page)}` : ''}`);
if (!Array.isArray(data.items)) throw new Error('Invalid owner calendar list; availability is unknown');
for (const calendar of data.items) if (!calendar.deleted && calendar.id) calendars.add(calendar.id);
page = data.nextPageToken;
} while (page);
// Widen UTC bounds to include the complete Berlin dates in either DST offset.
const timeMin = new Date(Date.parse(`${from}T00:00:00Z`) - 86400000).toISOString();
const timeMax = new Date(Date.parse(`${to}T00:00:00Z`) + 2 * 86400000).toISOString();
const result: AvailabilityEvent[] = [];
const ids = [...calendars];
for (let offset = 0; offset < ids.length; offset += 50) {
const group = ids.slice(offset, offset + 50);
const freebusy = await request('/freeBusy', { timeMin, timeMax, items: group.map(id => ({ id })) });
for (const id of group) {
const availability = freebusy.calendars?.[id];
if (!availability || availability.errors?.length || !Array.isArray(availability.busy)) throw new Error('Owner calendar freebusy is incomplete; no time can be booked');
const events: AvailabilityEvent[] = [];
page = undefined;
do {
const query = new URLSearchParams({ timeMin, timeMax, singleEvents: 'true', maxResults: '2500', ...(page ? { pageToken: page } : {}) });
const data = await request(`/calendars/${encodeURIComponent(id)}/events?${query}`);
if (!Array.isArray(data.items)) throw new Error('Invalid owner calendar events; availability is unknown');
events.push(...data.items.map((event: AvailabilityEvent) => ({ ...event, calendarId: id })));
page = data.nextPageToken;
} while (page);
result.push(...events);
for (const busy of availability.busy) {
let gaps: Array<[number, number]> = [[Date.parse(busy.start), Date.parse(busy.end)]];
if (!gaps.every(([start, end]) => Number.isFinite(start) && Number.isFinite(end) && start < end)) throw new Error('Invalid freebusy interval; availability is unknown');
for (const event of events) {
if (event.status === 'cancelled' || event.transparency === 'transparent') continue;
const [start, end] = bounds(event);
gaps = gaps.flatMap(([a,b]) => start >= b || end <= a || !Number.isFinite(start + end) ? [[a,b]] : [...(a < start ? [[a,start]] : []), ...(end < b ? [[end,b]] : [])]) as Array<[number,number]>;
}
result.push(...gaps.map(([start,end], i) => ({ id: `freebusy:${busy.start}:${i}`, calendarId: id, summary: 'Busy (freebusy)', start: { dateTime: new Date(start).toISOString() }, end: { dateTime: new Date(end).toISOString() } })));
}
}
}
return result;
}
51 changes: 25 additions & 26 deletions backend/src/calendar/ownerCalendarOverlay.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { readOwnerAvailability, isSoftEvent } from './ownerAvailability';
import type { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
import type { CalendarOverlayConnection, CalendarOverlayItem, CalendarOverlayProjection, CalendarOverlayProvider } from './overlays';
import {
Expand All @@ -23,6 +24,7 @@ export interface OwnerCalendarConfig {
accountId?: string;
settings?: CalendarOverlaySettings;
includeAll?: boolean;
excludeEventIds?: Record<string, string>;
/** Berlin date the overlay counts as today; defaults to the current one. */
today?: string;
/** Free contiguous block length in minutes. Default 60; workshops use 90. */
Expand Down Expand Up @@ -200,6 +202,7 @@ export interface DapierConnectionOption {
connectionId: string;
provider: string;
title: string;
accountId?: string;
}

export interface OwnerCalendarEventContext {
Expand Down Expand Up @@ -357,7 +360,7 @@ export function shouldFilterOwnerCalendarEvent(

// Transparent (free/non-blocking) events (unless flights/conferences/vacations)
if (filterTransparent && context?.transparency === 'transparent') {
if (!/(flight|conference|vacation|trip)/i.test(s)) {
if (!/(flight|conference|vacation|trip|summit)/i.test(s)) {
return true;
}
}
Expand Down Expand Up @@ -416,6 +419,7 @@ export async function fetchDapierConnections(config?: OwnerCalendarConfig): Prom
).map((c) => ({
connectionId: c.connection_id,
provider: c.provider,
accountId: c.verified_account_id,
title: `${c.connection_id}${c.verified_account_id || c.account_title ? ` (${c.verified_account_id || c.account_title})` : ''}`,
}));
return { connections, ...(!connections.length ? { connectionProblem: `No writable Google Calendar connections are available to agent "${config?.agent || DAPIER_AGENT}". A Dapier operator must connect Google Calendar and grant this machine identity and agent the \`use\` operation.` } : {}) };
Expand Down Expand Up @@ -449,7 +453,12 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver

const brokerUrl = (config?.brokerUrl || DAPIER_BASE_URL).replace(/\/$/, '');
const agent = config?.agent || DAPIER_AGENT;
const connectionId = (config?.connectionId ?? activeSettings.connectionId).trim();
let connectionId = (config?.connectionId ?? activeSettings.connectionId).trim();
if (!config?.connectionId) {
const discovery = await fetchDapierConnections(config);
connectionId = discovery.connections.find(c => c.accountId?.toLowerCase() === OWNER_PERSONAL_CALENDAR)?.connectionId || '';
if (!connectionId) return blank({ state: 'unavailable', reason: discovery.connectionProblem || 'Alexey’s Google Calendar connection is required to check all his calendars.' });
}
if (!connectionId) return blank({ state: 'not-configured', reason: `No Dapier calendar connection selected. ${CONNECTION_OPERATOR_HINT}` });
const { credential, problem } = await readDapierCredential(config?.brokerCredential);

Expand Down Expand Up @@ -482,27 +491,13 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver
return blank({ state: 'unavailable', reason: `Calendar connection "${connectionId}" returned no access token.` });
}

// 2. Query Google Calendar API
const timeMin = `${from}T00:00:00Z`;
const timeMax = `${to}T23:59:59Z`;
const url = `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(OWNER_PERSONAL_CALENDAR)}/events?timeMin=${encodeURIComponent(timeMin)}&timeMax=${encodeURIComponent(timeMax)}&singleEvents=true&orderBy=startTime&maxResults=2500`;

let calRes: Response;
let events: import('./ownerAvailability').AvailabilityEvent[];
try {
calRes = await fetcher(url, {
headers: { Authorization: `Bearer ${tokenData.access_token}` },
signal: AbortSignal.timeout(15000),
});
} catch {
return blank({ state: 'unavailable', reason: 'Google Calendar could not be reached.' });
}

if (!calRes.ok) {
return blank({ state: 'unavailable', reason: `Google Calendar returned HTTP ${calRes.status}.` });
events = await readOwnerAvailability(fetcher, tokenData.access_token, from, to);
} catch (error) {
return blank({ state: 'unavailable', reason: error instanceof Error ? error.message : 'Owner freebusy failed; availability is unknown.' });
}

const calData = (await calRes.json()) as { items?: any[] };
const events = calData.items || [];
events = events.filter(e => !e.id || !e.calendarId || config?.excludeEventIds?.[e.calendarId] !== e.id);

const includeAll = Boolean(config?.includeAll);
const effectiveSettings: CalendarOverlaySettings = includeAll
Expand Down Expand Up @@ -595,7 +590,10 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver
startIso,
endIso,
};
if (shouldFilterOwnerCalendarEvent(event.summary, effectiveSettings, context)) continue;
// Display preferences cannot weaken scheduling policy. Hard blocks, including
// transparent all-day No/conference entries, always close the date.
if (isSoftEvent(event)) continue;
if (!isAllDay && event.transparency === 'transparent' && !/^no$/i.test(event.summary || '')) continue;

const summary = (event.summary || '').trim() || '(No title)';
let startDate: string;
Expand All @@ -613,6 +611,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver
continue;
}

if (startDate > to || endDate < from) continue;
const slot = determineSlotType(startIso, endIso, isAllDay);
const isSlotEvent = slot !== 'outside';

Expand Down Expand Up @@ -644,7 +643,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver

result.push({
provider: 'owner-calendar',
id: `owner-calendar:${item.event.id}`,
id: `owner-calendar:${item.event.calendarId}:${item.event.id}`,
startDate: item.startDate,
endDate: item.endDate,
label,
Expand All @@ -665,7 +664,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver
// are never projected as items. They only decide which slots are open.
// All-day blockers (vacations, conferences, flights, etc.) close the whole day.
const allDayBlockers = validEvents.filter(
(e) => e.isAllDay || e.slot === 'all-day' || (/vacation|holiday|flight|conference|trip/i.test(e.summary) && e.isSlotEvent),
(e) => e.isAllDay || e.slot === 'all-day' || (/vacation|holiday|flight|conference|trip|summit/i.test(e.summary) && e.isSlotEvent),
);

// Project available slots across all weekdays in the range.
Expand Down Expand Up @@ -696,7 +695,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver

// Check Midday Slot (operational window 11:30–14:00, preferred start 12:30 Berlin time)
if (wantMidday) {
const busy = busyIntervalsInWindow('midday', dayTimedEvents);
const busy = dayTimedEvents.map(e => ({ start: e.startDate < curDate ? '00:00' : formatBerlinTime(e.startIso!), end: e.endDate > curDate || !e.endIso ? '24:00' : formatBerlinTime(e.endIso) }));
if (isWindowFreeForDuration('midday', busy, durationMinutes)) {
result.push({
provider: 'owner-calendar',
Expand All @@ -716,7 +715,7 @@ export function ownerCalendarOverlay(config?: OwnerCalendarConfig): CalendarOver
// preferred start 17:00; 90-min workshop shape anchors at 16:30)
// Per SOP: offered on Monday and Tuesday only (US guests)
if (wantEvening && (dayOfWeek === 1 || dayOfWeek === 2)) {
const busy = busyIntervalsInWindow('evening', dayTimedEvents);
const busy = dayTimedEvents.map(e => ({ start: e.startDate < curDate ? '00:00' : formatBerlinTime(e.startIso!), end: e.endDate > curDate || !e.endIso ? '24:00' : formatBerlinTime(e.endIso) }));
if (isWindowFreeForDuration('evening', busy, durationMinutes)) {
result.push({
provider: 'owner-calendar',
Expand Down
9 changes: 9 additions & 0 deletions backend/src/events/guestAgreement.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface GuestAgreement { agreedFrom?: string; agreedTo?: string }
export function validateGuestAgreement(input: GuestAgreement, requestedDate?: string): void {
for (const key of ['agreedFrom', 'agreedTo'] as const) {
const value = input[key];
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(Date.parse(`${value}T12:00:00Z`)) || new Date(`${value}T12:00:00Z`).toISOString().slice(0,10) !== value) throw new Error('Record the guest agreement with agreedFrom and agreedTo as real YYYY-MM-DD dates before scheduling');
}
if (input.agreedFrom! > input.agreedTo!) throw new Error('Guest agreement dates must be in order');
if (requestedDate && (requestedDate < input.agreedFrom! || requestedDate > input.agreedTo!)) throw new Error('Requested date is outside the guest agreement');
}
Loading
Loading