Skip to content

Module 1 practice — Apps Script in five small steps

Goes with: Module 1 — Gather · Session 12

Five short functions, each teaching one idea behind CoS Gather. Run them one at a time and read the log. Everything here is read-only — nothing is sent, changed, or saved — and it lives in its own project, so it can't break anything else.

Setup (5 minutes)

  1. Go to script.google.com and click New project.
  2. Click Untitled project at the top and rename it Module 1 Practice.
  3. In Code.gs, select everything (Ctrl+A), delete it, and paste the full script from the end of this page.
  4. Click Save (Ctrl+S).
  5. In the toolbar, pick step1_hello from the function dropdown and click Run.
  6. The first run asks for permission: click Review permissions, choose your account. If you see "Google hasn't verified this app," click Advanced → Go to Module 1 Practice (unsafe) → Allow. It's your own script reading your own data.
  7. The Execution log opens at the bottom. That's where every step reports what it found.

Step 1 — Who is running this?

Run: step1_hello

You should see: your email address, your calendar's time zone, and your local time.

The idea: a script always runs as the person who runs it. Session.getActiveUser() and CalendarApp.getDefaultCalendar() are yours — the same code run by a colleague reads their calendar, never yours. That's why the CoS build kit works for anyone without changes.

Try this: change the date format 'EEE MMM d, h:mm a' to 'yyyy-MM-dd HH:mm' and run again.

Step 2 — Today's meetings, and a rule as code

Run: step2_todaysMeetings

You should see: one line per meeting today — time, title, Organizer? YES/NO, and guest count.

The idea: the one-Gem Chief of Staff was told to check whether you organized each meeting. Here it's one line:

const organizer = e.isOwnedByMe() ? 'YES' : 'NO';

Same answer every run. In CoS Gather, YES sets the floor for your role to ACCOUNTABLE before any AI step sees the meeting.

Try this: list tomorrow instead — add start.setDate(start.getDate() + 1); on the line right after const start = startOfToday_(tz); — end is calculated from start, so it moves too.

Step 3 — Yesterday's email, with a noise rule

Run: step3_yesterdaysEmail

You should see: KEEP and SKIP lines for up to 25 threads from yesterday, whether you wrote in each kept thread, and a count at the end.

The idea: calendar notifications and auto-replies have fixed formats, so a pattern (PRACTICE.NOISE at the top of the script) removes them before an AI ever reads them. "You wrote in this thread" is a fact, so code decides it too.

Try this: add a word that's noise in your inbox. Put it inside the pattern with a bar, for example …|automatic reply|newsletter)\b, and run again — the count of skipped threads should change.

On a Monday, "yesterday" is Sunday, so the list may be short. CoS Gather uses the previous business day instead.

Step 4 — Your action items from Gemini notes

Run: step4_myActionItems

You should see: how many Gemini notes emails you received in the last 14 days, then one line per action item assigned to you: date, meeting, task.

The idea: Gemini notes emails follow a fixed format — the subject is Notes: "Meeting title" Oct 19, 2026, and the "Suggested next steps" section lists items as [Owner Name] Task. Code can read that reliably, so the AI steps get your action items as facts instead of hunting for them.

Try this: set PRACTICE.NOTES_DAYS to 30. Or look up a colleague's items: in step4_myActionItems, replace nameFromEmail_(Session.getActiveUser().getEmail()) with their name in lower case, e.g. 'jane doe'.

Step 5 — Refs: what the AI sees vs. what code keeps

Run: step5_refs

You should see: today's meetings twice — first as a short list with E1, E2… and no links, then as a link map from each ref to its calendar URL.

The idea: in testing, a model told never to touch links still changed one character in a calendar URL. So the AI steps only ever see refs; code keeps the URLs and puts real links back in at the end.

Try this: copy one URL from the link map into your browser and check it opens the right meeting. That's the "check it against what you know" habit from the session.

When something goes wrong

What you see What to do
"Google hasn't verified this app" Expected for your own scripts. Advanced → Go to Module 1 Practice (unsafe) → Allow.
The log is empty or says 0 events Nothing matched — check you have meetings today (step 2/5) or email yesterday (step 3).
0 Gemini notes emails You haven't had meetings with Gemini notes turned on in the window. Try NOTES_DAYS: 30.
Notes found but 0 action items are yours Your name in the notes doesn't match your email name (e.g. "Rob" vs "robert"). Use the "Try this" in step 4 with the name as it appears in the notes.
It asks for permission again after an edit Normal when the script starts using a new service. Approve it again.
ReferenceError or SyntaxError The paste was incomplete. Select all in Code.gs, delete, paste the whole script again.

The script

/**
 * CoS Build Kit — Module 1 practice: Apps Script in five small steps.
 *
 * Read-only: nothing is sent, changed, or saved.
 * Run one step at a time: pick it in the function dropdown, click Run, read the Execution log.
 */

const PRACTICE = {
  NOTES_DAYS: 14,   // Step 4: how far back to look for Gemini notes emails
  // Step 3: subjects that are noise. Add your own between the | bars.
  NOISE: /^(invitation|updated invitation|accepted|declined|canceled event|out of office|automatic reply)\b/i,
};

// STEP 1 — Who is running this? -------------------------------------------
function step1_hello() {
  const me = Session.getActiveUser().getEmail();
  const tz = CalendarApp.getDefaultCalendar().getTimeZone();
  Logger.log('Hello, ' + me);
  Logger.log('Your calendar time zone: ' + tz);
  Logger.log('Your local time right now: ' + Utilities.formatDate(new Date(), tz, 'EEE MMM d, h:mm a'));
}

