> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch42-hands-on-project/42.4-advanced-features.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 42.4 Advanced Features

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~365k tokens, Output \~5k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

After building the basic skeleton, this section adds three advanced features to MiniClaw: memory system, skill system, and Cron scheduling. These features reference OpenClaw's corresponding implementations (Chapters 20-22) but are significantly simplified.

## 42.4.1 Adding Memory System (Vector Search)

### Markdown Memory

OpenClaw's memory system is based on the philosophy of "pure Markdown as memory" (Chapter 28). MiniClaw adopts the same approach:

```typescript
// src/memory/markdown.ts

import fs from "node:fs";
import path from "node:path";

const MEMORY_DIR = path.join(process.cwd(), ".miniclaw", "memory");

export class MarkdownMemory {
  constructor() {
    fs.mkdirSync(MEMORY_DIR, { recursive: true });
  }

  // Save long-term memory
  save(key: string, content: string) {
    const filePath = path.join(MEMORY_DIR, `${key}.md`);
    fs.writeFileSync(filePath, content, "utf-8");
  }

  // Append log memory
  appendLog(content: string) {
    const date = new Date().toISOString().split("T")[0];
    const filePath = path.join(MEMORY_DIR, `${date}.md`);
    const entry = `\n## ${new Date().toLocaleTimeString()}\n\n${content}\n`;
    fs.appendFileSync(filePath, entry, "utf-8");
  }

  // Load all memories as context
  loadAll(): string {
    const files = fs.readdirSync(MEMORY_DIR)
      .filter(f => f.endsWith(".md"))
      .sort();
    const contents = files.map(f => {
      const content = fs.readFileSync(path.join(MEMORY_DIR, f), "utf-8");
      return `# ${f}\n${content}`;
    });
    return contents.join("\n\n---\n\n");
  }
}
```

### Memory Tools

Expose memory operations as tools callable by the Agent:

```typescript
// src/agent/tools/memory.ts

export function createMemoryTools(memory: MarkdownMemory): ToolExecutor[] {
  return [
    {
      name: "memory_save",
      definition: {
        name: "memory_save",
        description: "Save information to long-term memory.",
        input_schema: {
          type: "object",
          properties: {
            key: { type: "string", description: "Memory key (filename)" },
            content: { type: "string", description: "Content to save" },
          },
          required: ["key", "content"],
        },
      },
      execute: async (input) => {
        memory.save(input.key as string, input.content as string);
        return `Saved to memory: ${input.key}`;
      },
    },
    {
      name: "memory_search",
      definition: {
        name: "memory_search",
        description: "Search through saved memories.",
        input_schema: {
          type: "object",
          properties: {
            query: { type: "string", description: "Search query" },
          },
          required: ["query"],
        },
      },
      execute: async (input) => {
        const all = memory.loadAll();
        // Simple keyword search (production should use vector search)
        const query = (input.query as string).toLowerCase();
        const lines = all.split("\n");
        const matches = lines.filter(line =>
          line.toLowerCase().includes(query)
        );
        return matches.length > 0
          ? matches.slice(0, 20).join("\n")
          : "No matches found.";
      },
    },
  ];
}
```

### Vector Search Enhancement (Optional)

For scenarios requiring semantic search, you can integrate embedding vectors:

```typescript
// src/memory/vector.ts (optional enhancement)

import { OpenAI } from "openai";

export class VectorMemory {
  private openai: OpenAI;
  private vectors: Array<{ text: string; embedding: number[] }> = [];

  constructor(apiKey: string) {
    this.openai = new OpenAI({ apiKey });
  }

  async index(text: string) {
    const response = await this.openai.embeddings.create({
      model: "text-embedding-3-small",
      input: text,
    });
    this.vectors.push({
      text,
      embedding: response.data[0].embedding,
    });
  }

  async search(query: string, topK = 5) {
    const qEmbed = await this.embed(query);
    // Sort by cosine similarity
    const scored = this.vectors.map(v => ({
      text: v.text,
      score: cosineSimilarity(qEmbed, v.embedding),
    }));
    scored.sort((a, b) => b.score - a.score);
    return scored.slice(0, topK);
  }
}

