Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Personal Productivity v0.1.2 · generic

Archive SHA-256 a60f0d4435477cdd1283b89508dd4fecd555b4e30577796e13eebf8ab7f717ec · 37.8 KB · built Nov 27, 2026

src/tasks.js

// Markdown checkbox parsing, task normalisation and Eisenhower classification for personal-productivity.
// Only what is written on a task is used: no effort, due date or priority is ever inferred.
import { ToolError } from "./errors.js";
import { parseYmd, ymd } from "./tz.js";

const E = (cp) => String.fromCodePoint(cp);
const DUE_EMOJI = E(0x1f4c5); // calendar
const DONE_EMOJI = E(0x2705); // check mark button
const OTHER_DATE_EMOJI = [E(0x23f3), E(0x1f6eb), E(0x2795)]; // scheduled, start, created
const PRIO_EMOJI = { [E(0x1f53a)]: "high", [E(0x23eb)]: "high", [E(0x1f53c)]: "medium", [E(0x1f53d)]: "low", [E(0x23ec)]: "low" };
const PRIO_WORD = { high: "high", h: "high", p1: "high", 1: "high", a: "high", medium: "medium", med: "medium", m: "medium", p2: "medium", 2: "medium", b: "medium", low: "low", l: "low", p3: "low", 3: "low", c: "low" };
const PRIORITY_RANK = { high: 0, medium: 1, low: 2 };
export const QUADRANTS = ["do", "schedule", "delegate", "eliminate", "unsorted"];

const CHECKBOX = /^(\s*)(?:[-*+]|\d+[.)])\s+\[([ xX/-])\]\s+(.*)$/;
const HEADING = /^#{1,6}\s+(.+?)\s*#*\s*$/;
const END = "(?=$|\\s|[,.;:!?)])";

/** "45m", "1h", "1.5h", "1h30m", "90min" -> minutes, or null. */
export function parseDuration(s) {
  const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+)m(?:in)?)?$/i.exec(String(s).trim());
  if (!m || (m[1] === undefined && m[2] === undefined)) return null;
  const minutes = Math.round(Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0));
  return minutes > 0 && minutes <= 10080 ? minutes : null;
}

function resolveDate(token, todayDay, warn, label) {
  const t = token.toLowerCase();
  if (t === "today") return ymd(todayDay);
  if (t === "tomorrow") return ymd(todayDay + 1);
  if (parseYmd(token) === null) {
    warn(`${label}: "${token}" is not a real calendar date; ignored.`);
    return null;
  }
  return token;
}