// STEP 2 — Today's meetings, and the organizer check as code ---------------
function step2_todaysMeetings() {
  const cal = CalendarApp.getDefaultCalendar();
  const tz = cal.getTimeZone();
  const start = startOfToday_(tz);
  const end = new Date(start.getTime() + 24 * 60 * 60 * 1000);
  const events = cal.getEvents(start, end);

  Logger.log(events.length + ' events on your calendar today');
  events.forEach(e => {
    const when = e.isAllDayEvent() ? 'all day' : Utilities.formatDate(e.getStartTime(), tz, 'h:mm a');
    const organizer = e.isOwnedByMe() ? 'YES' : 'NO';  // one line, same answer every run
    Logger.log(`${when} | ${e.getTitle()} | Organizer? ${organizer} | guests: ${e.getGuestList().length}`);
  });
}

// STEP 3 — Yesterday's email, with a noise rule ----------------------------
function step3_yesterdaysEmail() {
  const tz = CalendarApp.getDefaultCalendar().getTimeZone();
  const me = Session.getActiveUser().getEmail().toLowerCase();
  const today = startOfToday_(tz);
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
  const query = `after:${Math.floor(yesterday / 1000)} before:${Math.floor(today / 1000)} -category:promotions -category:social`;
  const threads = GmailApp.search(query, 0, 25);

  let kept = 0, skipped = 0;
  threads.forEach(t => {
    const subject = t.getFirstMessageSubject();
    if (PRACTICE.NOISE.test(subject)) {
      skipped++;
      Logger.log('SKIP  ' + subject);
      return;
    }
    kept++;
    const youReplied = t.getMessages().some(m => m.getFrom().toLowerCase().includes(me));
    Logger.log(`KEEP  ${subject} | you wrote in this thread: ${youReplied ? 'yes' : 'no'}`);
  });
  Logger.log(`${kept} kept, ${skipped} skipped as noise (first 25 threads from yesterday)`);
}

// STEP 4 — Your action items from Gemini notes -----------------------------
function step4_myActionItems() {
  const myName = nameFromEmail_(Session.getActiveUser().getEmail());
  const threads = GmailApp.search(`from:[email protected] newer_than:${PRACTICE.NOTES_DAYS}d`, 0, 30);
  Logger.log(`${threads.length} Gemini notes emails in the last ${PRACTICE.NOTES_DAYS} days. Looking for items owned by "${myName}".`);

  let found = 0;
  threads.forEach(t => {
    const meeting = parseNotesSubject_(t.getFirstMessageSubject());
    if (!meeting) return;
    actionItemsFor_(t.getMessages()[0].getPlainBody(), myName).forEach(item => {
      found++;
      Logger.log(`${meeting.date} | ${meeting.title} | ${item}`);
    });
  });
  Logger.log(found + ' action items are yours');
}

// STEP 5 — Refs: what an AI step sees vs. what only code keeps -------------
function step5_refs() {
  const cal = CalendarApp.getDefaultCalendar();
  const tz = cal.getTimeZone();
  const start = startOfToday_(tz);
  const events = cal.getEvents(start, new Date(start.getTime() + 24 * 60 * 60 * 1000));

  const linkMap = {};
  const forTheAI = events.map((e, i) => {
    const ref = 'E' + (i + 1);
    linkMap[ref] = eventLink_(e, cal.getId(), tz);   // the URL stays here
    return { ref, title: e.getTitle(), organizer: e.isOwnedByMe() };
  });
  Logger.log('What an AI step would see (no URLs):\n' + JSON.stringify(forTheAI, null, 2));
  Logger.log('What only code keeps (the link map):\n' + JSON.stringify(linkMap, null, 2));
}

// ---------- helpers ----------

function startOfToday_(tz) {
  return new Date(Utilities.formatDate(new Date(), tz, "yyyy-MM-dd'T'00:00:00XXX"));
}

// "[email protected]" → "jane doe"
function nameFromEmail_(email) {
  return email.split('@')[0].split(/[._-]/).join(' ').toLowerCase();
}

// Notes: “Weekly Planning” Nov 4, 2026  →  { title: "Weekly Planning", date: "Nov 4, 2026" }
function parseNotesSubject_(subject) {
  const m = subject.match(/^Notes:\s*[“"](.+?)[”"]\s+([A-Z][a-z]{2} \d{1,2}, \d{4})/);
  return m ? { title: m[1], date: m[2] } : null;
}

// Finds "[Owner Name] task…" items after "Suggested next steps" and keeps the ones you own
function actionItemsFor_(body, myName) {
  const start = body.search(/Suggested next steps/i);
  if (start < 0) return [];
  const section = body.slice(start).split(/You should review Gemini|Please provide feedback/i)[0];
  const items = [];
  const re = /\[([^\]]+)\]\s*([^\[]+)/g;
  let m;
  while ((m = re.exec(section)) !== null) {
    if (m[1].trim().toLowerCase() === myName) items.push(m[2].replace(/\s+/g, ' ').trim());
  }
  return items;
}

// Calendar has no "event URL" method, so build the standard link (recurring meetings need the start time)
function eventLink_(e, calId, tz) {
  let id = e.getId().replace(/@google\.com$/, '');
  if (e.isRecurringEvent()) {
    id += '_' + (e.isAllDayEvent()
      ? Utilities.formatDate(e.getAllDayStartDate(), tz, 'yyyyMMdd')
      : Utilities.formatDate(e.getStartTime(), 'UTC', "yyyyMMdd'T'HHmmss'Z'"));
  }
  return 'https://calendar.google.com/calendar/event?eid=' + Utilities.base64Encode(id + ' ' + calId).replace(/=+$/, '');
}

Build kit home · 1 Gather · 2 Analyst · 3 Writer · 4 Send · 5 Build your own