Written with Claude Code to my requirements. I directed and fact-checked it; I didn't write it. All data it generates is made up.
The engine: staffed-hours math, the health check, the ownership queue, reminders, the weekly scorecard, sorting and scoring.
/**
* InboxOwner core: response-time audit, ownership/SLA status and rules triage
* for a shared inbox.
*
* Plain JavaScript with no dependencies, so the same file runs in the browser
* demo, in Node tests and in Google Apps Script (where it reads a real Gmail
* inbox).
*
* Time convention: every timestamp is "studio wall-clock milliseconds", i.e.
* Date.UTC(year, month, day, hour, minute) of the local time at the business.
* Callers convert real dates once at the edge; nothing in here depends on the
* machine's time zone.
*/
(function (root) {
'use strict';
const HOUR = 3600000;
const MIN = 60000;
const DAY = 24 * HOUR;
/* ------------------------------------------------------------ helpers */
function median(xs) { return quantile(xs, 0.5); }
// Linear-interpolated quantile (same method as Google Sheets PERCENTILE).
function quantile(xs, q) {
if (!xs.length) return null;
const s = xs.slice().sort((a, b) => a - b);
const pos = (s.length - 1) * q;
const lo = Math.floor(pos), hi = Math.ceil(pos);
return s[lo] + (s[hi] - s[lo]) * (pos - lo);
}
function round(x, d) { const f = Math.pow(10, d || 0); return Math.round(x * f) / f; }
/* ----------------------------------------------------- business hours */
/**
* hours: {0..6: [openHour, closeHour] | null}, 0 = Sunday.
* Returns business minutes between two wall-clock timestamps.
*/
function businessMinutes(start, end, hours) {
if (end <= start) return 0;
let total = 0;
let dayStart = Math.floor(start / DAY) * DAY;
while (dayStart < end) {
const h = hours[new Date(dayStart).getUTCDay()];
if (h) {
const open = dayStart + h[0] * HOUR, close = dayStart + h[1] * HOUR;
const a = Math.max(open, start), b = Math.min(close, end);
if (b > a) total += (b - a) / MIN;
}
dayStart += DAY;
}
return total;
}
/** Adds business minutes to a wall-clock timestamp (used for SLA due times). */
function addBusinessMinutes(start, minutes, hours) {
let t = start, left = minutes;
for (let guard = 0; guard < 400; guard++) {
const dayStart = Math.floor(t / DAY) * DAY;
const h = hours[new Date(dayStart).getUTCDay()];
if (h) {
const open = dayStart + h[0] * HOUR, close = dayStart + h[1] * HOUR;
const from = Math.max(t, open);
if (from < close) {
const avail = (close - from) / MIN;
if (avail >= left) return from + left * MIN;
left -= avail;
}
}
t = dayStart + DAY;
}
throw new Error('addBusinessMinutes: no business hours configured');
}
/* ------------------------------------------------------------- audit */
/**
* Per-thread facts. A thread is {id, category?, messages:[{from:'customer'|'staff', staff?, at}]}
* sorted by time. Only metadata is used; message bodies are never needed.
*/
function analyzeThread(thread, cfg) {
const msgs = thread.messages;
const firstIn = msgs.find(m => m.from === 'customer');
if (!firstIn) return null; // outbound-only thread: not a customer request
const firstReply = msgs.find(m => m.from === 'staff' && m.at > firstIn.at);
const replyAt = firstReply ? firstReply.at : null;
// Duplicate reply: two or more different staff answer the same customer
// message before the customer writes again.
let duplicate = false;
for (let i = 0; i < msgs.length; i++) {
if (msgs[i].from !== 'customer') continue;
const repliers = new Set();
for (let j = i + 1; j < msgs.length && msgs[j].from !== 'customer'; j++) repliers.add(msgs[j].staff);
if (repliers.size > 1) { duplicate = true; break; }
}
const last = msgs[msgs.length - 1];
const awaiting = last.from === 'customer';
// Oldest customer message that is still unanswered (drives SLA).
let waitingSince = null;
if (awaiting) {
for (let i = msgs.length - 1; i >= 0 && msgs[i].from === 'customer'; i--) waitingSince = msgs[i].at;
}
const age = cfg.asOf - firstIn.at;
return {
id: thread.id,
category: thread.category || null,
firstIn: firstIn.at,
firstReplyBy: firstReply ? firstReply.staff : null,
frtMinutes: replyAt === null ? null : businessMinutes(firstIn.at, replyAt, cfg.hours),
frtClockHours: replyAt === null ? null : (replyAt - firstIn.at) / HOUR,
// Only judge a thread at 24h/48h once it is at least that old.
unanswered24: age >= 24 * HOUR ? (replyAt === null || replyAt - firstIn.at > 24 * HOUR) : null,
unanswered48: age >= 48 * HOUR ? (replyAt === null || replyAt - firstIn.at > 48 * HOUR) : null,
neverAnswered: replyAt === null,
duplicate,
awaiting,
waitingSince,
staffReplies: msgs.filter(m => m.from === 'staff').map(m => m.staff),
};
}
/** Inbox health check over a lookback window ending at cfg.asOf. */
function audit(threads, cfg) {
const from = cfg.asOf - (cfg.lookbackDays || 90) * DAY;
const rows = threads.map(t => analyzeThread(t, cfg)).filter(r => r && r.firstIn >= from && r.firstIn <= cfg.asOf);
const answered = rows.filter(r => r.frtMinutes !== null);
const frt = answered.map(r => r.frtMinutes / 60);
const judged24 = rows.filter(r => r.unanswered24 !== null);
const judged48 = rows.filter(r => r.unanswered48 !== null);
const pct = (num, den) => den.length ? num.length / den.length : null;
const byCategory = {};
rows.forEach(r => {
const k = r.category || 'uncategorized';
(byCategory[k] = byCategory[k] || []).push(r);
});
const categories = Object.keys(byCategory).map(k => {
const rs = byCategory[k];
const f = rs.filter(r => r.frtMinutes !== null).map(r => r.frtMinutes / 60);
const j48 = rs.filter(r => r.unanswered48 !== null);
return {
category: k, threads: rs.length,
medianFrtHours: f.length ? round(median(f), 2) : null,
p90FrtHours: f.length ? round(quantile(f, 0.9), 2) : null,
unanswered48: j48.length ? round(j48.filter(r => r.unanswered48).length / j48.length, 4) : null,
duplicateRate: round(rs.filter(r => r.duplicate).length / rs.length, 4),
};
}).sort((a, b) => b.threads - a.threads);
// Arrival heatmap: weekday (0=Sun) × hour of first customer message.
const heat = Array.from({ length: 7 }, () => Array(24).fill(0));
rows.forEach(r => { const d = new Date(r.firstIn); heat[d.getUTCDay()][d.getUTCHours()]++; });
const outsideHours = rows.filter(r => {
const d = new Date(r.firstIn), h = cfg.hours[d.getUTCDay()];
return !h || d.getUTCHours() < h[0] || d.getUTCHours() >= h[1];
}).length;
// Who carries the inbox: share of all staff replies.
const replyCounts = {};
rows.forEach(r => r.staffReplies.forEach(s => { replyCounts[s] = (replyCounts[s] || 0) + 1; }));
const totalReplies = Object.values(replyCounts).reduce((a, b) => a + b, 0);
const staff = Object.keys(replyCounts).map(s => ({ staff: s, replies: replyCounts[s], share: round(replyCounts[s] / totalReplies, 4) }))
.sort((a, b) => b.replies - a.replies);
return {
window: { from, to: cfg.asOf, days: cfg.lookbackDays || 90 },
threads: rows.length,
answered: answered.length,
medianFrtHours: frt.length ? round(median(frt), 2) : null,
p90FrtHours: frt.length ? round(quantile(frt, 0.9), 2) : null,
unanswered24: pct(judged24.filter(r => r.unanswered24), judged24),
unanswered48: pct(judged48.filter(r => r.unanswered48), judged48),
neverAnswered: rows.filter(r => r.neverAnswered).length,
awaitingNow: rows.filter(r => r.awaiting).length,
duplicateRate: rows.length ? rows.filter(r => r.duplicate).length / rows.length : null,
outsideHoursShare: rows.length ? outsideHours / rows.length : null,
categories, heat, staff, rows,
};
}
/** Plain-language findings, generated from the audit (never hard-coded). */
function findings(a, labels, exclude) {
const name = k => (labels && labels[k]) || k;
const out = [];
// `exclude` drops internal mail (e.g. vendors) from customer-facing comparisons.
const cats = a.categories.filter(c => c.medianFrtHours !== null && c.threads >= 10 && !(exclude || []).includes(c.category));
if (cats.length >= 2) {
const slow = cats.reduce((x, y) => (y.medianFrtHours > x.medianFrtHours ? y : x));
const fast = cats.reduce((x, y) => (y.medianFrtHours < x.medianFrtHours ? y : x));
// The ratio is computed from the medians exactly as displayed (1 decimal),
// so a reader can check it: 18.7 / 1.2 = 15.6, not the unrounded 15.2.
const slowShown = round(slow.medianFrtHours, 1), fastShown = round(fast.medianFrtHours, 1);
if (fastShown > 0 && slowShown / fastShown >= 1.5) {
const cap = s => s.charAt(0).toUpperCase() + s.slice(1);
out.push({ kind: 'slowest', ratio: round(slowShown / fastShown, 1), text: `${cap(name(slow.category))} wait ${round(slowShown / fastShown, 1)}× longer for a first reply than ${name(fast.category)} (median ${slowShown} vs ${fastShown} business hours).` });
}
const dropped = cats.filter(c => c.unanswered48 !== null).sort((x, y) => y.unanswered48 - x.unanswered48)[0];
if (dropped && dropped.unanswered48 >= 0.1) {
out.push({ kind: 'dropped', text: `${round(dropped.unanswered48 * 100)}% of ${name(dropped.category)} had no reply within 48 hours, the worst of any category.` });
}
const dup = cats.slice().sort((x, y) => y.duplicateRate - x.duplicateRate)[0];
if (dup && dup.duplicateRate >= 0.05) {
out.push({ kind: 'duplicate', text: `${round(dup.duplicateRate * 100)}% of ${name(dup.category)} got replies from two or more staff: nobody could see who already had it.` });
}
}
if (a.staff.length && a.staff[0].share >= 0.4) {
out.push({ kind: 'load', text: `${a.staff[0].staff} sent ${round(a.staff[0].share * 100)}% of all replies. The inbox depends on one person.` });
}
if (a.outsideHoursShare !== null && a.outsideHoursShare >= 0.25) {
out.push({ kind: 'afterhours', text: `${round(a.outsideHoursShare * 100)}% of emails arrive outside staffed hours, so they start the next day already waiting.` });
}
return out;
}
/* ------------------------------------------------ ownership and SLAs */
/**
* Open-queue status at `now`. routing: {category: {owner, slaHours}} in business hours.
* claims: {threadId: owner} overrides the routing default.
*/
function queue(threads, cfg, claims, now) {
now = now || cfg.asOf;
const soonMin = (cfg.dueSoonHours || 1) * 60;
return threads.map(t => analyzeThread(t, Object.assign({}, cfg, { asOf: now })))
.filter(r => r && r.awaiting && r.waitingSince <= now)
.map(r => {
const route = (cfg.routing && cfg.routing[r.category]) || cfg.defaultRoute || { owner: null, slaHours: 8 };
const owner = (claims && claims[r.id]) || null;
const due = addBusinessMinutes(r.waitingSince, route.slaHours * 60, cfg.hours);
const leftMin = due > now ? businessMinutes(now, due, cfg.hours) : -businessMinutes(due, now, cfg.hours);
// Requests older than staleDays are a one-time backlog to clean up, not
// something to nudge about every day.
const stale = cfg.staleDays && now - r.waitingSince > cfg.staleDays * DAY;
const status = stale ? 'stale' : leftMin < 0 ? 'overdue' : leftMin <= soonMin ? 'due-soon' : 'on-track';
const unclaimedHours = owner ? 0 : (now - r.waitingSince) / HOUR;
return {
id: r.id, category: r.category, owner, suggestedOwner: route.owner, slaHours: route.slaHours,
waitingSince: r.waitingSince, due, businessMinutesLeft: round(leftMin), status, unclaimedHours: round(unclaimedHours, 1),
};
})
.sort((a, b) => (a.status === 'stale') - (b.status === 'stale') || a.due - b.due);
}
/**
* Nudge plan: who gets an email right now. Owners get one digest of their
* overdue threads; unclaimed threads older than cfg.escalateUnclaimedHours go
* to the whole team. Batched per person to respect daily send limits.
*/
function nudges(q, cfg) {
const byPerson = {};
const add = (who, item, why) => { (byPerson[who] = byPerson[who] || []).push({ id: item.id, why }); };
q.forEach(item => {
if (item.status === 'stale') return;
if (item.owner && item.status === 'overdue') add(item.owner, item, 'overdue');
if (!item.owner && item.unclaimedHours >= (cfg.escalateUnclaimedHours || 24)) cfg.team.forEach(p => add(p, item, 'unclaimed'));
});
return Object.keys(byPerson).map(p => ({ to: p, items: byPerson[p] }));
}
/** Weekly scorecard rows for the last n weeks (Monday-start weeks). */
function weekly(threads, cfg, weeks) {
const rows = [];
const d = new Date(cfg.asOf);
const monday = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - ((d.getUTCDay() + 6) % 7) * DAY;
for (let w = (weeks || 6) - 1; w >= 0; w--) {
const start = monday - w * 7 * DAY, end = Math.min(start + 7 * DAY, cfg.asOf);
const a = audit(threads, Object.assign({}, cfg, { asOf: end, lookbackDays: (end - start) / DAY }));
rows.push({ weekOf: start, threads: a.threads, medianFrtHours: a.medianFrtHours, unanswered48: a.unanswered48, duplicateRate: a.duplicateRate });
}
return rows;
}
/* ----------------------------------------------------------- triage */
/**
* Rules-first triage. rules: {category: [[regexSource, weight], ...]}.
* Confidence = top score / (top + runner-up). Below `threshold` goes to a
* human instead of being auto-routed.
*/
function compileRules(rules) {
const out = {};
Object.keys(rules).forEach(k => { out[k] = rules[k].map(([src, w]) => [new RegExp(src, 'i'), w, src]); });
return out;
}
function classify(text, compiled, threshold) {
const scores = [];
Object.keys(compiled).forEach(k => {
let s = 0; const hits = [];
compiled[k].forEach(([re, w, src]) => { if (re.test(text)) { s += w; hits.push(src); } });
scores.push({ category: k, score: s, hits });
});
scores.sort((a, b) => b.score - a.score);
const top = scores[0], second = scores[1];
if (!top || top.score <= 0) return { category: null, confidence: 0, needsHuman: true, scores };
const confidence = top.score / (top.score + Math.max(0, second ? second.score : 0));
return { category: top.category, confidence: round(confidence, 3), needsHuman: confidence < (threshold || 0.6), hits: top.hits, scores };
}
/** Accuracy report against hand labels. items: [{text, label}] */
function evaluate(items, compiled, threshold, categories) {
const cats = categories || Object.keys(compiled);
const matrix = {};
cats.forEach(a => { matrix[a] = {}; cats.concat(['(human)']).forEach(b => { matrix[a][b] = 0; }); });
let correct = 0, auto = 0, autoCorrect = 0;
const errors = [];
items.forEach(it => {
const r = classify(it.text, compiled, threshold);
const predicted = r.needsHuman ? '(human)' : r.category;
matrix[it.label][predicted] = (matrix[it.label][predicted] || 0) + 1;
if (!r.needsHuman) {
auto++;
if (r.category === it.label) autoCorrect++; else errors.push({ text: it.text, label: it.label, predicted: r.category, confidence: r.confidence });
}
if (r.category === it.label) correct++;
});
const perClass = cats.map(c => {
const tp = matrix[c][c];
const predictedC = cats.reduce((s, a) => s + (matrix[a][c] || 0), 0);
const actualC = cats.concat(['(human)']).reduce((s, b) => s + (matrix[c][b] || 0), 0);
return { category: c, support: actualC, precision: predictedC ? round(tp / predictedC, 3) : null, recall: actualC ? round(tp / actualC, 3) : null };
});
return {
n: items.length,
topLabelAccuracy: round(correct / items.length, 3), // if every email were auto-routed
autoRouted: auto, autoRate: round(auto / items.length, 3),
autoPrecision: auto ? round(autoCorrect / auto, 3) : null, // accuracy of what actually gets auto-routed
humanQueue: items.length - auto,
perClass, matrix, errors,
};
}
const api = { HOUR, MIN, DAY, median, quantile, businessMinutes, addBusinessMinutes, analyzeThread, audit, findings, queue, nudges, weekly, compileRules, classify, evaluate };
if (typeof module !== 'undefined' && module.exports) module.exports = api;
else root.InboxCore = api;
})(typeof globalThis !== 'undefined' ? globalThis : this);
The sorting rules (current version, with the history of the earlier versions in the header comment).
/**
* Keyword rules for routing shared-inbox email (v2). [regex, weight] per category.
*
* History (see test/triage-eval.js for the measurements):
* v1 was written from the DEV phrasings only. It scored well on dev and badly
* on the held-out TEST phrasings: it had memorised wording.
* v2 (this file) was rewritten from dev + test around INTENT (stop paying,
* come back later, try before buying) instead of exact phrases, and
* generic words that appear in every category ("session", "class",
* "membership") were removed. Because test was used to write v2, v2 is
* meant to be measured on data/holdout.js, but words from that set leaked into these
* rules while they were being written, so it is not a clean test either. The clean
* measurement is data/blind.json (independent author). See test/triage-eval.js.
* v2.1 fixes one bug found on the blind set (data/blind.json, written by an
* independent author): "lease" matched inside "please". v2 is kept in
* triage-rules.v2.js because its blind score is the clean measurement.
* Weights: 3 = strong signal, 2 = medium, 1 = weak.
*/
(function (root) {
const TRIAGE_RULES = {
trial: [
['free (trial|week|session|class)|trial (week|session|class|pass)', 3],
['intro (offer|deal|special)|new.?member|newcomer|first.?timer|first (class|visit|time|week)', 3],
['guest pass|day pass|drop.?in|bring a friend', 3],
['\\b(try|sample|test) (it|a|out|before|some|the place|a couple)|try a few|give it a shot', 3],
['before (committing|buying|i (sign|join|decide))|thinking about joining|interested in (becoming|joining)', 3],
['\\btour\\b|stop by|check (the place|it) out|good fit', 2],
['\\bbeginner|never (done|been)|starting out|intimidated', 2],
['\\bpromo|special for|complimentary', 2],
],
schedule: [
['\\bschedule\\b(?! changed)|timetable|calendar|class times?', 3],
['wait.?list|spots? (left|in)|openings tonight|sold out|\\bfull\\b', 3],
['\\b(re|un)?book(ing|ed)?\\b|reserve|sign (up|in) for|hold my spot|switch my', 3],
['\\b(when|what time) (is|does)|start(s)? on|rescheduled|has it moved|still (on|happening)', 2],
['\\b\\d{1,2}(:\\d{2})?\\s?(am|pm)\\b|\\bthe \\d{1,2}(:\\d{2})?\\b', 2],
['instructor|who is teaching|which room|running late|be \\d+ min late', 3],
['holiday|winter break|open on|on sundays|weekday', 2],
['\\bapp\\b', 1],
],
billing: [
['charged|charge from|billed for|double (charge|payment)|paid .* (two|2) times', 3],
['refund|money back', 3],
['receipt|proof of payment|payment history|statement|tax (id|docs)|year.end summary', 3],
['\\bcard\\b|declined|bank (transfer|flagged)', 2],
['payment|autopay|\\bbill(ed|ing)?\\b|balance due|\\bowe\\b|overdue notice', 2],
['cost more|went up|price change|\\$\\d+', 1],
['discount|corporate rate|student discount|paying full price', 2],
['reimburse|\\bhsa\\b|insurance', 2],
],
cancel: [
['\\bcancel(l?ation)?\\b(?! (my |the |tonight|tomorrow)?(class|spin|yoga|session))', 3],
['(end|close|terminate|discontinue|stop) (my|the|things)? ?(membership|account|plan|it)|termination', 3],
['\\bquit\\b|leave the gym|move on|opt out|not (renew|continue|continuing)|won.?t be continuing|no longer need', 3],
['stop (all )?(future )?(charges|paying)|don.?t charge me|not be charged again|for good', 2],
['moving out of|relocating|withdraw from', 2],
['not (for me|coming back|working out)|done with', 2],
],
freeze: [
['freeze|unfreeze|\\bpause|put .* on (hold|ice)|on hold|medical hold|military hold', 4],
['suspend(ed)?|\\bbreak from|vacation hold', 3],
['resume|reactivate|restart|back in town', 3],
['while (i.?m |i am |my .* )?(away|traveling|heals?|recover)|out of town|overseas|abroad|deployed|until (i.?m|march|i am)', 2],
['not (quitting|cancell?ing)|rather than cancell?ing|don.?t want to cancel', 3],
['surgery|injury|hospital|expecting', 1],
],
training: [
['personal (training|sessions)|private(ly)? (sessions?|train)|train me', 3],
['\\btrainers?\\b|\\bcoach(es|ing)?\\b(?! intern)', 2],
['1:1|one.?on.?ones?|partner sessions|semi.?private', 3],
['(write|build|custom) (me )?(a )?(program|plan)|program design|plateau', 3],
['form check|squat form|olympic lifts|deadlift|powerlifting|marathon|strength work', 2],
['assessment|nutrition|postpartum|youth|weight loss', 1],
],
vendor: [
['partner(ship)? (on|with|opportunity)|referral partnership|co.?brand|collaborat', 3],
['sponsor|fundraiser|donation|nonprofit|raffle', 3],
['\\bquote\\b|estimate|invoice #?\\d+|net 30|\\blease\\b|wholesale', 3], // v2.1: \\b added; "lease" matched inside "please"
['we (provide|help|sell|offer|are a)|our (brand|company|clinic|5k)|i (represent|offer|run|create|teach)', 2],
['technician|maintenance|repair|hvac|flooring|cleaning (supply|services)|supply order|delivery window', 2],
['\\bdemo\\b|more leads|free audit|photo shoots|guest speakers?|wellness week|group rates', 2],
['rent your space|stock our|flyers', 2],
],
general: [
['left my|lost|did anyone find|took my|cameras?', 3],
['parking|\\bbus\\b|bike', 3],
['locker|cubby|towels?|showers?|sauna|water (refill|bottle)|wifi', 2],
['gift card|merch|hoodies?', 2],
['childcare|\\bkids\\b|\\bdog\\b|wheelchair|accessib', 3],
['hiring|part time work|join(ing)? the staff|intern\\b', 3],
['too loud|music|door code|smoke|filming|policy on', 2],
['thank you to the staff|everyone was so kind|feedback', 2],
],
};
if (typeof module !== 'undefined' && module.exports) module.exports = TRIAGE_RULES;
else root.TRIAGE_RULES = TRIAGE_RULES;
})(typeof globalThis !== 'undefined' ? globalThis : this);
The real-inbox version: Gmail to metadata to a Sheet, owner labels, hourly reminders, weekly scorecard. Never stores message bodies.
/**
* InboxOwner pilot: runs inside the inbox owner's own Google account.
*
* Files in this Apps Script project:
* Core.gs — core/inbox-core.js (unchanged)
* Rules.gs — core/triage-rules.js (unchanged)
* Pilot.gs — this file: Gmail → metadata → Sheets, ownership labels, nudges
*
* Privacy by design: message bodies are read in memory only to pick a
* category and are never written anywhere. The Sheet stores thread IDs,
* timestamps, who replied, and the category. Subjects are stored only if the
* owner switches STORE_SUBJECTS on in Settings.
*/
const NOUNS = { trial: 'trial inquiries', schedule: 'schedule questions', billing: 'billing emails', cancel: 'cancellation requests',
freeze: 'freeze requests', training: 'training inquiries', vendor: 'vendor emails', general: 'general questions', 'needs-review': 'unsorted emails' };
const PILOT = {
SETTINGS: 'Settings', AUDIT: 'Audit', QUEUE: 'Queue', WEEKLY: 'Weekly',
LABEL_PREFIX: 'owner/',
};
function onOpen() {
SpreadsheetApp.getUi().createMenu('InboxOwner')
.addItem('1. Create settings tab', 'setupPilot')
.addItem('2. Run inbox health check', 'runAudit')
.addItem('3. Refresh ownership queue', 'refreshQueue')
.addSeparator()
.addItem('Start hourly nudges + weekly scorecard', 'installPilotTriggers')
.addItem('Stop all automation', 'removePilotTriggers')
.addToUi();
}
/* ------------------------------------------------------------ settings */
function setupPilot() {
const ss = SpreadsheetApp.getActive();
let sh = ss.getSheetByName(PILOT.SETTINGS);
if (sh) { SpreadsheetApp.getUi().alert('Settings tab already exists.'); return; }
sh = ss.insertSheet(PILOT.SETTINGS);
const me = Session.getEffectiveUser().getEmail();
sh.getRange(1, 1, 9, 2).setValues([
['Shared inbox address', me],
['Time zone', Session.getScriptTimeZone()],
['Lookback days', 90],
['Business hours (Sun..Sat, "9-18" or blank)', ',9-18,9-18,9-18,9-18,9-18,9-13'],
['Store subjects? (TRUE/FALSE)', false],
['Escalate unclaimed after (hours)', 24],
['Stale after (days)', 14],
['Triage confidence threshold', 0.6],
['', ''],
]);
sh.getRange(10, 1, 1, 2).setValues([['Team member', 'Email']]);
sh.getRange(11, 1, 1, 2).setValues([['Owner', me]]);
sh.getRange(10, 4, 1, 3).setValues([['Category', 'Default owner', 'SLA (business hours)']]);
const cats = ['trial', 'schedule', 'billing', 'cancel', 'freeze', 'training', 'vendor', 'general'];
sh.getRange(11, 4, cats.length, 3).setValues(cats.map(c => [c, 'Owner', c === 'trial' ? 2 : c === 'vendor' ? 24 : 8]));
sh.getRange('A1:A10').setFontWeight('bold');
sh.getRange('D10:F10').setFontWeight('bold');
sh.setColumnWidth(1, 300); sh.setColumnWidth(2, 260); sh.setColumnWidth(4, 120); sh.setColumnWidth(5, 120);
SpreadsheetApp.getUi().alert('Fill in the team list (column A/B, from row 11) and the routing table, then run the health check.');
}
function readPilotSettings() {
const sh = SpreadsheetApp.getActive().getSheetByName(PILOT.SETTINGS);
if (!sh) throw new Error('Run "Create settings tab" first.');
const v = sh.getRange(1, 2, 8, 1).getValues().map(r => r[0]);
const hours = {};
String(v[3]).split(',').forEach((x, i) => {
const m = /^(\d{1,2})-(\d{1,2})$/.exec(String(x).trim());
hours[i] = m ? [Number(m[1]), Number(m[2])] : null;
});
const last = sh.getLastRow();
const team = sh.getRange(11, 1, Math.max(1, last - 10), 2).getValues().filter(r => r[0] && r[1])
.map(r => ({ name: String(r[0]).trim(), email: String(r[1]).trim().toLowerCase() }));
const routing = {};
sh.getRange(11, 4, Math.max(1, last - 10), 3).getValues().filter(r => r[0])
.forEach(r => { routing[String(r[0]).trim()] = { owner: String(r[1]).trim() || null, slaHours: Number(r[2]) || 8 }; });
const tz = String(v[1] || Session.getScriptTimeZone());
return {
shared: String(v[0]).trim().toLowerCase(), tz, lookbackDays: Number(v[2]) || 90, hours,
storeSubjects: v[4] === true || String(v[4]).toUpperCase() === 'TRUE',
escalateUnclaimedHours: Number(v[5]) || 24, staleDays: Number(v[6]) || 14, triageThreshold: Number(v[7]) || 0.6,
team, teamNames: team.map(t => t.name), routing, defaultRoute: { owner: null, slaHours: 8 }, dueSoonHours: 1,
asOf: toWallClock(new Date(), tz),
};
}
/* ---------------------------------------------- Gmail → core threads */
// Converts a real Date to studio wall-clock ms (the core's time convention).
function toWallClock(date, tz) {
const s = Utilities.formatDate(date, tz, "yyyy-MM-dd'T'HH:mm:ss");
return Date.UTC(+s.slice(0, 4), +s.slice(5, 7) - 1, +s.slice(8, 10), +s.slice(11, 13), +s.slice(14, 16), +s.slice(17, 19));
}
function addressOf(from) {
const m = /<([^>]+)>/.exec(from);
return (m ? m[1] : from).trim().toLowerCase();
}
/**
* Turns one GmailThread into {id, category, subject?, messages:[{from, staff, at}]}.
* Staff = any team member's address or the shared address itself.
*/
function convertThread(thread, st, rules) {
const byEmail = {};
st.team.forEach(t => { byEmail[t.email] = t.name; });
const messages = thread.getMessages().map(m => {
const addr = addressOf(m.getFrom());
const isStaff = addr === st.shared || Object.prototype.hasOwnProperty.call(byEmail, addr);
return { from: isStaff ? 'staff' : 'customer', staff: isStaff ? (byEmail[addr] || 'Shared inbox') : null, at: toWallClock(m.getDate(), st.tz) };
});
const firstIn = thread.getMessages().find(m => {
const a = addressOf(m.getFrom());
return a !== st.shared && !Object.prototype.hasOwnProperty.call(byEmail, a);
});
let category = null;
if (firstIn && rules) {
// Body is used in memory only; it is never written to the Sheet.
const text = thread.getFirstMessageSubject() + '\n' + String(firstIn.getPlainBody()).slice(0, 600);
const r = InboxCore.classify(text, rules, st.triageThreshold);
category = r.needsHuman ? 'needs-review' : r.category;
}
const out = { id: thread.getId(), category, messages: messages.sort((a, b) => a.at - b.at) };
if (st.storeSubjects) out.subject = thread.getFirstMessageSubject();
return out;
}
function fetchThreads(st) {
const rules = InboxCore.compileRules(TRIAGE_RULES);
const query = `to:${st.shared} newer_than:${st.lookbackDays}d -in:spam -in:trash`;
const threads = [];
for (let start = 0; start < 1500; start += 100) {
const page = GmailApp.search(query, start, 100);
page.forEach(t => threads.push(convertThread(t, st, rules)));
if (page.length < 100) break;
}
return threads;
}
/* -------------------------------------------------------------- audit */
function runAudit() {
const st = readPilotSettings();
const threads = fetchThreads(st);
const a = InboxCore.audit(threads, st);
const sh = resetSheet(PILOT.AUDIT);
const fmtH = x => (x === null ? '—' : Math.round(x * 10) / 10 + ' h');
const fmtP = x => (x === null ? '—' : Math.round(x * 100) + '%');
const summary = [
['Inbox health check', ''],
['Window', `${a.window.days} days to ${Utilities.formatDate(new Date(), st.tz, 'yyyy-MM-dd HH:mm')}`],
['Customer threads', a.threads],
['Median first reply (business hours)', fmtH(a.medianFrtHours)],
['90th percentile first reply', fmtH(a.p90FrtHours)],
['No reply within 24h', fmtP(a.unanswered24)],
['No reply within 48h', fmtP(a.unanswered48)],
['Never answered', a.neverAnswered],
['Duplicate replies', fmtP(a.duplicateRate)],
['Arrived outside staffed hours', fmtP(a.outsideHoursShare)],
];
sh.getRange(1, 1, summary.length, 2).setValues(summary);
sh.getRange('A1').setFontWeight('bold').setFontSize(14);
const finds = InboxCore.findings(a, NOUNS, ['vendor', 'needs-review']).map(f => [f.text]);
sh.getRange(12, 1).setValue('Findings').setFontWeight('bold');
if (finds.length) sh.getRange(13, 1, finds.length, 1).setValues(finds);
const r0 = 15 + finds.length;
const head = ['Category', 'Threads', 'Median first reply (h)', 'p90 (h)', 'No reply 48h', 'Duplicate rate'];
sh.getRange(r0, 1, 1, head.length).setValues([head]).setFontWeight('bold');
if (a.categories.length) sh.getRange(r0 + 1, 1, a.categories.length, head.length)
.setValues(a.categories.map(c => [c.category, c.threads, c.medianFrtHours, c.p90FrtHours, c.unanswered48, c.duplicateRate]));
// Per-thread metadata (no bodies; subjects only if enabled).
const r1 = r0 + a.categories.length + 3;
const cols = ['Thread ID', 'Category', 'First message (local)', 'First reply by', 'First reply (business h)', 'No reply 48h', 'Duplicate', 'Awaiting reply'];
sh.getRange(r1, 1, 1, cols.length).setValues([cols]).setFontWeight('bold');
const iso = ms => new Date(ms).toISOString().slice(0, 16).replace('T', ' ');
const rows = a.rows.map(r => [r.id, r.category || '', iso(r.firstIn), r.firstReplyBy || '', r.frtMinutes === null ? '' : Math.round(r.frtMinutes / 6) / 10, r.unanswered48, r.duplicate, r.awaiting]);
if (rows.length) sh.getRange(r1 + 1, 1, rows.length, cols.length).setValues(rows);
sh.setColumnWidth(1, 320);
return a;
}
/* ------------------------------------------------ ownership and nudges */
// Claims come from Gmail labels named owner/<Name>.
function readClaims(st) {
const claims = {};
st.teamNames.forEach(name => {
const label = GmailApp.getUserLabelByName(PILOT.LABEL_PREFIX + name);
if (label) label.getThreads(0, 200).forEach(t => { claims[t.getId()] = name; });
});
return claims;
}
function ensureOwnerLabels(st) {
st.teamNames.forEach(name => {
if (!GmailApp.getUserLabelByName(PILOT.LABEL_PREFIX + name)) GmailApp.createLabel(PILOT.LABEL_PREFIX + name);
});
}
function refreshQueue() {
const st = readPilotSettings();
ensureOwnerLabels(st);
const q = InboxCore.queue(fetchThreads(st), st, readClaims(st));
const sh = resetSheet(PILOT.QUEUE);
const head = ['Thread ID', 'Category', 'Owner', 'Suggested owner', 'Waiting since', 'Due', 'Status', 'Business min left'];
sh.getRange(1, 1, 1, head.length).setValues([head]).setFontWeight('bold');
const iso = ms => new Date(ms).toISOString().slice(0, 16).replace('T', ' ');
if (q.length) sh.getRange(2, 1, q.length, head.length).setValues(q.map(x => [x.id, x.category || '', x.owner || 'UNCLAIMED', x.suggestedOwner || '', iso(x.waitingSince), iso(x.due), x.status, x.businessMinutesLeft]));
return q;
}
/** Hourly during business hours: one batched email per person, never per thread. */
function hourlyNudge() {
const st = readPilotSettings();
const now = new Date(st.asOf), h = st.hours[now.getUTCDay()];
if (!h || now.getUTCHours() < h[0] || now.getUTCHours() >= h[1]) return; // closed
const q = refreshQueue();
const plan = InboxCore.nudges(q, Object.assign({}, st, { team: st.teamNames }));
const emailOf = {};
st.team.forEach(t => { emailOf[t.name] = t.email; });
plan.forEach(p => {
if (!emailOf[p.to]) return;
const lines = p.items.map(i => `• ${i.why === 'overdue' ? 'Overdue' : 'Unclaimed 24h+'}: https://mail.google.com/mail/u/0/#all/${i.id}`);
MailApp.sendEmail(emailOf[p.to], `[InboxOwner] ${p.items.length} email(s) need you`, lines.join('\n') +
'\n\nClaim a thread by adding the label owner/<your name>. Reply and the item clears on the next refresh.');
});
}
/** Weekly scorecard row (Mondays). */
function weeklyScorecard() {
const st = readPilotSettings();
const rows = InboxCore.weekly(fetchThreads(st), st, 1);
const sh = SpreadsheetApp.getActive().getSheetByName(PILOT.WEEKLY) || SpreadsheetApp.getActive().insertSheet(PILOT.WEEKLY);
if (sh.getLastRow() === 0) sh.appendRow(['Week of', 'Threads', 'Median first reply (h)', 'No reply 48h', 'Duplicate rate']);
rows.forEach(r => sh.appendRow([new Date(r.weekOf).toISOString().slice(0, 10), r.threads, r.medianFrtHours, r.unanswered48, r.duplicateRate]));
}
function installPilotTriggers() {
removePilotTriggers();
ScriptApp.newTrigger('hourlyNudge').timeBased().everyHours(1).create();
ScriptApp.newTrigger('weeklyScorecard').timeBased().onWeekDay(ScriptApp.WeekDay.MONDAY).atHour(8).create();
}
function removePilotTriggers() {
ScriptApp.getProjectTriggers()
.filter(t => ['hourlyNudge', 'weeklyScorecard'].indexOf(t.getHandlerFunction()) !== -1)
.forEach(t => ScriptApp.deleteTrigger(t));
}
function resetSheet(name) {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName(name) || ss.insertSheet(name);
sh.clear();
return sh;
}
Builds the sample inbox from a seed, including the behaviour the health check has to find.
/**
* Generates 90+ days of synthetic shared-inbox email for "Cedar & Iron
* Fitness" (fictional), deterministically from a seed.
*
* Behaviour baked into the model (what a real audit would have to discover):
* - many emails arrive before/after staffed hours (members email around workouts)
* - uncomfortable requests (cancellations, freezes, vendors) wait longest and
* are most often never answered
* - easy requests (trials, schedule) sometimes get two replies because nobody
* can see who already answered
* - one person (the owner) carries most money-related email
* Usage: node data/generate.js → writes web/data/inbox.json
*/
const fs = require('fs');
const path = require('path');
const C = require('../core/inbox-core.js');
const { CATEGORIES, PHRASINGS, FOLLOW_UPS, STAFF_REPLIES } = require('./phrasings.js');
const AS_OF = Date.UTC(2026, 9, 22, 16, 0); // Thu Oct 22, 2026, 4:00pm studio time
const DAYS = 95;
const HOURS = { 0: null, 1: [9, 18], 2: [9, 18], 3: [9, 18], 4: [9, 18], 5: [9, 18], 6: [9, 13] };
const STAFF = ['Maya', 'Jordan', 'Priya', 'Sam'];
function mulberry32(a) {
return function () {
a |= 0; a = (a + 0x6D2B79F5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function generate(seed) {
const rnd = mulberry32(seed || 20261022);
const pick = a => a[Math.floor(rnd() * a.length)];
const weighted = obj => {
const keys = Object.keys(obj), total = keys.reduce((s, k) => s + obj[k], 0);
let x = rnd() * total;
for (const k of keys) { x -= obj[k]; if (x <= 0) return k; }
return keys[keys.length - 1];
};
const normal = () => Math.sqrt(-2 * Math.log(1 - rnd())) * Math.cos(2 * Math.PI * rnd());
const lognormal = (medianMin, sigma) => Math.max(3, medianMin * Math.exp(sigma * normal()));
const MIX = { trial: 22, schedule: 18, billing: 14, cancel: 10, freeze: 9, training: 10, vendor: 7, general: 10 };
// Arrival hour weights: peaks before work and after evening workouts.
const HOUR_W = [0.1, 0.05, 0.05, 0.05, 0.1, 0.3, 0.8, 1.2, 1.6, 1.8, 1.7, 1.6, 1.8, 1.7, 1.5, 1.4, 1.4, 1.3, 1.2, 1.2, 1.3, 1.1, 0.6, 0.3];
// Who answers what (before any ownership rules exist).
const RESPONDER = {
trial: { Jordan: 5, Priya: 3, Maya: 2 }, schedule: { Jordan: 5, Priya: 4, Maya: 1 },
billing: { Maya: 8, Jordan: 2 }, cancel: { Maya: 9, Jordan: 1 }, freeze: { Maya: 7, Jordan: 3 },
training: { Sam: 6, Maya: 3, Jordan: 1 }, vendor: { Maya: 10 }, general: { Jordan: 4, Priya: 4, Maya: 2 },
};
// Median first-reply delay in BUSINESS minutes, and chance of never replying.
const DELAY = { trial: 70, schedule: 110, billing: 280, cancel: 900, freeze: 520, training: 300, vendor: 1300, general: 380 };
const NEVER = { trial: 0.02, schedule: 0.04, billing: 0.03, cancel: 0.16, freeze: 0.1, training: 0.04, vendor: 0.22, general: 0.1 };
const DUP = { trial: 0.15, schedule: 0.09, general: 0.05 };
const GREET = ['', '', 'Hi, ', 'Hello, ', 'Hey there, ', 'Good morning, '];
const SIGN = ['', '', ' Thanks!', ' Thank you.', ' Thx', ' Appreciate it.'];
const NOISE = ['', '', '', '', " I've been a member for two years.", ' Love the classes by the way.', ' Sorry if this is the wrong email.', ' I emailed last week too.'];
const FIRST = ['Alex', 'Sam', 'Jamie', 'Taylor', 'Morgan', 'Riley', 'Casey', 'Avery', 'Quinn', 'Rowan', 'Dakota', 'Reese', 'Emerson', 'Skyler', 'Kai', 'Noor', 'Lena', 'Mateo', 'Hana', 'Theo'];
const LAST = ['Nguyen', 'Garcia', 'Okafor', 'Larsen', 'Haddad', 'Ito', 'Moreno', 'Kowalski', 'Silva', 'Fischer', 'Achebe', 'Lindqvist', 'Patel', 'Duval', 'Tanaka', 'Romero'];
const threads = [];
let n = 0;
for (let day = DAYS; day >= 0; day--) {
const dayStart = Date.UTC(2026, 9, 22) - day * C.DAY;
const dow = new Date(dayStart).getUTCDay();
const mean = dow === 0 ? 4 : dow === 6 ? 5 : dow === 1 ? 7.5 : 6;
// Poisson draw
let k = 0, p = Math.exp(-mean), s = p; const u = rnd();
while (u > s) { k++; p *= mean / k; s += p; }
for (let i = 0; i < k; i++) {
const hour = Number(weighted(Object.fromEntries(HOUR_W.map((w, h) => [h, w]))));
const at = dayStart + hour * C.HOUR + Math.floor(rnd() * 60) * C.MIN;
if (at > AS_OF) continue;
const category = weighted(MIX);
const split = rnd() < 0.5 ? 'dev' : 'test';
const [subject, body] = pick(PHRASINGS[category][split]);
const first = pick(FIRST), last = pick(LAST);
let text = pick(GREET) + body + pick(NOISE) + pick(SIGN);
if (rnd() < 0.12) text = text.toLowerCase();
const thread = {
id: 'T' + String(++n).padStart(4, '0'), category, split, subject,
customer: { name: first + ' ' + last, email: `${first}.${last}@mail.example`.toLowerCase() },
messages: [{ from: 'customer', at, text }],
};
// First reply
const responder = weighted(RESPONDER[category]);
let replyAt = rnd() < NEVER[category] ? null : C.addBusinessMinutes(at, lognormal(DELAY[category], 0.9), HOURS);
replyAt = replyAt === null ? null : Math.round(replyAt / C.MIN) * C.MIN;
// Customer chases if nothing came back within a day
if ((replyAt === null || replyAt - at > 24 * C.HOUR) && rnd() < 0.45) {
const fu = at + (26 + Math.floor(rnd() * 14)) * C.HOUR;
if (fu <= AS_OF && (replyAt === null || fu < replyAt)) thread.messages.push({ from: 'customer', at: fu, text: pick(FOLLOW_UPS) });
}
if (replyAt !== null && replyAt <= AS_OF) {
thread.messages.push({ from: 'staff', staff: responder, at: replyAt, text: STAFF_REPLIES[category] });
// Second person answers too, unaware someone already did
if (DUP[category] && rnd() < DUP[category]) {
const other = pick(STAFF.filter(x => x !== responder && x !== 'Sam'));
const dupAt = replyAt + (5 + Math.floor(rnd() * 40)) * C.MIN;
if (dupAt <= AS_OF) thread.messages.push({ from: 'staff', staff: other, at: dupAt, text: STAFF_REPLIES[category] });
}
// Conversation continues
if (rnd() < 0.3) {
const back = replyAt + (1 + Math.floor(rnd() * 30)) * C.HOUR;
if (back <= AS_OF) {
thread.messages.push({ from: 'customer', at: back, text: 'Thanks. One more question about this.' });
if (rnd() < 0.85) {
const again = Math.round(C.addBusinessMinutes(back, lognormal(DELAY[category] / 2, 0.8), HOURS) / C.MIN) * C.MIN;
if (again <= AS_OF) thread.messages.push({ from: 'staff', staff: responder, at: again, text: 'Answered below.' });
}
}
}
}
thread.messages.sort((a, b) => a.at - b.at);
threads.push(thread);
}
}
return threads;
}
const CONFIG = {
business: 'Cedar & Iron Fitness',
inbox: 'info@cedariron.example',
asOf: AS_OF,
lookbackDays: 90,
hours: HOURS,
team: STAFF,
categories: CATEGORIES,
// Plural nouns for generated sentences ("67% of cancellation requests …").
nouns: { trial: 'trial inquiries', schedule: 'schedule questions', billing: 'billing emails', cancel: 'cancellation requests',
freeze: 'freeze requests', training: 'training inquiries', vendor: 'vendor emails', general: 'general questions' },
// Proposed routing after the audit: default owner + first-reply SLA in business hours.
routing: {
trial: { owner: 'Jordan', slaHours: 2 },
schedule: { owner: 'Priya', slaHours: 4 },
billing: { owner: 'Maya', slaHours: 8 },
cancel: { owner: 'Maya', slaHours: 8 },
freeze: { owner: 'Jordan', slaHours: 8 },
training: { owner: 'Sam', slaHours: 8 },
vendor: { owner: 'Maya', slaHours: 24 },
general: { owner: 'Priya', slaHours: 8 },
},
defaultRoute: { owner: null, slaHours: 8 },
dueSoonHours: 1,
escalateUnclaimedHours: 24,
staleDays: 14,
internalCategories: ['vendor'],
triageThreshold: 0.6,
};
if (require.main === module) {
const threads = generate();
const out = path.join(__dirname, '..', 'web', 'data');
fs.mkdirSync(out, { recursive: true });
fs.writeFileSync(path.join(out, 'inbox.json'), JSON.stringify({ config: CONFIG, threads }));
console.log(`wrote ${threads.length} threads (${threads.reduce((s, t) => s + t.messages.length, 0)} messages)`);
}
module.exports = { generate, CONFIG };
Unit tests with hand-worked answers.
// Unit tests for core/inbox-core.js. Expected values are worked out by hand
// in the comments, not copied from the code's output.
const assert = require('node:assert/strict');
const C = require('../core/inbox-core.js');
const T = (y, mo, d, h, mi) => Date.UTC(y, mo - 1, d, h || 0, mi || 0); // wall clock
// Studio hours: Mon–Fri 9–18, Sat 9–13, Sun closed. 2026-10-19 is a Monday.
const HOURS = { 0: null, 1: [9, 18], 2: [9, 18], 3: [9, 18], 4: [9, 18], 5: [9, 18], 6: [9, 13] };
let passed = 0;
const test = (name, fn) => { fn(); passed++; console.log(' ✓ ' + name); };
console.log('business hours');
test('same day inside hours', () => assert.equal(C.businessMinutes(T(2026, 10, 19, 10), T(2026, 10, 19, 11, 30), HOURS), 90));
test('overnight: Mon 17:00 → Tue 10:00 = 60 + 60', () => assert.equal(C.businessMinutes(T(2026, 10, 19, 17), T(2026, 10, 20, 10), HOURS), 120));
test('weekend: Fri 17:00 → Mon 10:00 = 60 (Fri) + 240 (Sat) + 0 (Sun) + 60 (Mon)', () =>
assert.equal(C.businessMinutes(T(2026, 10, 23, 17), T(2026, 10, 26, 10), HOURS), 360));
test('after-hours arrival: Sat 20:00 → Mon 9:30 = 30', () => assert.equal(C.businessMinutes(T(2026, 10, 24, 20), T(2026, 10, 26, 9, 30), HOURS), 30));
test('end before start = 0', () => assert.equal(C.businessMinutes(T(2026, 10, 20, 10), T(2026, 10, 19, 10), HOURS), 0));
test('add 120 business min to Fri 17:00 → Sat 10:00', () => assert.equal(C.addBusinessMinutes(T(2026, 10, 23, 17), 120, HOURS), T(2026, 10, 24, 10)));
test('add 4h to Sat 12:00 → Mon 12:00 (1h Sat, Sun closed, 3h Mon)', () => assert.equal(C.addBusinessMinutes(T(2026, 10, 24, 12), 240, HOURS), T(2026, 10, 26, 12)));
test('add from before opening starts at opening: Tue 07:00 + 30 → 09:30', () => assert.equal(C.addBusinessMinutes(T(2026, 10, 20, 7), 30, HOURS), T(2026, 10, 20, 9, 30)));
test('add/measure are inverses over 500 random starts', () => {
let seed = 7; const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
for (let i = 0; i < 500; i++) {
const start = T(2026, 10, 1) + Math.floor(rnd() * 20 * 24 * 60) * C.MIN;
const mins = Math.floor(rnd() * 3000) + 1;
const end = C.addBusinessMinutes(start, mins, HOURS);
assert.equal(C.businessMinutes(start, end, HOURS), mins);
}
});
console.log('thread analysis');
const cfg = { asOf: T(2026, 10, 22, 16), hours: HOURS, lookbackDays: 90 };
test('first response in business hours, and who replied', () => {
const r = C.analyzeThread({ id: 'a', messages: [{ from: 'customer', at: T(2026, 10, 19, 17) }, { from: 'staff', staff: 'Jordan', at: T(2026, 10, 20, 10) }] }, cfg);
assert.equal(r.frtMinutes, 120); assert.equal(r.frtClockHours, 17); assert.equal(r.firstReplyBy, 'Jordan');
assert.equal(r.unanswered24, false); assert.equal(r.duplicate, false); assert.equal(r.awaiting, false);
});
test('two staff answering the same message = duplicate', () => {
const r = C.analyzeThread({ id: 'b', messages: [{ from: 'customer', at: T(2026, 10, 19, 10) }, { from: 'staff', staff: 'Jordan', at: T(2026, 10, 19, 10, 20) }, { from: 'staff', staff: 'Priya', at: T(2026, 10, 19, 10, 25) }] }, cfg);
assert.equal(r.duplicate, true);
});
test('same staffer replying twice is NOT a duplicate', () => {
const r = C.analyzeThread({ id: 'c', messages: [{ from: 'customer', at: T(2026, 10, 19, 10) }, { from: 'staff', staff: 'Jordan', at: T(2026, 10, 19, 11) }, { from: 'staff', staff: 'Jordan', at: T(2026, 10, 19, 12) }] }, cfg);
assert.equal(r.duplicate, false);
});
test('different staff on different customer messages is NOT a duplicate', () => {
const r = C.analyzeThread({ id: 'd', messages: [{ from: 'customer', at: T(2026, 10, 19, 10) }, { from: 'staff', staff: 'Jordan', at: T(2026, 10, 19, 11) }, { from: 'customer', at: T(2026, 10, 19, 12) }, { from: 'staff', staff: 'Priya', at: T(2026, 10, 19, 13) }] }, cfg);
assert.equal(r.duplicate, false);
});
test('no reply after 3 days: unanswered at 24h and 48h, awaiting since the FIRST unanswered message', () => {
const r = C.analyzeThread({ id: 'e', messages: [{ from: 'customer', at: T(2026, 10, 19, 9) }, { from: 'customer', at: T(2026, 10, 21, 9) }] }, cfg);
assert.equal(r.unanswered24, true); assert.equal(r.unanswered48, true); assert.equal(r.neverAnswered, true);
assert.equal(r.awaiting, true); assert.equal(r.waitingSince, T(2026, 10, 19, 9)); assert.equal(r.frtMinutes, null);
});
test('a thread only 5 hours old is not judged at 24h/48h yet', () => {
const r = C.analyzeThread({ id: 'f', messages: [{ from: 'customer', at: T(2026, 10, 22, 11) }] }, cfg);
assert.equal(r.unanswered24, null); assert.equal(r.unanswered48, null);
});
test('reply after 30 clock hours: unanswered at 24h but not at 48h', () => {
const r = C.analyzeThread({ id: 'g', messages: [{ from: 'customer', at: T(2026, 10, 19, 9) }, { from: 'staff', staff: 'Maya', at: T(2026, 10, 20, 15) }] }, cfg);
assert.equal(r.unanswered24, true); assert.equal(r.unanswered48, false);
});
test('outbound-only thread is ignored', () => assert.equal(C.analyzeThread({ id: 'h', messages: [{ from: 'staff', staff: 'Maya', at: T(2026, 10, 19, 9) }] }, cfg), null));
console.log('audit');
test('median and p90 of first-response hours', () => {
// FRTs (business hours): 1, 2, 3, 4, 10 → median 3; p90 = 4 + 0.6×(10−4) = 7.6
const mk = (id, h) => ({ id, category: 'x', messages: [{ from: 'customer', at: T(2026, 10, 20, 9) }, { from: 'staff', staff: 'Jordan', at: C.addBusinessMinutes(T(2026, 10, 20, 9), h * 60, HOURS) }] });
const a = C.audit([mk(1, 1), mk(2, 2), mk(3, 3), mk(4, 4), mk(5, 10)], cfg);
assert.equal(a.medianFrtHours, 3); assert.equal(a.p90FrtHours, 7.6); assert.equal(a.threads, 5);
});
test('lookback window excludes older threads', () => {
const old = { id: 'o', messages: [{ from: 'customer', at: T(2026, 6, 1, 9) }] };
const recent = { id: 'r', messages: [{ from: 'customer', at: T(2026, 10, 20, 9) }] };
assert.equal(C.audit([old, recent], cfg).threads, 1);
});
test('staff share and outside-hours share', () => {
const ts = [
{ id: 1, messages: [{ from: 'customer', at: T(2026, 10, 19, 8) }, { from: 'staff', staff: 'Maya', at: T(2026, 10, 19, 10) }] }, // 8am = outside
{ id: 2, messages: [{ from: 'customer', at: T(2026, 10, 19, 12) }, { from: 'staff', staff: 'Maya', at: T(2026, 10, 19, 13) }] },
{ id: 3, messages: [{ from: 'customer', at: T(2026, 10, 25, 12) }, { from: 'staff', staff: 'Jordan', at: T(2026, 10, 26, 9) }] }, // Sunday = outside
];
const a = C.audit(ts, Object.assign({}, cfg, { asOf: T(2026, 10, 27, 12) }));
assert.equal(a.staff[0].staff, 'Maya'); assert.equal(a.staff[0].share, 0.6667); assert.equal(round2(a.outsideHoursShare), 0.67);
});
function round2(x) { return Math.round(x * 100) / 100; }
test('findings: ratio is computed from the displayed (rounded) medians', () => {
// Medians 18.68 h and 1.23 h display as 18.7 and 1.2 → ratio must read 15.6 (not 15.2).
const f = C.findings({ categories: [
{ category: 'cancel', threads: 20, medianFrtHours: 18.68, unanswered48: 0, duplicateRate: 0 },
{ category: 'trial', threads: 20, medianFrtHours: 1.23, unanswered48: 0, duplicateRate: 0 },
], staff: [], outsideHoursShare: null });
const slow = f.find(x => x.kind === 'slowest');
assert.equal(slow.ratio, 15.6);
assert.match(slow.text, /15\.6× longer .*median 18\.7 vs 1\.2/);
});
console.log('queue and nudges');
const routing = { cancel: { owner: 'Maya', slaHours: 4 }, trial: { owner: 'Jordan', slaHours: 2 } };
const qcfg = Object.assign({}, cfg, { routing, team: ['Maya', 'Jordan', 'Priya'], escalateUnclaimedHours: 24, dueSoonHours: 1 });
test('SLA due time and status at 16:00 Thu', () => {
const threads = [
{ id: 'late', category: 'cancel', messages: [{ from: 'customer', at: T(2026, 10, 22, 9) }] }, // due 13:00 → overdue by 3h
{ id: 'soon', category: 'trial', messages: [{ from: 'customer', at: T(2026, 10, 22, 14, 30) }] }, // due 16:30 → 30 min left
{ id: 'ok', category: 'cancel', messages: [{ from: 'customer', at: T(2026, 10, 22, 15, 30) }] }, // due Fri 10:30 → 120 (Thu) + 90 (Fri) = 210 min left
{ id: 'done', category: 'trial', messages: [{ from: 'customer', at: T(2026, 10, 22, 10) }, { from: 'staff', staff: 'Jordan', at: T(2026, 10, 22, 10, 5) }] },
];
const q = C.queue(threads, qcfg, { late: 'Maya' });
assert.deepEqual(q.map(x => x.id), ['late', 'soon', 'ok']);
assert.deepEqual(q.map(x => x.status), ['overdue', 'due-soon', 'on-track']);
assert.deepEqual(q.map(x => x.businessMinutesLeft), [-180, 30, 210]);
assert.equal(q[2].due, T(2026, 10, 23, 10, 30));
assert.equal(q[1].suggestedOwner, 'Jordan'); assert.equal(q[1].owner, null);
});
test('nudges: owner gets overdue items; old unclaimed items go to the whole team', () => {
const threads = [
{ id: 'late', category: 'cancel', messages: [{ from: 'customer', at: T(2026, 10, 22, 9) }] },
{ id: 'orphan', category: 'trial', messages: [{ from: 'customer', at: T(2026, 10, 20, 9) }] }, // unclaimed 55h
{ id: 'fresh', category: 'trial', messages: [{ from: 'customer', at: T(2026, 10, 22, 15, 45) }] },
];
const plan = C.nudges(C.queue(threads, qcfg, { late: 'Maya' }), qcfg);
const maya = plan.find(p => p.to === 'Maya');
assert.deepEqual(maya.items.map(i => i.id).sort(), ['late', 'orphan']);
assert.deepEqual(plan.find(p => p.to === 'Priya').items, [{ id: 'orphan', why: 'unclaimed' }]);
assert.equal(plan.length, 3);
});
test('requests older than staleDays are backlog, not nudged', () => {
const threads = [
{ id: 'ancient', category: 'cancel', messages: [{ from: 'customer', at: T(2026, 9, 1, 9) }] },
{ id: 'late', category: 'cancel', messages: [{ from: 'customer', at: T(2026, 10, 22, 9) }] },
];
const c = Object.assign({}, qcfg, { staleDays: 14 });
const q = C.queue(threads, c, { late: 'Maya', ancient: 'Maya' });
assert.deepEqual(q.map(x => [x.id, x.status]), [['late', 'overdue'], ['ancient', 'stale']]);
assert.deepEqual(C.nudges(q, c), [{ to: 'Maya', items: [{ id: 'late', why: 'overdue' }] }]);
});
console.log('triage');
const rules = C.compileRules({ cancel: [['\\bcancel', 3], ['\\bquit\\b', 2]], trial: [['\\btrial\\b', 3], ['first class', 2]] });
test('clear match routes automatically with confidence 1', () => {
const r = C.classify('I want to cancel my membership', rules, 0.6);
assert.equal(r.category, 'cancel'); assert.equal(r.confidence, 1); assert.equal(r.needsHuman, false);
});
test('mixed signals: 3 vs 3 → confidence 0.5 → human', () => {
const r = C.classify('cancel my trial', rules, 0.6);
assert.equal(r.confidence, 0.5); assert.equal(r.needsHuman, true);
});
test('no keyword → human', () => assert.equal(C.classify('hello?', rules, 0.6).needsHuman, true));
test('evaluation counts precision/recall correctly', () => {
const ev = C.evaluate([
{ text: 'cancel please', label: 'cancel' }, { text: 'free trial?', label: 'trial' },
{ text: 'I quit', label: 'cancel' }, { text: 'first class trial cancel', label: 'trial' }, // 5 vs 3 → trial, correct
{ text: 'is my trial cancelled', label: 'cancel' }, // 3 vs 3 → human
], rules, 0.6);
assert.equal(ev.autoRouted, 4); assert.equal(ev.humanQueue, 1); assert.equal(ev.autoPrecision, 1);
const cancel = ev.perClass.find(p => p.category === 'cancel');
assert.equal(cancel.recall, 0.667); assert.equal(cancel.precision, 1);
});
console.log(`\n${passed} tests passed`);
Runs the Gmail version against a fake inbox, including the privacy check.
// Runs apps-script/Pilot.gs against mocked GmailApp / SpreadsheetApp to check
// the Gmail → metadata conversion, the audit/queue sheets, nudges, and that no
// message body text is ever written to the spreadsheet.
const assert = require('node:assert/strict');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const ROOT = path.join(__dirname, '..');
const TZ = 'America/Los_Angeles';
// Real instants → Gmail messages. 2026-10-19 is a Monday (PDT = UTC−7).
const at = (d, h, m) => new Date(Date.UTC(2026, 9, d, h + 7, m || 0));
const SECRET = 'MY-CARD-ENDS-4242';
const SPEC = [
{ id: 'g1', subject: 'Cancel', msgs: [['pat@mail.example', at(19, 10), `Please cancel my membership. ${SECRET}`], ['maya@studio.example', at(19, 15)]] },
{ id: 'g2', subject: 'Free trial?', msgs: [['lee@mail.example', at(20, 9), 'Do you offer a free trial week?'], ['jordan@studio.example', at(20, 9, 30)], ['priya@studio.example', at(20, 9, 40)]] },
{ id: 'g3', subject: 'Charged twice', msgs: [['kim@mail.example', at(21, 10), 'I was charged twice, refund please']] }, // unanswered
{ id: 'g4', subject: 'hello', msgs: [['ash@mail.example', at(22, 8), 'hello?']] }, // ambiguous → needs-review
];
function gmailMock() {
const labels = { 'owner/Maya': ['g3'] };
const threads = SPEC.map(s => ({
getId: () => s.id,
getFirstMessageSubject: () => s.subject,
getMessages: () => s.msgs.map(([from, date, body]) => ({ getFrom: () => `Someone <${from}>`, getDate: () => date, getPlainBody: () => body || 'reply' })),
}));
return {
search: (q, start) => (start === 0 ? threads : []),
getUserLabelByName: n => (labels[n] !== undefined || n.startsWith('owner/') ? { getThreads: () => (labels[n] || []).map(id => threads.find(t => t.getId() === id)) } : null),
createLabel: n => { labels[n] = []; },
};
}
function sheetsMock() {
const sheets = {};
const mk = name => {
const cells = {};
const sh = {
cells, getName: () => name,
getRange(r, c, nr, nc) {
if (typeof r === 'string') { const m = /^([A-Z])(\d+)/.exec(r); return sh.getRange(Number(m[2]), m[1].charCodeAt(0) - 64, 1, 1); }
nr = nr || 1; nc = nc || 1;
const rng = {
setValues(v) { v.forEach((row, i) => row.forEach((x, j) => { cells[`${r + i},${c + j}`] = x; })); return rng; },
setValue(x) { cells[`${r},${c}`] = x; return rng; },
getValues() { return Array.from({ length: nr }, (_, i) => Array.from({ length: nc }, (_, j) => (cells[`${r + i},${c + j}`] ?? ''))); },
setFontWeight: () => rng, setFontSize: () => rng,
};
return rng;
},
getLastRow() { return Math.max(0, ...Object.keys(cells).filter(k => cells[k] !== '').map(k => Number(k.split(',')[0]))); },
clear() { Object.keys(cells).forEach(k => delete cells[k]); },
setColumnWidth() {}, appendRow(row) { const r = sh.getLastRow() + 1; row.forEach((x, j) => { cells[`${r},${j + 1}`] = x; }); },
};
sheets[name] = sh;
return sh;
};
return { sheets, ss: { getSheetByName: n => sheets[n] || null, insertSheet: mk } };
}
const sent = [];
const { sheets, ss } = sheetsMock();
const ctx = {
console,
GmailApp: gmailMock(),
SpreadsheetApp: { getActive: () => ss, getUi: () => ({ alert() {}, createMenu: () => ({}) }) },
Session: { getEffectiveUser: () => ({ getEmail: () => 'info@studio.example' }), getScriptTimeZone: () => TZ },
Utilities: {
formatDate(date, tz, fmt) {
const p = Object.fromEntries(new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }).formatToParts(date).map(x => [x.type, x.value]));
return fmt === "yyyy-MM-dd'T'HH:mm:ss" ? `${p.year}-${p.month}-${p.day}T${p.hour}:${p.minute}:${p.second}` : `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}`;
},
},
MailApp: { sendEmail: (to, subject, body) => sent.push({ to, subject, body }) },
ScriptApp: { getProjectTriggers: () => [], newTrigger: () => ({}), WeekDay: {} },
Date,
};
vm.createContext(ctx);
for (const f of ['core/inbox-core.js', 'core/triage-rules.js', 'apps-script/Pilot.gs']) vm.runInContext(fs.readFileSync(path.join(ROOT, f), 'utf8'), ctx, { filename: f });
// Objects built inside the vm have a different Array prototype; compare as plain JSON.
const eq = (a, b) => assert.deepEqual(JSON.parse(JSON.stringify(a)), b);
let passed = 0;
const test = (name, fn) => { fn(); passed++; console.log(' ✓ ' + name); };
ctx.setupPilot();
const S = sheets.Settings;
S.getRange(11, 1, 3, 2).setValues([['Maya', 'maya@studio.example'], ['Jordan', 'jordan@studio.example'], ['Priya', 'priya@studio.example']]);
S.getRange(11, 5, 8, 1).setValues([['Maya'], ['Jordan'], ['Maya'], ['Maya'], ['Jordan'], ['Maya'], ['Maya'], ['Jordan']]);
S.getRange(1, 2).setValue('info@studio.example');
// Freeze "now" at Thu Oct 22, 2026 16:00 PDT for deterministic results.
const realNow = Date.now;
ctx.Date = class extends Date { constructor(...a) { if (a.length) super(...a); else super(Date.UTC(2026, 9, 22, 23, 0)); } static now() { return Date.UTC(2026, 9, 22, 23, 0); } };
vm.runInContext('Date = this.Date', ctx);
console.log('pilot');
const st = ctx.readPilotSettings();
test('settings parse: team, hours, routing', () => {
eq(st.teamNames, ['Maya', 'Jordan', 'Priya']);
assert.equal(st.hours[0], null); eq(st.hours[1], [9, 18]); eq(st.hours[6], [9, 13]);
assert.equal(st.routing.cancel.owner, 'Maya'); assert.equal(st.routing.trial.slaHours, 2);
});
test('time conversion uses the studio time zone (10:00 PDT stays 10:00)', () => {
assert.equal(ctx.toWallClock(at(19, 10), TZ), Date.UTC(2026, 9, 19, 10));
});
const threads = ctx.fetchThreads(st);
test('Gmail threads convert: staff vs customer by address, category by triage', () => {
const g2 = threads.find(t => t.id === 'g2');
eq(g2.messages.map(m => [m.from, m.staff]), [['customer', null], ['staff', 'Jordan'], ['staff', 'Priya']]);
assert.equal(g2.category, 'trial');
assert.equal(threads.find(t => t.id === 'g1').category, 'cancel');
assert.equal(threads.find(t => t.id === 'g4').category, 'needs-review');
assert.equal(g2.subject, undefined); // subjects off by default
});
const a = ctx.runAudit();
test('audit numbers: g1 5h, g2 0.5h → median 2.75h; g2 duplicate; g3/g4 awaiting', () => {
assert.equal(a.threads, 4); assert.equal(a.medianFrtHours, 2.75); assert.equal(a.duplicateRate, 0.25); assert.equal(a.awaitingNow, 2);
});
test('PRIVACY: no message body text anywhere in the spreadsheet', () => {
const all = Object.values(sheets).flatMap(s => Object.values(s.cells)).map(String).join(' | ');
assert.ok(!all.includes(SECRET), 'body text leaked'); assert.ok(!all.includes('refund please'), 'body text leaked');
});
const q = ctx.refreshQueue();
test('queue: claimed via owner/Maya label; statuses at Thu 16:00', () => {
const g3 = q.find(x => x.id === 'g3'), g4 = q.find(x => x.id === 'g4');
assert.equal(g3.owner, 'Maya'); assert.equal(g3.status, 'overdue'); // billing SLA 8h from Wed 10:00 → Wed 18:00
assert.equal(g4.owner, null); assert.equal(g4.category, 'needs-review'); // default 8h from Thu 09:00 (arrived 08:00) → Thu 17:00, 60 min left
assert.equal(g4.status, 'due-soon'); // 60 business min left
});
ctx.hourlyNudge();
test('nudge: one batched email to Maya for her overdue thread; nobody else yet', () => {
assert.equal(sent.length, 1); assert.equal(sent[0].to, 'maya@studio.example'); assert.match(sent[0].body, /Overdue: .*g3/);
});
console.log(`\n${passed} pilot tests passed`);
Scores each rule version on the four test sets.
// Triage evaluation on unique phrasings (body text only, so every split is
// scored the same way). Writes web/data/triage-eval.json for the demo.
const fs = require('fs');
const path = require('path');
const C = require('../core/inbox-core.js');
const V1 = require('../core/triage-rules.v1.js');
const V2 = require('../core/triage-rules.v2.js');
const V21 = require('../core/triage-rules.js');
const { PHRASINGS, CATEGORIES } = require('../data/phrasings.js');
const HOLDOUT = require('../data/holdout.js');
const cats = Object.keys(CATEGORIES);
const split = name => cats.flatMap(c => PHRASINGS[c][name].map(([, body]) => ({ text: body, label: c })));
const sets = {
dev: split('dev'),
test: split('test'),
// Written during the build just before v2; words from it leaked into v2, so
// this is development data now, not a fair test.
holdout: cats.flatMap(c => HOLDOUT[c].map(text => ({ text, label: c }))),
// Written by an independent author who never saw the rules or any examples.
blind: require('../data/blind.json').items,
};
const THRESHOLD = 0.6;
const results = {};
for (const [ver, rules] of [['v1', V1], ['v2', V2], ['v2.1', V21]]) {
const compiled = C.compileRules(rules);
results[ver] = {};
for (const [name, items] of Object.entries(sets)) {
const ev = C.evaluate(items, compiled, THRESHOLD, cats);
results[ver][name] = ev;
}
}
const pct = x => (x === null ? '—' : Math.round(x * 100) + '%');
console.log('version split n top-label auto-routed auto-precision to-human');
for (const ver of ['v1', 'v2', 'v2.1']) for (const name of Object.keys(sets)) {
const e = results[ver][name];
console.log(`${ver.padEnd(8)} ${name.padEnd(8)} ${String(e.n).padStart(3)} ${pct(e.topLabelAccuracy).padStart(6)} ${pct(e.autoRate).padStart(6)} ${pct(e.autoPrecision).padStart(6)} ${String(e.humanQueue).padStart(3)}`);
}
const h = results.v2.blind;
console.log('\nv2 BLIND per class:', h.perClass.map(p => `${p.category} P${pct(p.precision)} R${pct(p.recall)}`).join(' | '));
console.log('v2 BLIND auto-routed mistakes:');
h.errors.forEach(e => console.log(` ✗ ${e.label} → ${e.predicted} (${e.confidence}) ${e.text}`));
fs.writeFileSync(path.join(__dirname, '..', 'web', 'data', 'triage-eval.json'), JSON.stringify({
threshold: THRESHOLD, categories: CATEGORIES,
summary: Object.fromEntries(['v1', 'v2', 'v2.1'].map(v => [v, Object.fromEntries(Object.entries(results[v]).map(([k, e]) => [k, {
n: e.n, topLabelAccuracy: e.topLabelAccuracy, autoRate: e.autoRate, autoPrecision: e.autoPrecision, humanQueue: e.humanQueue,
}]))])),
blind: { perClass: h.perClass, matrix: h.matrix, errors: h.errors },
}, null, 1));
module.exports = results;