# How the Lemon AI Planning Module Coordinates Multi-Step Agent Tasks

> Discover how the Lemon AI planning module coordinates multi-step agent tasks. Learn its three-stage pipeline for goal conversion to executable action lists within the hexdocom/lemonai repository.

- Repository: [hexdocom/lemonai](https://github.com/hexdocom/lemonai)
- Tags: deep-dive
- Published: 2026-03-03

---

**The Lemon AI planning module converts high-level user goals into executable task lists through a three-stage pipeline: context-aware prompt construction in [`src/agent/prompt/plan.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/prompt/plan.js), LLM invocation with retry logic and markdown parsing in [`src/agent/planning/index.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/planning/index.js), and task registration via the TaskManager, which materializes a [`todo.md`](https://github.com/hexdocom/lemonai/blob/main/todo.md) file to drive execution loops.**

The planning component in the [hexdocom/lemonai](https://github.com/hexdocom/lemonai) repository serves as the orchestration layer that transforms abstract user objectives into deterministic workflows. By integrating multi-source context aggregation, resilient LLM interaction patterns, and structured task handoff mechanisms, this module ensures that agent tasks proceed sequentially from planning through completion.

## Prompt Construction and Context Aggregation

The coordination pipeline begins in [`src/agent/prompt/plan.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/prompt/plan.js), where the `resolvePlanningPrompt` function gathers execution context from multiple sources to build a comprehensive planning prompt.

### Aggregating Multi-Source Context

The function collects **uploaded files**, **previous conversation summaries**, and **best-practice knowledge** specific to the current agent to ground the planning request:

```javascript
const resolvePlanningPrompt = async (goal, options) => {
  const { files, previousResult, agent_id, planning_mode } = options;
  const templateFilename = resolveTemplateFilename(planning_mode);
  const promptTemplate = await loadTemplate(templateFilename);
  const system = `Current Time: ${new Date().toLocaleString()}`;
  const uploadFileDescription = describeUploadFiles(files);
  const best_practice_knowledge = await resolvePlanningKnowledge({ agent_id });

  const prompt = await resolveTemplate(promptTemplate, {
    goal,
    files: uploadFileDescription,
    previous: previousResult,
    system,
    experiencePrompt: '',
    best_practice_knowledge,
  });
  return prompt;
};

```

*Source:* [[`src/agent/prompt/plan.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/prompt/plan.js)](https://github.com/hexdocom/lemonai/blob/main/src/agent/prompt/plan.js)

### Template Selection and Rendering

The module dynamically selects templates based on the `planning_mode` parameter (defaulting to [`planning.txt`](https://github.com/hexdocom/lemonai/blob/main/planning.txt)) using `resolveTemplateFilename`. The `resolveTemplate` function then interpolates placeholders—such as `goal`, `files`, `previous`, and `best_practice_knowledge`—to produce a single prompt string ready for LLM consumption.

## LLM Invocation and Robust Parsing

The `planning_local` function in [`src/agent/planning/index.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/planning/index.js) manages the actual generation and conversion of unstructured LLM responses into executable task structures.

### Retry Logic and Error Handling

The implementation incorporates **robust parsing mechanisms** that validate LLM output format. When the model returns markdown that doesn't conform to the expected task structure, the system retries the request to ensure reliable extraction.

### Markdown-to-Task Conversion

After successful generation, the pipeline converts the markdown response into a **structured task array**. This transformation bridges the gap between natural language planning and programmatic execution, producing a clean list of tasks that the agent can iterate through.

```javascript
const planning_local = async (goal, options = {}) => {
  const { conversation_id } = options;
  const prompt = await resolvePlanningPromptBP(goal, options);
  
  // LLM invocation with retry logic for format validation
  // ...
  // Returns structured task array from markdown parsing
};

```

*Source:* [[`src/agent/planning/index.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/planning/index.js)](https://github.com/hexdocom/lemonai/blob/main/src/agent/planning/index.js)

## Task Registration and Execution Handoff

Once the task list is structured, the **AgenticAgent** class assumes control of the execution workflow. The module stores the validated tasks internally, publishes a `plan` message to signal downstream components, and materializes a physical [`todo.md`](https://github.com/hexdocom/lemonai/blob/main/todo.md) file that serves as the canonical execution checklist.

The **TaskManager** consumes this structured list to coordinate subsequent execution loops, ensuring each planned step is tracked and completed according to the generated sequence. This materialization strategy creates a transparent audit trail while enabling the agent to resume or modify workflows based on runtime feedback.

## Summary

- The **planning module** in Lemon AI operates through three distinct phases: context aggregation, LLM generation with retry logic, and structured task registration.
- **Prompt construction** in [`src/agent/prompt/plan.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/prompt/plan.js) leverages `resolvePlanningPrompt` to combine file descriptions, conversation history, and best-practice knowledge into a single templated prompt.
- **Robust parsing** in [`src/agent/planning/index.js`](https://github.com/hexdocom/lemonai/blob/main/src/agent/planning/index.js) handles markdown-to-task conversion, with automatic retries for malformed LLM responses to ensure reliable task extraction.
- The system materializes a ** [`todo.md`](https://github.com/hexdocom/lemonai/blob/main/todo.md) ** file and publishes `plan` messages to enable deterministic execution tracking via the TaskManager.

## Frequently Asked Questions

### What is the role of `planning_mode` in the Lemon AI planning module?

The `planning_mode` parameter determines which template file the system selects via `resolveTemplateFilename`. By default, it resolves to [`planning.txt`](https://github.com/hexdocom/lemonai/blob/main/planning.txt), but different modes allow the agent to adapt its planning strategy for specific workflow types, such as reactive planning or multi-agent coordination scenarios.

### How does the planning module handle LLM response errors?

The `planning_local` function implements **retry logic** that triggers when the LLM returns markdown that cannot be parsed into the expected task structure. This resilience mechanism ensures that transient formatting errors or model hallucinations don't corrupt the execution pipeline, requesting regenerated responses until valid structured data is obtained.

### What is the purpose of [`todo.md`](https://github.com/hexdocom/lemonai/blob/main/todo.md) in the execution workflow?

The [`todo.md`](https://github.com/hexdocom/lemonai/blob/main/todo.md) file serves as a **materialized execution checklist** that persists the structured task list to disk. This approach creates a transparent audit trail for debugging, allows the agent to resume workflows after interruptions, and provides human operators with visibility into the agent's planned execution path.

### How does `best_practice_knowledge` influence task planning?

The `best_practice_knowledge` variable injects domain-specific guidance retrieved via `resolvePlanningKnowledge` based on the `agent_id`. This contextual memory ensures that generated task sequences incorporate learned patterns from previous executions, organizational standards, or agent-specific heuristics to improve planning quality and reduce repetitive errors.