// @bun
import {
  getAutoMemPath,
  init_paths
} from "./chunk-7rrkrej7.js";
import {
  init_debug,
  logForDebugging
} from "./chunk-byd20vdq.js";
import {
  __esm
} from "./chunk-hhsxm2yr.js";

// src/memdir/checkpoint.ts
import { readFile, writeFile, stat } from "fs/promises";
import { join } from "path";
function parseTasksMd(content) {
  const lines = content.split(`
`).filter((l) => l.trim());
  const roots = [];
  const stack = [];
  for (const line of lines) {
    const m = line.match(/^(\s*)- \[(.)\] (\S+):?\s+(.*)$/);
    if (!m)
      continue;
    const indent = m[1].length;
    const statusChar = m[2];
    const id = m[3];
    const title = m[4].trim();
    const status = statusChar === "x" ? "completed" : statusChar === "-" ? "blocked" : statusChar === "~" ? "in_progress" : "pending";
    const node = { id, title, status, children: [] };
    while (stack.length > 0 && stack[stack.length - 1].indent >= indent) {
      stack.pop();
    }
    if (stack.length === 0) {
      roots.push(node);
    } else {
      stack[stack.length - 1].node.children.push(node);
    }
    stack.push({ node, indent });
  }
  return roots;
}
function serializeTasksMd(tasks) {
  const lines = [
    "# Task Progress",
    "",
    "_Auto-managed task tree. Do not edit manually._",
    ""
  ];
  function renderNode(node, depth) {
    const indent = "  ".repeat(depth);
    const checkbox = node.status === "completed" ? "x" : node.status === "blocked" ? "-" : node.status === "in_progress" ? "~" : " ";
    lines.push(`${indent}- [${checkbox}] ${node.id}: ${node.title}`);
    for (const child of node.children) {
      renderNode(child, depth + 1);
    }
  }
  for (const task of tasks) {
    renderNode(task, 0);
  }
  return lines.join(`
`) + `
`;
}
function updateTaskStatus(tasks, taskId, status) {
  for (const task of tasks) {
    if (task.id === taskId) {
      task.status = status;
      return true;
    }
    if (updateTaskStatus(task.children, taskId, status)) {
      return true;
    }
  }
  return false;
}
function addTask(tasks, parentId, id, title) {
  if (!parentId) {
    tasks.push({ id, title, status: "pending", children: [] });
    return true;
  }
  for (const task of tasks) {
    if (task.id === parentId) {
      task.children.push({ id, title, status: "pending", children: [] });
      return true;
    }
    if (addTask(task.children, parentId, id, title)) {
      return true;
    }
  }
  return false;
}
function parseCheckpoint(content) {
  const sections = {};
  let currentSection = "";
  let currentContent = [];
  for (const line of content.split(`
`)) {
    const headerMatch = line.match(/^## (.+)$/);
    if (headerMatch) {
      if (currentSection) {
        sections[currentSection] = currentContent.join(`
`).trim();
      }
      currentSection = headerMatch[1].toLowerCase();
      currentContent = [];
    } else {
      currentContent.push(line);
    }
  }
  if (currentSection) {
    sections[currentSection] = currentContent.join(`
`).trim();
  }
  return {
    title: sections["session"] || "",
    currentState: sections["current state"] || "",
    keyFiles: (sections["key files"] || "").split(`
`).filter((l) => l.startsWith("- ")).map((l) => l.slice(2)),
    recentErrors: sections["recent errors"] || "",
    nextSteps: sections["next steps"] || "",
    taskSummary: sections["task progress"] || "",
    timestamp: sections["updated"] || ""
  };
}
function serializeCheckpoint(data) {
  return `# Session Checkpoint

_Auto-generated checkpoint for session resumption._

## Session
${data.title}

## Updated
${data.timestamp}

## Current State
${data.currentState}

## Key Files
${data.keyFiles.map((f) => `- ${f}`).join(`
`) || "- _(none yet)_"}

## Recent Errors
${data.recentErrors || "- _(none)_"}

## Next Steps
${data.nextSteps || "- _(none specified)_"}

## Task Progress
${data.taskSummary || "- _(no tasks tracked)_"}
`;
}
function getCheckpointPath() {
  return join(getAutoMemPath(), CHECKPOINT_FILENAME);
}
function getTasksPath() {
  return join(getAutoMemPath(), TASKS_FILENAME);
}
async function loadCheckpoint() {
  try {
    const content = await readFile(getCheckpointPath(), "utf-8");
    return parseCheckpoint(content);
  } catch {
    return null;
  }
}
async function saveCheckpoint(data) {
  try {
    await writeFile(getCheckpointPath(), serializeCheckpoint(data), "utf-8");
    logForDebugging("checkpoint: saved", { level: "debug" });
  } catch (e) {
    logForDebugging(`checkpoint: save failed: ${String(e)}`, { level: "warn" });
  }
}
async function loadTasks() {
  try {
    const content = await readFile(getTasksPath(), "utf-8");
    return parseTasksMd(content);
  } catch {
    return [];
  }
}
async function saveTasks(tasks) {
  try {
    await writeFile(getTasksPath(), serializeTasksMd(tasks), "utf-8");
    logForDebugging("checkpoint: tasks saved", { level: "debug" });
  } catch (e) {
    logForDebugging(`checkpoint: tasks save failed: ${String(e)}`, {
      level: "warn"
    });
  }
}
async function buildCheckpointContext() {
  const checkpoint = await loadCheckpoint();
  if (!checkpoint || !checkpoint.title)
    return null;
  const tasks = await loadTasks();
  const taskLines = tasks.length > 0 ? serializeTasksMd(tasks).split(`
`).slice(4).join(`
`) : "";
  const parts = [`## Session Resumption Context`];
  parts.push("");
  if (checkpoint.title)
    parts.push(`**Previous session:** ${checkpoint.title}`);
  if (checkpoint.currentState)
    parts.push(`**State:** ${checkpoint.currentState}`);
  if (checkpoint.keyFiles?.length)
    parts.push(`**Key files:** ${checkpoint.keyFiles.join(", ")}`);
  if (checkpoint.nextSteps)
    parts.push(`**Next steps:** ${checkpoint.nextSteps}`);
  if (taskLines.trim()) {
    parts.push("");
    parts.push("**Task progress:**");
    parts.push(taskLines);
  }
  return parts.join(`
`);
}
var CHECKPOINT_FILENAME = "checkpoint.md", TASKS_FILENAME = "tasks.md";
var init_checkpoint = __esm(() => {
  init_debug();
  init_paths();
});

export { updateTaskStatus, addTask, saveCheckpoint, loadTasks, saveTasks, buildCheckpointContext, init_checkpoint };

//# debugId=4905306C24B1A8BB64756E2164756E21
//# sourceMappingURL=chunk-n8kbhswc.js.map
