src/prep.js
// Agenda, prep checklist and follow-up template builders for meeting-prep. Pure and deterministic.
// Times are handled as absolute instants (UTC milliseconds); no local-time or DST arithmetic is done.
const ISO_INSTANT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})$/i;
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
export class PrepError extends Error {
constructor(code, message) {
super(message);
this.code = code;
}
}
// Parses an ISO 8601 instant that carries an explicit offset. Returns {ms, offsetMin} or throws.
export function parseInstant(value, label) {
if (typeof value !== "string") throw new PrepError("invalid_input", `${label} must be an ISO 8601 string`);
if (ISO_DATE.test(value)) throw new PrepError("invalid_input", `${label} is a date without a time (all-day event); an agenda needs start and end times`);
const m = ISO_INSTANT.exec(value);
if (!m) throw new PrepError("invalid_input", `${label} must be an ISO 8601 date-time with a UTC offset, e.g. 2026-11-26T15:00:00Z or 2026-11-26T10:00:00-05:00 (got "${String(value).slice(0, 40)}")`);
const [, y, mo, d, h, mi, s] = m.map((x, i) => (i >= 1 && i <= 6 ? Number(x ?? 0) : x));
const check = new Date(Date.UTC(y, mo - 1, d, h, mi, s));
if (check.getUTCMonth() !== mo - 1 || check.getUTCDate() !== d || h > 23 || mi > 59 || s > 59) throw new PrepError("invalid_input", `${label} is not a valid calendar date-time`);
const zone = m[7].toUpperCase();
let offsetMin = 0;
if (zone !== "Z") {
const sign = zone[0] === "-" ? -1 : 1;
offsetMin = sign * (Number(zone.slice(1, 3)) * 60 + Number(zone.slice(4, 6)));
if (Math.abs(offsetMin) > 14 * 60) throw new PrepError("invalid_input", `${label} has an out-of-range UTC offset`);
}
return { ms: Date.parse(value), offsetMin };
}
export function iso(ms) {
return new Date(ms).toISOString().replace(/\.000Z$/, "Z");
}
// Formats an instant in a fixed UTC offset (the one the event start was given in).
export function isoWithOffset(ms, offsetMin) {
if (offsetMin === 0) return iso(ms);
const local = new Date(ms + offsetMin * 60000).toISOString().slice(0, 19);
const sign = offsetMin < 0 ? "-" : "+";
const abs = Math.abs(offsetMin);
return `${local}${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`;
}
// ---------------------------------------------------------------------------------------------
// Event selection
// ---------------------------------------------------------------------------------------------
export function selectEvent(events, uid, nowMs, warnings) {
if (uid !== undefined) {
const ev = events.find((e) => e.uid === uid);
if (!ev) throw new PrepError("invalid_input", `No event with uid "${uid}"`);
return ev;
}
if (events.length === 1) return events[0];
const timed = [];
for (const e of events) {
try {
timed.push({ e, start: parseInstant(e.start, "start").ms, end: parseInstant(e.end, "end").ms });
} catch {
warnings.push(`Event "${e.uid}" skipped during selection: its start/end are not ISO date-times with offsets`);
}
}
timed.sort((a, b) => a.start - b.start || (a.e.uid < b.e.uid ? -1 : 1));
const next = timed.find((t) => t.end > nowMs);
if (!next) throw new PrepError("invalid_input", "No upcoming or ongoing event found; pass event_uid to choose one");
if (timed.length > 1) warnings.push(`Several events given; using the next one that has not ended: "${next.e.uid}" (pass event_uid to choose another)`);
return next.e;
}
// ---------------------------------------------------------------------------------------------
// Notes parsing (markdown). Notes are untrusted: they are only pattern-matched.
// ---------------------------------------------------------------------------------------------
const TOPIC_HEADING = /\b(agenda|topics?|discussion|to discuss|talking points|items)\b/i;
const PREP_HEADING = /\b(prep|preparation|before the meeting|pre-?reads?|to prepare|homework)\b/i;
const ATTENDEE_HEADING = /\b(attendees|participants|invitees|people)\b/i;
const OWNER_LABEL = /\b(?:owner|assignee|assigned to)\s*[:=]?\s*([\p{L}][\p{L}\p{N} .'-]{0,40}?)(?=[,;)\]]|$)/iu;
function ownerOf(text) {
const at = /(?:^|[\s(])@([\p{L}\p{N}][\p{L}\p{N}._-]*)/u.exec(text);
if (at) return at[1].replace(/[._-]+$/, "");
const lab = OWNER_LABEL.exec(text);
return lab ? lab[1].trim() : null;
}
/** Removes the owner marker (`@name` or `owner: Name`) from a topic line, plus any brackets it leaves empty. */
function stripOwner(text, owner) {
const esc = owner.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const out = text.replace(new RegExp(`(^|\\s)@${esc}(?![\\p{L}\\p{N}])`, "u"), "$1").replace(OWNER_LABEL, "");
return out.replace(/([([])\s*[,;]\s*/g, "$1").replace(/\s*[,;]\s*([)\]])/g, "$1").replace(/[([]\s*[)\]]/g, "").replace(/\s+[,;:-]\s*$/, "");
}
// A duration is only read from "(15 min)" / "[10m]" brackets, a trailing "- 10 min", or the words
// "min/mins/minutes". A bare "m" elsewhere is not a duration ("$10m ARR", "2m users").
const MIN_BRACKET = /[([]\s*(\d{1,3})\s*(?:min(?:ute)?s?|m)\s*[)\]]/i;
const MIN_TRAILING = /\s+(?:[-–—:]\s*(\d{1,3})\s*(?:min(?:ute)?s?|m)|(\d{1,3})\s*min(?:ute)?s?)\s*$/i;
const MIN_WORD = /(?<![\p{L}\p{N}$£€.,])(\d{1,3})\s*min(?:ute)?s?\b/iu;
function minutesOf(text) {
const m = MIN_BRACKET.exec(text) ?? MIN_TRAILING.exec(text) ?? MIN_WORD.exec(text);
return m ? Number(m[1] ?? m[2]) : null;
}
function stripMinutes(text) {
return text.replace(/\s*[([]\s*\d{1,3}\s*(?:min(?:ute)?s?|m)\s*[)\]]/i, "").replace(MIN_TRAILING, "").trim();
}
export function parseNotes(notes) {
const out = { actions: [], done: 0, topics: [], prep: [], attendees: [] };
if (!notes) return out;
const lines = String(notes).replace(/\r\n?/g, "\n").split("\n");
let fence = null;
let heading = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const f = /^ {0,3}(`{3,}|~{3,})/.exec(line);
if (fence) { if (f && f[1][0] === fence[0]) fence = null; continue; }
if (f) { fence = f[1]; continue; }
const h = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
if (h) { heading = h[2]; continue; }
const att = /^\s*(?:\*\*)?(attendees|participants|invitees)(?:\*\*)?\s*:\s*(.+)$/i.exec(line);
if (att) {
for (const a of att[2].split(/[,;]/)) if (a.trim()) out.attendees.push(a.trim().replace(/^@/, ""));
continue;
}
const box = /^\s*[-*+]\s+\[([ xX])\]\s+(.*\S)\s*$/.exec(line);
if (box) {
if (box[1] !== " ") { out.done++; continue; }
const text = box[2];
const due = /\b(\d{4}-\d{2}-\d{2})\b/.exec(text);
const owner = ownerOf(text);
out.actions.push({ text, ...(owner ? { owner } : {}), ...(due ? { due: due[1] } : {}), line: i + 1, ...(heading ? { section: heading } : {}) });
continue;
}
const item = /^\s*(?:[-*+]|\d+[.)])\s+(.*\S)\s*$/.exec(line);
if (item && heading) {
const text = item[1];
if (ATTENDEE_HEADING.test(heading) && !TOPIC_HEADING.test(heading)) out.attendees.push(text.replace(/^@/, ""));
else if (PREP_HEADING.test(heading)) out.prep.push(text);
else if (TOPIC_HEADING.test(heading)) {
const minutes = minutesOf(text);
const owner = ownerOf(text);
const topic = stripMinutes(owner ? stripOwner(text, owner) : text).replace(/\s{2,}/g, " ").trim() || text;
out.topics.push({ topic, ...(minutes ? { minutes } : {}), ...(owner ? { owner } : {}), source: "notes", line: i + 1 });
}
}
}
return out;
}
// ---------------------------------------------------------------------------------------------
// Agenda
// ---------------------------------------------------------------------------------------------
function attendeeName(a) {
if (typeof a === "string") return a.trim();
if (a && typeof a === "object") {
const name = typeof a.name === "string" ? a.name.trim() : "";
const email = typeof a.email === "string" ? a.email.trim() : "";
return name && email ? `${name} <${email}>` : name || email;
}
return "";
}
function dedupe(list, key = (x) => x.toLowerCase()) {
const seen = new Set();
return list.filter((x) => {
const k = key(x);
if (!k || seen.has(k)) return false;
seen.add(k);
return true;
});
}
export function buildAgenda(input, nowMs) {
const warnings = [];
const ev = selectEvent(input.events, input.event_uid, nowMs, warnings);
const s = parseInstant(ev.start, `Event "${ev.uid}" start`);
const e = parseInstant(ev.end, `Event "${ev.uid}" end`);
if (e.ms <= s.ms) throw new PrepError("invalid_input", `Event "${ev.uid}" ends before it starts`);
const duration = Math.floor((e.ms - s.ms) / 60000);
if (duration > 1440) throw new PrepError("invalid_input", `Event "${ev.uid}" is longer than 24 hours; split it into sessions`);
if (duration < 1) throw new PrepError("invalid_input", `Event "${ev.uid}" is shorter than one minute`);
if (s.offsetMin !== e.offsetMin) warnings.push("Start and end use different UTC offsets (e.g. across a DST change); durations use absolute time and item times use the start's offset");
const notes = parseNotes(input.notes);
// "Alice <alice@example.com>" and "Alice" are the same person; the first (most detailed) form wins.
const attendees = dedupe(
[...(Array.isArray(ev.attendees) ? ev.attendees.map(attendeeName) : []), ...notes.attendees].filter(Boolean),
(x) => x.replace(/<[^>]*>/, "").trim().toLowerCase() || x.toLowerCase(),
);
const topics = dedupe(
[
...(input.topics ?? []).map((t) => ({ topic: t.topic.trim(), ...(t.minutes ? { minutes: t.minutes } : {}), ...(t.owner ? { owner: t.owner } : {}), ...(t.notes ? { notes: t.notes } : {}), source: "input" })),
...notes.topics,
],
(t) => t.topic.toLowerCase(),
);
const open = notes.actions;
const reviewCap = Math.floor(duration * 0.25);
const review = open.length ? Math.min(Math.max(2, 2 * open.length), reviewCap) : 0;
if (open.length && !review) warnings.push("Meeting too short for a separate action-item review; review them asynchronously");
const wantedWrap = input.wrap_up_minutes ?? (duration >= 30 ? 5 : duration >= 15 ? 3 : 0);
const wrap = Math.max(0, Math.min(wantedWrap, duration - review - 1));
if (wrap < wantedWrap && input.wrap_up_minutes !== undefined) warnings.push(`Wrap-up shortened to ${wrap} min to leave time for topics`);
const available = duration - wrap - review;
const usingPlaceholder = topics.length === 0;
if (usingPlaceholder) topics.push({ topic: `Discussion: ${ev.summary || "untitled meeting"}`, source: "event_summary" });
const explicit = topics.filter((t) => t.minutes);
const flexible = topics.filter((t) => !t.minutes);
const parking = [];
const alloc = new Map();
const explicitSum = explicit.reduce((a, t) => a + t.minutes, 0);
if (explicitSum > available) {
warnings.push(`Requested topic time (${explicitSum} min) exceeds the ${available} min available; timed topics were scaled down proportionally`);
// Largest-remainder apportionment with at least 1 minute per kept topic; topics that cannot get a
// minute (more topics than minutes) go to the parking lot from the end of the list.
const fit = [...explicit];
while (fit.length > available) parking.unshift(fit.pop().topic);
const sum = fit.reduce((a, t) => a + t.minutes, 0);
const raw = fit.map((t) => (t.minutes * available) / sum);
const base = raw.map((r) => Math.max(1, Math.floor(r)));
let used = base.reduce((a, b) => a + b, 0);
while (used > available) {
const i = base.reduce((best, v, j) => (v > base[best] ? j : best), 0);
base[i]--;
used--;
}
const order = raw.map((r, i) => ({ i, frac: r - Math.floor(r) })).sort((a, b) => b.frac - a.frac || a.i - b.i);
for (let k = 0; used < available && order.length; k = (k + 1) % order.length) { base[order[k].i]++; used++; }
fit.forEach((t, i) => alloc.set(t, base[i]));
for (const t of flexible) parking.push(t.topic);
} else {
for (const t of explicit) alloc.set(t, t.minutes);
const rest = available - explicitSum;
if (flexible.length) {
const each = Math.floor(rest / flexible.length);
let extra = rest - each * flexible.length;
flexible.forEach((t) => {
const m = each + (extra > 0 ? 1 : 0);
if (extra > 0) extra--;
if (m >= 1) alloc.set(t, m);
else parking.push(t.topic);
});
}
}
if (parking.length) warnings.push(`${parking.length} topic(s) did not fit and were moved to the parking lot`);
const items = [];
if (review) {
items.push({ topic: `Review open action items (${open.length})`, minutes: review, notes: open.slice(0, 10).map((a) => a.text).join("; ") + (open.length > 10 ? "; …" : ""), source: "action_items" });
}
for (const t of topics) if (alloc.has(t)) items.push({ topic: t.topic, minutes: alloc.get(t), ...(t.owner ? { owner: t.owner } : {}), ...(t.notes ? { notes: t.notes } : {}), source: t.source });
const usedSoFar = items.reduce((a, it) => a + it.minutes, 0);
const buffer = duration - wrap - usedSoFar;
if (buffer > 0) items.push({ topic: "Open discussion / buffer", minutes: buffer, source: "buffer" });
if (wrap) items.push({ topic: "Wrap-up: decisions, owners and next steps", minutes: wrap, source: "wrap_up" });
let offset = 0;
for (const it of items) {
it.offset_minutes = offset;
it.start = iso(s.ms + offset * 60000);
it.local_start = isoWithOffset(s.ms + offset * 60000, s.offsetMin);
offset += it.minutes;
}
const agenda = {
title: input.title ?? (ev.summary || "Untitled meeting"),
event_uid: ev.uid,
start: iso(s.ms),
end: iso(e.ms),
local_start: isoWithOffset(s.ms, s.offsetMin),
duration_minutes: duration,
...(typeof ev.timezone === "string" ? { timezone: ev.timezone } : {}),
...(typeof ev.location === "string" && ev.location.trim() ? { location: ev.location.trim() } : {}),
attendees,
items,
prep: [],
carried_over_actions: open,
completed_actions_in_notes: notes.done,
parking_lot: parking,
warnings,
};
agenda.prep = prepChecklist(agenda, notes, usingPlaceholder).map((c) => c.task);
return { agenda, notes };
}
export function prepChecklist(agenda, notes, usingPlaceholder) {
const list = [];
const add = (task, source) => list.push({ task, source });
const meetingDay = agenda.start.slice(0, 10);
for (const p of notes.prep) add(`From your notes: ${p}`, "notes");
if (agenda.carried_over_actions.length) {
add(`Check the status of ${agenda.carried_over_actions.length} open action item(s) before the meeting`, "action_items");
for (const a of agenda.carried_over_actions.slice(0, 10)) {
const dueNote = a.due ? (a.due < meetingDay ? ` (overdue since ${a.due})` : ` (due ${a.due})`) : "";
add(a.owner ? `Ask ${a.owner} for an update: ${a.text}${dueNote}` : `Find an owner for: ${a.text}${dueNote}`, "action_items");
}
}
if (agenda.attendees.length) add(`Send the agenda to ${agenda.attendees.length} attendee(s) before ${agenda.local_start}`, "event");
else add("No attendees are listed on the event or in the notes; confirm who should attend", "event");
if (agenda.location) {
if (/^https:\/\/|^http:\/\//i.test(agenda.location)) add(`Test the meeting link: ${agenda.location}`, "event");
else add(`Confirm the location: ${agenda.location}`, "event");
} else add("The event has no location or meeting link; add one before the meeting", "event");
for (const it of agenda.items) if (it.owner && it.source !== "action_items") add(`Confirm ${it.owner} is ready to lead "${it.topic}" (${it.minutes} min)`, it.source);
if (usingPlaceholder) add("No agenda topics were given (topics input or an Agenda/Topics section in the notes); add topics to replace the open discussion slot", "agenda");
if (agenda.parking_lot.length) add(`${agenda.parking_lot.length} topic(s) did not fit: decide whether to drop, defer or extend the meeting`, "agenda");
return list;
}
// ---------------------------------------------------------------------------------------------
// Follow-up template (markdown with explicit placeholders; nothing is invented)
// ---------------------------------------------------------------------------------------------
const FILL = "_(fill in)_";
function mdEscapeInline(s) {
return String(s).replace(/([\\`*_[\]<>])/g, "\\$1").replace(/\n+/g, " ");
}
export function followUpMarkdown(agenda) {
const out = [];
out.push(`# Follow-up: ${mdEscapeInline(agenda.title)}`, "");
if (agenda.local_start || agenda.start) out.push(`- **When:** ${agenda.local_start ?? agenda.start}${agenda.duration_minutes ? ` (${agenda.duration_minutes} min)` : ""}`);
if (agenda.location) out.push(`- **Where:** ${mdEscapeInline(agenda.location)}`);
out.push(`- **Attendees:** ${agenda.attendees?.length ? agenda.attendees.map(mdEscapeInline).join(", ") : FILL}`, "");
out.push("## Summary", "", FILL, "");
out.push("## Decisions", "", `- ${FILL}`, "");
out.push("## Action items", "", "| Done | Action | Owner | Due |", "| --- | --- | --- | --- |");
for (const a of agenda.carried_over_actions ?? []) out.push(`| [ ] | ${mdEscapeInline(a.text).replace(/\|/g, "\\|")} (carried over) | ${a.owner ? mdEscapeInline(a.owner) : FILL} | ${a.due ?? FILL} |`);
out.push(`| [ ] | ${FILL} | ${FILL} | ${FILL} |`, "");
out.push("## Agenda recap", "");
(agenda.items ?? []).forEach((it, i) => {
out.push(`${i + 1}. **${mdEscapeInline(it.topic)}** (${it.minutes} min${it.owner ? `, ${mdEscapeInline(it.owner)}` : ""})`, ` - Notes: ${FILL}`);
});
out.push("");
if (agenda.parking_lot?.length) {
out.push("## Parking lot", "");
for (const p of agenda.parking_lot) out.push(`- ${mdEscapeInline(p)}`);
out.push("");
}
out.push("## Next meeting", "", FILL, "");
return out.join("\n");
}