src/plan.js
// Free-time computation and time-block placement for personal-productivity. Pure functions over
// epoch milliseconds; local labels use the planning time zone (DST-correct via tz.js).
import { createHash } from "node:crypto";
import { ToolError } from "./errors.js";
import { zonedToUtc, fromDayNum, weekday, parseYmd, isoUtc, isoLocal, parseInstant } from "./tz.js";
import { PRIORITY_ORDER } from "./tasks.js";
const MIN = 60000;
const DAY = 86400000;
const WD = { SU: 0, MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6 };
export function merge(list) {
const sorted = list.filter(([s, e]) => e > s).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
const out = [];
for (const [s, e] of sorted) {
const last = out[out.length - 1];
if (last && s <= last[1]) last[1] = Math.max(last[1], e);
else out.push([s, e]);
}
return out;
}
function subtract(free, busy) {
const out = [];
for (const [fs, fe] of free) {
let cur = fs;
for (const [bs, be] of busy) {
if (be <= cur || bs >= fe) continue;
if (bs > cur) out.push([cur, Math.min(bs, fe)]);
cur = Math.max(cur, be);
if (cur >= fe) break;
}
if (cur < fe) out.push([cur, fe]);
}
return out;
}
const parseInterval = (x, field) => {
const s = parseInstant(x.start);
const e = parseInstant(x.end);
if (s === null || e === null) throw new ToolError("invalid_input", `${field}: start/end must be ISO 8601 date-times with Z or an offset.`);
if (e <= s) throw new ToolError("invalid_input", `${field}: end must be after start.`);
return [s, e];
};
/** Free intervals from explicit slots, or from working hours minus busy time. */
export function freeTime(input, tz) {
if (input.slots && input.working_hours) throw new ToolError("invalid_input", "Give slots or working_hours, not both.");
const busy = merge((input.busy ?? []).map((b, i) => parseInterval(b, `busy[${i}]`)));
if (input.slots) return subtract(merge(input.slots.map((s, i) => parseInterval(s, `slots[${i}]`))), busy);
const wh = input.working_hours;
if (!wh) throw new ToolError("invalid_input", "Give slots (e.g. find_free_slots output) or working_hours with date_from and date_to.");
if (!input.date_from || !input.date_to) throw new ToolError("invalid_input", "working_hours needs date_from and date_to (YYYY-MM-DD).");
const from = parseYmd(input.date_from);
const to = parseYmd(input.date_to);
if (from === null || to === null) throw new ToolError("invalid_input", "date_from/date_to must be real calendar dates.");
if (to < from) throw new ToolError("invalid_input", "date_to must not be before date_from.");
if (to - from + 1 > (input.max_days ?? 14)) throw new ToolError("invalid_input", `The date range may span at most ${input.max_days ?? 14} days (max_days).`);
const days = new Set((wh.days ?? ["MO", "TU", "WE", "TH", "FR"]).map((d) => WD[d]));
const [sh, sm] = wh.start.split(":").map(Number);
const [eh, em] = wh.end.split(":").map(Number);
const startMin = sh * 60 + sm;
const endMin = eh * 60 + em;
if (endMin <= startMin) throw new ToolError("invalid_input", "working_hours.end must be after start (overnight hours are not supported).");
const windows = [];
for (let day = from; day <= to; day++) {
if (!days.has(weekday(day))) continue;
const f = fromDayNum(day);
const ws = zonedToUtc(f.y, f.m, f.d, sh, sm, 0, tz);
const n = fromDayNum(day + 1);
const we = endMin === 1440 ? zonedToUtc(n.y, n.m, n.d, 0, 0, 0, tz) : zonedToUtc(f.y, f.m, f.d, eh, em, 0, tz);
windows.push([ws, we]);
}
return subtract(windows, busy);
}
const QUADRANT_RANK = { do: 0, schedule: 1, delegate: 2, eliminate: 3, unsorted: 4 };
/**
* Places tasks into free time. `items` = [{ task, quadrant }]. Returns blocks/unscheduled/at_risk and
* what is left of `free` (mutated copy).
*/
export function placeBlocks(items, freeIn, opts) {
let free = freeIn.map((x) => [...x]);
const blocks = [];
const unscheduled = [];
const atRisk = [];
const breakMs = (opts.breakMinutes ?? 0) * MIN;
const minChunk = (opts.minBlockMinutes ?? 25) * MIN;
const sorted = [...items].sort(
(a, b) =>
QUADRANT_RANK[a.quadrant] - QUADRANT_RANK[b.quadrant] ||
(a.task.due ?? "9999-99-99").localeCompare(b.task.due ?? "9999-99-99") ||
(PRIORITY_ORDER[a.task.priority] ?? 3) - (PRIORITY_ORDER[b.task.priority] ?? 3) ||
a.index - b.index,
);
for (const { task, quadrant } of sorted) {
const minutes = task.effort_minutes ?? opts.defaultBlockMinutes ?? null;
if (!minutes) {
unscheduled.push({ task_id: task.id, title: task.title, reason: "No effort estimate on the task (add ~30m or est:1h, or set default_block_minutes); none was invented." });
continue;
}
const need = minutes * MIN;
let pieces = null;
const single = free.findIndex(([s, e]) => e - s >= need);
if (single >= 0) pieces = [[single, free[single][0], free[single][0] + need]];
else if (opts.allowSplit !== false) {
let remaining = need;
const plan = [];
for (const [i, [s, e]] of free.entries()) {
if (remaining <= 0) break;
const take = Math.min(remaining, e - s);
if (take < minChunk && take < remaining) continue;
plan.push([i, s, s + take]);
remaining -= take;
}
if (remaining <= 0) pieces = plan;
}
if (!pieces) {
const left = Math.round(free.reduce((n, [s, e]) => n + (e - s), 0) / MIN);
unscheduled.push({
task_id: task.id,
title: task.title,
reason: opts.allowSplit === false ? `No single free slot of ${minutes} min (allow_split is false).` : `Not enough free time: needs ${minutes} min in pieces of at least ${opts.minBlockMinutes ?? 25} min; ${left} min of free time left.`,
});
continue;
}
for (const [k, [i, s, e]] of pieces.entries()) {
const block = { task_id: task.id, title: task.title, start: s, end: e, minutes: Math.round((e - s) / MIN), quadrant };
if (pieces.length > 1) Object.assign(block, { part: k + 1, parts: pieces.length });
blocks.push(block);
free[i] = [e + breakMs, free[i][1]];
}
free = free.filter(([s, e]) => e - s >= MIN);
if (task.due) {
const d = parseYmd(task.due);
const f = fromDayNum(d + 1);
const dueEnd = zonedToUtc(f.y, f.m, f.d, 0, 0, 0, opts.tz);
const lastEnd = pieces[pieces.length - 1][2];
if (d < opts.todayDay) atRisk.push({ task_id: task.id, title: task.title, reason: `Already overdue (due ${task.due}).` });
else if (lastEnd > dueEnd) atRisk.push({ task_id: task.id, title: task.title, reason: `Planned to finish ${isoLocal(lastEnd, opts.tz)}, after its due date ${task.due}.` });
}
}
blocks.sort((a, b) => a.start - b.start);
return { blocks, unscheduled, atRisk, free };
}
export function blockOutput(b, tz) {
return { ...b, start: isoUtc(b.start), end: isoUtc(b.end), local_start: isoLocal(b.start, tz), local_end: isoLocal(b.end, tz) };
}
export function blockEvent(b, tz) {
const uid = `${createHash("sha256").update(JSON.stringify([b.task_id, b.start, b.end])).digest("hex").slice(0, 24)}@agentrove.personal-productivity`;
const summary = `Focus: ${b.title}${b.parts ? ` (part ${b.part}/${b.parts})` : ""}`;
return { uid, summary, start: isoUtc(b.start), end: isoUtc(b.end), timezone: tz };
}
export const DAY_MS = DAY;