src/index.js
// AgentRove native agent: personal-productivity (MIT).
// Tools: parse_tasks, classify_eisenhower, plan_time_blocks, review_checklist. All offline and
// side-effect free. Effort, due dates and priorities come only from what the user wrote.
import { readFileSync } from "node:fs";
import { defineAgent, makeContext, handleMcpMessage, runCli, runMcpStdio, validateManifest } from "../sdk/index.js";
import { ToolError } from "./errors.js";
import { isValidTimeZone, parseYmd, ymd, utcToZoned, dayNum, isoUtc } from "./tz.js";
import { loadTasks, parseMarkdown, classifyAll, QUADRANTS, describeTask, md } from "./tasks.js";
import { freeTime, placeBlocks, blockOutput, blockEvent } from "./plan.js";
import { buildReview } from "./review.js";
export { makeContext, handleMcpMessage, runCli, runMcpStdio, validateManifest };
export const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
const LABELS = { do: "Do first (urgent and important)", schedule: "Schedule (important or dated, not urgent)", delegate: "Delegate (urgent, not important)", eliminate: "Eliminate or defer (no due date, not important)", unsorted: "Unsorted (no due date, priority or tag)" };
function requireTz(tz, field = "timezone") {
if (!isValidTimeZone(tz)) throw new ToolError("invalid_input", `${field}: unknown IANA time zone "${String(tz).slice(0, 64)}"`);
return tz;
}
function todayOf(input, ctx, tz) {
if (input.today !== undefined) {
const d = parseYmd(input.today);
if (d === null) throw new ToolError("invalid_input", "today must be a real calendar date (YYYY-MM-DD).");
return d;
}
const z = utcToZoned(ctx.now().getTime(), tz);
return dayNum(z.y, z.m, z.d);
}
const classOpts = (input) => ({ urgentWithin: input.urgent_within_days ?? 2, importantPriorities: input.important_priorities ?? ["high"] });
function effortNote(tasks) {
const n = tasks.filter((t) => !t.done && !t.effort_minutes).length;
return n ? [`${n} open task(s) have no effort estimate; none was invented.`] : [];
}
async function parse_tasks(input, ctx) {
const tz = requireTz(input.timezone ?? "UTC");
const { tasks, warnings } = parseMarkdown(input.markdown, todayOf(input, ctx, tz));
const done = tasks.filter((t) => t.done).length;
return { tasks, counts: { total: tasks.length, open: tasks.length - done, done }, warnings };
}
async function classify_eisenhower(input, ctx) {
const tz = requireTz(input.timezone ?? "UTC");
const todayDay = todayOf(input, ctx, tz);
const { tasks, warnings } = loadTasks(input, todayDay);
const quadrants = classifyAll(tasks, todayDay, classOpts(input), input.include_done === true);
const counts = Object.fromEntries(QUADRANTS.map((q) => [q, quadrants[q].length]));
const lines = [`# Eisenhower matrix: ${ymd(todayDay)}`];
for (const q of QUADRANTS) {
lines.push("", `## ${LABELS[q]}`, "");
if (!quadrants[q].length) lines.push("_None._");
for (const t of quadrants[q]) lines.push(`- [ ] ${describeTask(t)}`, ` - why: ${md(t.reasons.join("; "))}`);
}
const notes = [...warnings, ...effortNote(tasks)];
if (counts.unsorted) notes.push(`${counts.unsorted} task(s) are unsorted because they carry no due date, priority or urgent/important tag.`);
return { today: ymd(todayDay), quadrants, counts, markdown: lines.join("\n") + "\n", notes };
}
async function plan_time_blocks(input, ctx) {
const tz = requireTz(input.working_hours?.timezone ?? input.timezone ?? "UTC", input.working_hours ? "working_hours.timezone" : "timezone");
if (input.working_hours && input.timezone && input.timezone !== input.working_hours.timezone) throw new ToolError("invalid_input", "timezone and working_hours.timezone differ; give one.");
const todayDay = todayOf(input, ctx, tz);
const { tasks, warnings } = loadTasks(input, todayDay);
let free = freeTime(input, tz);
if (input.exclude_past !== false) {
const notBefore = Math.ceil(ctx.now().getTime() / 300000) * 300000;
free = free.map(([s, e]) => [Math.max(s, notBefore), e]).filter(([s, e]) => e > s);
}
const available = Math.round(free.reduce((n, [s, e]) => n + (e - s), 0) / 60000);
const quadrants = classifyAll(tasks, todayDay, classOpts(input));
const include = new Set(input.include_quadrants ?? ["do", "schedule"]);
// Default plan: do-first, then scheduled tasks, then any remaining free time is filled with unsorted
// tasks that carry a written effort estimate (they are placed last, so they only use leftover time).
// An explicit include_quadrants list turns this fill off and is followed exactly.
const fillUnsorted = input.include_quadrants === undefined;
const items = [];
const unscheduled = [];
let index = 0;
let filled = 0;
for (const q of QUADRANTS) {
for (const c of quadrants[q]) {
const task = tasks.find((t) => t.id === c.id);
const fill = fillUnsorted && q === "unsorted";
if (task.waiting && (include.has(q) || fill)) unscheduled.push({ task_id: task.id, title: task.title, reason: "Tagged waiting/delegate: someone else holds this task, so no focus time was blocked. Follow up with them instead." });
else if (include.has(q)) items.push({ task, quadrant: q, index: index++ });
else if (fill && task.effort_minutes) {
items.push({ task, quadrant: q, index: index++ });
filled++;
} else if (fill) unscheduled.push({ task_id: task.id, title: task.title, reason: "Unsorted (no due date, priority or tag) and no effort estimate, so it was not used to fill free time; add an estimate (~30m) or a due date or priority. None was invented." });
else unscheduled.push({ task_id: task.id, title: task.title, reason: q === "delegate" ? "Delegate quadrant: hand it off instead of blocking your own time (or add it to include_quadrants)." : `${LABELS[q]}: not included (include_quadrants).` });
}
}
if (filled) warnings.push(`${filled} unsorted task(s) with a written effort estimate were used to fill free time left after do-first and scheduled tasks; pass include_quadrants to plan only specific quadrants.`);
const r = placeBlocks(items, free, { breakMinutes: input.break_minutes, minBlockMinutes: input.min_block_minutes, allowSplit: input.allow_split, defaultBlockMinutes: input.default_block_minutes, tz, todayDay });
const blocks = r.blocks.map((b) => blockOutput(b, tz));
const planned = r.blocks.reduce((n, b) => n + b.minutes, 0);
if (!free.length) warnings.push("No free time in the given slots or working hours (after removing busy and past time).");
warnings.push(...effortNote(tasks));
warnings.push("Nothing was added to any calendar. Review the events and import them yourself if you want them (for example with calendar-assistant propose_meeting).");
return {
timezone: tz,
blocks,
events: r.blocks.map((b) => blockEvent(b, tz)),
unscheduled: [...r.unscheduled, ...unscheduled],
at_risk: r.atRisk,
remaining_slots: r.free.filter(([s, e]) => e - s >= 5 * 60000).map(([s, e]) => ({ start: isoUtc(s), end: isoUtc(e) })),
summary: { available_minutes: available, planned_minutes: planned, tasks_planned: new Set(r.blocks.map((b) => b.task_id)).size },
warnings,
};
}
async function review_checklist(input, ctx) {
const tz = requireTz(input.timezone ?? "UTC");
const todayDay = todayOf(input, ctx, tz);
const { tasks } = loadTasks(input, todayDay);
const quadrants = classifyAll(tasks, todayDay, classOpts(input));
const r = buildReview(input.kind, tasks, quadrants, todayDay, ymd(todayDay), input.max_items ?? 10);
return { kind: input.kind, today: ymd(todayDay), markdown: r.markdown, sections: r.sections };
}
const agent = defineAgent(manifest, { parse_tasks, classify_eisenhower, plan_time_blocks, review_checklist });
export default agent;