Skip to content
← Public packages

@kentcdodds/quiet-hours

Quiet hours for Kent's bots: 10 PM to 8 AM MT (DST-aware) clock, shared overnight queue, override, and the 8 AM digest of finished work and open decisions.

FollowFork

Files

queue.ts

116 lines · 4.2 KB · TypeScript
import { insertItem, setWaitingOnMe } from './store.ts'
import { mirrorToWaitingOnMe } from './mirror.ts'
import { isExcludedBot, parseNow } from './status-core.ts'
import { ITEM_KINDS, PRIORITIES, type ItemKind, type Priority, type QueueItem } from './types.ts'

export type QueueInput = {
	/** Bot name that produced the item (e.g. 'Cole'). Lilly and Imogen are refused. */
	bot: string
	/** done | needs-decision | fyi | kent-request (kent-request is legacy; digested as fyi). */
	kind: ItemKind
	/** urgent | high | normal | low. Default normal. */
	priority?: Priority
	/** One-line summary Kent reads in the digest. */
	title: string
	/** Where Kent acts or reads more. Required for needs-decision (Waiting on Me needs it). */
	link?: string
	/** Optional longer context. */
	detail?: string
	/** Optional ISO hard deadline. A deadline on the digest's local day (or earlier) lands in "Due today". */
	deadline?: string
	/** Optional ISO instant to stamp instead of now (tests). */
	now?: string
}

function text(value: unknown, field: string, required: boolean, max: number): string | null {
	if (value == null || value === '') {
		if (required) throw new Error(`${field} is required.`)
		return null
	}
	if (typeof value !== 'string') throw new Error(`${field} must be a string.`)
	const trimmed = value.trim()
	if (!trimmed) {
		if (required) throw new Error(`${field} is required.`)
		return null
	}
	return trimmed.slice(0, max)
}

/** Pure validation + normalization (exported for tests). */
export function normalizeQueueInput(input: QueueInput, now: Date): QueueItem {
	const bot = text(input?.bot, 'bot', true, 80) as string
	const kind = input?.kind
	if (!(ITEM_KINDS as ReadonlyArray<string>).includes(kind as string)) {
		throw new Error(`kind must be one of ${ITEM_KINDS.join(', ')}.`)
	}
	const priority = input?.priority ?? 'normal'
	if (!(PRIORITIES as ReadonlyArray<string>).includes(priority)) {
		throw new Error(`priority must be one of ${PRIORITIES.join(', ')}.`)
	}
	const link = text(input?.link, 'link', kind === 'needs-decision', 2000)
	if (link && !/^https?:\/\//i.test(link)) throw new Error('link must be an http(s) URL.')
	let deadline = text(input?.deadline, 'deadline', false, 64)
	if (deadline) {
		const parsed = Date.parse(deadline)
		if (!Number.isFinite(parsed)) throw new Error('deadline must be an ISO timestamp.')
		deadline = new Date(parsed).toISOString()
	}
	return {
		id: crypto.randomUUID(),
		createdAt: now.toISOString(),
		bot,
		kind: kind as ItemKind,
		priority: priority as Priority,
		title: text(input?.title, 'title', true, 300) as string,
		link,
		detail: text(input?.detail, 'detail', false, 4000),
		deadline,
		deliveredAt: null,
		digestId: null,
		waitingOnMe: null,
	}
}

/**
 * Append an item to the shared overnight queue for the 8 AM digest.
 * Use `needs-decision` when work needs Kent's input and is not urgent: stop
 * at that point and queue it. Work that does not need Kent keeps going; queue
 * a `done` when it finishes. needs-decision items are mirrored into
 * @kentcdodds/waiting-on-me (`create`) so they persist after the digest.
 * Lilly and Imogen are excluded and get `{ queued: false, excluded: true }`.
 *
 * @param input - `{ bot, kind, priority?, title, link?, detail?, deadline? }`
 * @returns `{ ok, queued, item, waitingOnMe }`
 *
 * @example
 * import queue from 'kody:@kentcdodds/quiet-hours/queue'
 * await queue({
 *   bot: 'Cole',
 *   kind: 'needs-decision',
 *   priority: 'high',
 *   title: 'Approve rollback cleanup PR #2412',
 *   link: 'https://github.com/kody-hq/kody/pull/2412',
 * })
 */
export default async function queue(input: QueueInput) {
	if (isExcludedBot(input?.bot)) {
		return {
			ok: true as const,
			queued: false as const,
			excluded: true as const,
			reason: `${String(input.bot).trim()} is excluded from quiet hours and never writes to the shared queue.`,
		}
	}
	const item = normalizeQueueInput(input, parseNow(input?.now))
	await insertItem(item)
	let waitingOnMe: QueueItem['waitingOnMe'] = null
	if (item.kind === 'needs-decision') {
		waitingOnMe = await mirrorToWaitingOnMe(item)
		try {
			await setWaitingOnMe(item.id, waitingOnMe)
		} catch {
			// Recording the mirror outcome is best-effort.
		}
	}
	return { ok: true as const, queued: true as const, item: { ...item, waitingOnMe }, waitingOnMe }
}