/** Parses one checkbox's text into fields. */
function parseTaskText(raw, todayDay, warn, label) {
  let text = ` ${raw} `;
  const f = { due: null, done_date: null, priority: null, effort_minutes: null, tags: [], urgent: false, important: false, waiting: false };
  const setPriority = (p) => {
    if (f.priority && f.priority !== p) warn(`${label}: more than one priority marker; kept "${f.priority}".`);
    f.priority ??= p;
  };
  const take = (re, fn) => {
    text = text.replace(re, (...m) => {
      fn(m);
      return " ";
    });
  };
  // Leading todo.txt priority "(A) ".
  take(/^\s\(([ABC])\)\s/, (m) => setPriority(PRIO_WORD[m[1].toLowerCase()]));
  take(new RegExp(`\\s(?:due::?\\s*|@due\\()(\\d{4}-\\d{2}-\\d{2}|today|tomorrow)\\)?${END}`, "gi"), (m) => {
    const d = resolveDate(m[1], todayDay, warn, label);
    if (d) f.due ??= d;
  });
  take(new RegExp(`\\s${DUE_EMOJI}\\uFE0F?\\s*(\\d{4}-\\d{2}-\\d{2})${END}`, "gu"), (m) => {
    const d = resolveDate(m[1], todayDay, warn, label);
    if (d) f.due ??= d;
  });
  take(new RegExp(`\\s(?:done::?\\s*|${DONE_EMOJI}\\uFE0F?\\s*)(\\d{4}-\\d{2}-\\d{2})${END}`, "giu"), (m) => {
    f.done_date ??= resolveDate(m[1], todayDay, warn, label);
  });
  take(new RegExp(`\\s(?:${OTHER_DATE_EMOJI.join("|")})\\uFE0F?\\s*\\d{4}-\\d{2}-\\d{2}${END}`, "gu"), () => {});
  take(new RegExp(`\\s!(high|h|medium|med|m|low|l|p[1-3]|[1-3])${END}`, "gi"), (m) => setPriority(PRIO_WORD[m[1].toLowerCase()]));
  take(new RegExp(`\\spriority::?\\s*(high|medium|low|p[1-3])${END}`, "gi"), (m) => setPriority(PRIO_WORD[m[1].toLowerCase()]));
  take(/\s\[#([ABC])\](?=$|\s)/g, (m) => setPriority(PRIO_WORD[m[1].toLowerCase()]));
  take(new RegExp(`\\s(${Object.keys(PRIO_EMOJI).join("|")})\\uFE0F?(?=$|\\s)`, "gu"), (m) => setPriority(PRIO_EMOJI[m[1]]));
  take(new RegExp(`\\s(?:~|(?:est|effort|estimate)::?\\s*)(\\d+(?:\\.\\d+)?h(?:\\d+m(?:in)?)?|\\d+m(?:in)?)${END}`, "gi"), (m) => {
    const d = parseDuration(m[1]);
    if (d === null) warn(`${label}: effort "${m[1]}" is out of range; ignored.`);
    else f.effort_minutes ??= d;
  });
  take(/\s[#!](urgent)(?=$|\s)/gi, () => (f.urgent = true));
  take(/\s[#!](important)(?=$|\s)/gi, () => (f.important = true));
  take(/\s[#@](waiting|delegate|delegated)(?=$|\s)/gi, () => (f.waiting = true));
  take(/\s#([\p{L}\p{N}_/-]{1,100})(?=$|\s)/gu, (m) => {
    if (!f.tags.includes(m[1])) f.tags.push(m[1]);
  });
  f.title = text.replace(/\s+/g, " ").trim();
  return f;
}

export function parseMarkdown(markdown, todayDay) {
  const warnings = [];
  const warn = (w) => warnings.length < 200 && warnings.push(w);
  const tasks = [];
  const stack = [];
  let section = null;
  const lines = String(markdown).replace(/\r\n?/g, "\n").split("\n");
  let inFence = false;
  for (const [i, line] of lines.entries()) {
    if (/^\s*(```|~~~)/.test(line)) {
      inFence = !inFence;
      continue;
    }
    if (inFence) continue;
    const h = HEADING.exec(line);
    if (h) {
      section = h[1].slice(0, 300);
      stack.length = 0;
      continue;
    }
    const m = CHECKBOX.exec(line);
    if (!m) continue;
    const indent = m[1].replace(/\t/g, "    ").length;
    const label = `line ${i + 1}`;
    const f = parseTaskText(m[3].slice(0, 2000), todayDay, warn, label);
    while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
    const id = `L${i + 1}`;
    const state = m[2];
    const task = {
      id,
      title: f.title || "(untitled)",
      done: state === "x" || state === "X" || state === "-",
      due: f.due,
      done_date: f.done_date,
      priority: f.priority,
      effort_minutes: f.effort_minutes,
      tags: f.tags,
      urgent: f.urgent,
      important: f.important,
      waiting: f.waiting,
      section,
      line: i + 1,
      parent_id: stack.length ? stack[stack.length - 1].id : null,
      raw: m[3].slice(0, 2000),
    };
    if (state === "-") task.tags = [...task.tags, "cancelled"];
    if (!f.title) warn(`${label}: task has no title.`);
    tasks.push(task);
    stack.push({ indent, id });
    if (tasks.length >= 5000) {
      warn("Stopped after 5000 tasks.");
      break;
    }
  }
  if (!tasks.length) warnings.push("No Markdown checkboxes found. Tasks look like: - [ ] Write report due:2026-12-01 !high ~45m");
  return { tasks, warnings };
}

/** Normalises either markdown or a tasks array (parse_tasks output) into a task list. */
export function loadTasks(input, todayDay) {
  if ((input.markdown === undefined) === (input.tasks === undefined)) throw new ToolError("invalid_input", "Provide exactly one of markdown or tasks.");
  if (input.markdown !== undefined) return parseMarkdown(input.markdown, todayDay);
  const warnings = [];
  const ids = new Set();
  const tasks = input.tasks.map((t, i) => {
    if (ids.has(t.id)) throw new ToolError("invalid_input", `tasks[${i}].id "${t.id}" is duplicated.`);
    ids.add(t.id);
    for (const k of ["due", "done_date"]) {
      if (t[k] !== undefined && t[k] !== null && parseYmd(t[k]) === null) throw new ToolError("invalid_input", `tasks[${i}].${k} must be YYYY-MM-DD.`);
    }
    return { done: false, due: null, done_date: null, priority: null, effort_minutes: null, tags: [], urgent: false, important: false, waiting: false, section: null, ...t };
  });
  return { tasks, warnings };
}

export function classify(task, todayDay, opts) {
  const reasons = [];
  let urgent = false;
  let urgentKnown = false;
  let important = false;
  let importantKnown = false;
  if (task.due) {
    const d = parseYmd(task.due);
    urgentKnown = true;
    const diff = d - todayDay;
    if (diff < 0) {
      urgent = true;
      reasons.push(`overdue by ${-diff} day(s) (due ${task.due})`);
    } else if (diff <= opts.urgentWithin) {
      urgent = true;
      reasons.push(diff === 0 ? `due today (${task.due})` : `due ${task.due}, ${diff} day(s) away (within the ${opts.urgentWithin}-day urgency threshold)`);
    } else reasons.push(`due ${task.due}, ${diff} days away (beyond the ${opts.urgentWithin}-day urgency threshold)`);
  }
  if (task.urgent) {
    urgent = true;
    urgentKnown = true;
    reasons.push("tagged urgent");
  }
  if (task.priority) {
    importantKnown = true;
    if (opts.importantPriorities.includes(task.priority)) {
      important = true;
      reasons.push(`priority ${task.priority}`);
    } else reasons.push(`priority ${task.priority} (important priorities: ${opts.importantPriorities.join(", ")})`);
  }
  if (task.important) {
    important = true;
    importantKnown = true;
    reasons.push("tagged important");
  }
  if (!urgentKnown && !importantKnown) return { quadrant: "unsorted", reasons: ["no due date, priority or urgent/important tag, so it was not classified; add one"] };
  if (!urgentKnown) reasons.push("no due date: treated as not urgent");
  if (!importantKnown) reasons.push("no priority: treated as not important");
  if (task.waiting) reasons.push("tagged waiting/delegate");
  let quadrant = urgent ? (important ? "do" : "delegate") : important ? "schedule" : "eliminate";
  // A task with a real due date is a commitment: it is scheduled before that date, never "eliminated".
  if (quadrant === "eliminate" && task.due) {
    quadrant = "schedule";
    reasons.push(`has a due date (${task.due}), so it is scheduled before then instead of eliminated`);
  }
  return { quadrant, reasons };
}

export function classifyAll(tasks, todayDay, opts, includeDone = false) {
  const quadrants = Object.fromEntries(QUADRANTS.map((q) => [q, []]));
  for (const t of tasks) {
    if (t.done && !includeDone) continue;
    const c = classify(t, todayDay, opts);
    quadrants[c.quadrant].push({ id: t.id, title: t.title, done: t.done, due: t.due, priority: t.priority, effort_minutes: t.effort_minutes, quadrant: c.quadrant, reasons: c.reasons });
  }
  const order = (a, b) => (a.due ?? "9999-99-99").localeCompare(b.due ?? "9999-99-99") || (PRIORITY_RANK[a.priority] ?? 3) - (PRIORITY_RANK[b.priority] ?? 3);
  for (const q of QUADRANTS) quadrants[q].sort(order);
  return quadrants;
}

/** Markdown escaping for task titles (titles are user text). */
export const md = (s) =>
  String(s ?? "")
    .replace(/[\u0000-\u001f\u007f]/g, " ")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/[\\`*_[\]|]/g, (c) => `\\${c}`);

export const describeTask = (t) => {
  const bits = [];
  if (t.due) bits.push(`due ${t.due}`);
  if (t.priority) bits.push(`priority ${t.priority}`);
  if (t.effort_minutes) bits.push(`${t.effort_minutes} min`);
  return `${md(t.title)}${bits.length ? ` (${bits.join(", ")})` : ""}`;
};

export const PRIORITY_ORDER = PRIORITY_RANK;

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).