function cosineSimilarity(a: number[], b: number[]): number {
  let dot = 0, normA = 0, normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
```

## 42.4.2 Adding Skill System

OpenClaw's skill system (Chapter 29) allows dynamic loading of capability modules. MiniClaw implements a simplified version:

```typescript
// src/skills/loader.ts

import fs from "node:fs";
import path from "node:path";

export type Skill = {
  name: string;
  description: string;
  systemPrompt: string;  // Additional instructions injected into Agent
};

const SKILLS_DIR = path.join(process.cwd(), ".miniclaw", "skills");

export function loadSkills(): Skill[] {
  if (!fs.existsSync(SKILLS_DIR)) return [];

  const skills: Skill[] = [];
  const dirs = fs.readdirSync(SKILLS_DIR, { withFileTypes: true })
    .filter(d => d.isDirectory());

  for (const dir of dirs) {
    const skillFile = path.join(SKILLS_DIR, dir.name, "SKILL.md");
    if (!fs.existsSync(skillFile)) continue;

    const content = fs.readFileSync(skillFile, "utf-8");
    skills.push({
      name: dir.name,
      description: extractDescription(content),
      systemPrompt: content,
    });
  }
  return skills;
}

function extractDescription(markdown: string): string {
  const firstLine = markdown.split("\n").find(l => l.trim() && !l.startsWith("#"));
  return firstLine?.trim() ?? "";
}
```

Skill file format is compatible with OpenClaw's `SKILL.md`:

```markdown
<!-- .miniclaw/skills/coding/SKILL.md -->
# Coding Assistant

You are an expert programmer. Follow these rules:

1. Write clean, well-documented code
2. Use TypeScript best practices
3. Always handle errors properly
4. Prefer functional programming patterns
```

After loading, skills are concatenated into the Agent's system prompt:

```typescript
const skills = loadSkills();
const skillsPrompt = skills.map(s => s.systemPrompt).join("\n\n---\n\n");
const systemPrompt = `You are a helpful AI assistant.\n\n${skillsPrompt}`;
```

## 42.4.3 Adding Cron Scheduling

Referencing OpenClaw's Cron system (Chapter 26), implement a simple scheduled task scheduler:

```typescript
// src/cron/scheduler.ts

import { CronJob } from "cron";  // Use cron library

export type CronTask = {
  id: string;
  expression: string;  // Cron expression
  prompt: string;       // Message to send to Agent
  sessionKey: string;   // Target session
  enabled: boolean;
};

export class CronScheduler {
  private tasks = new Map<string, CronTask>();
  private jobs = new Map<string, CronJob>();
  private sendMessage: (sessionKey: string, message: string) => Promise<void>;

  constructor(sendMessage: (sessionKey: string, message: string) => Promise<void>) {
    this.sendMessage = sendMessage;
  }

  addTask(task: CronTask) {
    this.tasks.set(task.id, task);
    if (task.enabled) {
      this.startJob(task);
    }
  }

  private startJob(task: CronTask) {
    const job = new CronJob(task.expression, async () => {
      console.log(`[cron] Running task: ${task.id}`);
      try {
        await this.sendMessage(
          task.sessionKey,
          `[Scheduled task: ${task.id}] ${task.prompt}`
        );
      } catch (err) {
        console.error(`[cron] Task ${task.id} failed:`, err);
      }
    });
    job.start();
    this.jobs.set(task.id, job);
  }

  removeTask(id: string) {
    this.jobs.get(id)?.stop();
    this.jobs.delete(id);
    this.tasks.delete(id);
  }

  listTasks(): CronTask[] {
    return Array.from(this.tasks.values());
  }
}
```

Configuration file-driven scheduled tasks:

```jsonc
// .miniclaw/cron.json
{
  "tasks": [
    {
      "id": "daily-summary",
      "expression": "0 9 * * *",
      "prompt": "Please summarize today's schedule and to-do items",
      "sessionKey": "telegram:123456",
      "enabled": true
    },
    {
      "id": "weather-check",
      "expression": "0 7 * * 1-5",
      "prompt": "Check today's weather forecast",
      "sessionKey": "webchat:default",
      "enabled": true
    }
  ]
}
```

### Cron Tool

Allow the Agent to create scheduled tasks itself:

```typescript
export const cronTool: ToolExecutor = {
  name: "cron_create",
  definition: {
    name: "cron_create",
    description: "Create a scheduled task that runs at specified times.",
    input_schema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Unique task ID" },
        expression: { type: "string", description: "Cron expression (e.g. '0 9 * * *')" },
        prompt: { type: "string", description: "Message to process when triggered" },
      },
      required: ["id", "expression", "prompt"],
    },
  },
  execute: async (input) => {
    scheduler.addTask({
      id: input.id as string,
      expression: input.expression as string,
      prompt: input.prompt as string,
      sessionKey: "global",
      enabled: true,
    });
    return `Created cron task: ${input.id} (${input.expression})`;
  },
};
```

***

## Summary of This Section

1. **Markdown memory** stores long-term memory and logs on a per-file basis, retrieved through keyword search.
2. **Vector search enhancement** optionally integrates OpenAI Embeddings for semantic-level memory retrieval.
3. **Skill system** defines additional capabilities through `SKILL.md` files, dynamically loaded and concatenated into the system prompt.
4. **Cron scheduling** uses the `cron` library to implement scheduled tasks, supporting both configuration file and Agent tool creation methods.
5. All advanced features follow the "optional enhancement" principle—core functionality doesn't depend on them, but adding them significantly improves the assistant's practicality.
