Skip to content

lua-ai-global/lua-mesh-demo

Repository files navigation

🤖 Mesh Financial & Operational Coach

A comprehensive AI-powered financial coaching system built with HeyLua that guides small business owners through 5 levels of financial maturity—from basic compliance to strategic mastery.

📖 Table of Contents


Overview

What Is This?

The Mesh Financial Coach is an intelligent agent that:

  • ✅ Assesses users' current financial practices (one-time evaluation)
  • ✅ Assigns them to 1 of 5 maturity levels
  • ✅ Guides them through 3 modules per level
  • ✅ Tracks progress and automatically levels them up
  • ✅ Sends personalized reminders based on their journey
  • ✅ Grounds all advice in educational principles (never gives specific investment advice)

The "Cautious Mentor" Persona

The agent embodies the Cautious Mentor philosophy:

NEVER:

  • ❌ Give specific investment advice ("Buy this stock")
  • ❌ Make purchasing decisions ("You should buy this equipment")
  • ❌ Guarantee financial outcomes ("Do this and you'll make $X")

ALWAYS:

  • ✅ Educate on principles (separation, tracking, forecasting)
  • ✅ Ask guiding questions ("What's your target gross margin?")
  • ✅ Empower users to make their own informed decisions

The 5-Level System

Level 1: The Financial Starter

Goal: Basic compliance and habit formation

Modules:

  1. The Separation Rule - Open separate business bank account
  2. Digital Capture Setup - Implement digital expense tracking
  3. 5-Receipt Challenge - Capture 5 receipts in one week

Key Concepts: Personal vs. business accounts, digital capture, basic categories (Revenue, Costs, Transfers)


Level 2: The Tracker

Goal: Consistent data capture and monthly review cycles

Modules:

  1. Monthly Filing Cycle - Complete first full monthly reconciliation
  2. Revenue Stream Definition - Identify and name 3 primary revenue sources
  3. Fixed Cost Budgeting - Calculate monthly survival number

Key Concepts: Monthly reconciliation, revenue stream visibility, fixed vs. variable costs


Level 3: The Planner

Goal: Forecasting and forward planning

Modules:

  1. P&L Mastery - Understand Net P&L vs. bank balance
  2. Proactive Tax Savings - Set up 30% tax savings system
  3. Forecast Initiation - Create first 3-month cash flow forecast

Key Concepts: P&L vs. bank balance, quarterly tax savings, rolling cash flow forecasts


Level 4: The Scaler

Goal: Strategic growth and investment

Modules:

  1. Reinvestment Strategy - Define profit allocation (Tax/Owner/Reinvest)
  2. Delegation & Automation - Identify first task to delegate
  3. COGS Calculation - Separate Cost of Goods Sold from Operating Expenses

Key Concepts: Strategic reinvestment, time value, gross margin, COGS vs. OpEx


Level 5: The Master

Goal: Optimization and long-term resilience

Modules:

  1. Building Cash Reserves - Establish 6-month operating reserve
  2. Quarterly Review Cycle - Complete strategic quarterly review
  3. Mentorship Simulation - Demonstrate Cautious Mentor approach

Key Concepts: Cash reserves, quarterly reviews, teaching others


Quick Start

Prerequisites

node >= 20.x
npm >= 9.x

Installation

# Install dependencies
npm install

# Build TypeScript
npm run build

Data Loading (Optional but Recommended)

Load full RAG educational content to the Data Primitive:

npm run load-data

Note: The agent works without this step (using embedded metadata), but full content provides richer guidance.

Testing Locally

# Test tools individually
lua test

# Chat with agent in sandbox mode
lua chat

Deployment

# Compile for deployment
lua compile

# Push all components and deploy
lua push all --force --auto-deploy

Agent Architecture

Core Components

┌─────────────────────────────────────────────────┐
│         Mesh Financial Coach Agent              │
│           (Cautious Mentor Persona)             │
└─────────────────────────────────────────────────┘
                        │
        ┌───────────────┴───────────────┐
        ↓                               ↓
┌───────────────────┐         ┌──────────────────┐
│ Financial Coach   │         │  Dynamic Jobs    │
│      Skill        │         │  (Per-User)      │
└───────────────────┘         └──────────────────┘
        │
        ├── MaturityAssessmentTool
        ├── CompleteModuleTool
        ├── CheckLevelProgressTool
        └── GetLevelContentTool

Data Flow

  1. User starts → Agent calls check_level_progress
  2. New user? → Run run_maturity_assessment (one-time)
  3. Progress tracking → Use complete_module when user demonstrates competency
  4. Content retrieval → Use get_level_content to ground responses
  5. Proactive pings → Jobs created dynamically after assessment/completion

Directory Structure

mesh-financial-coach/
│
├── src/
│   ├── index.ts                    # Main agent configuration
│   │
│   ├── data/                       # RAG educational content
│   │   ├── rag_level1.md          # Level 1 full content
│   │   ├── rag_level2.md          # Level 2 full content
│   │   ├── rag_level3.md          # Level 3 full content
│   │   ├── rag_level4.md          # Level 4 full content
│   │   ├── rag_level5.md          # Level 5 full content
│   │   └── levelContentMap.ts     # Metadata (compiled with agent)
│   │
│   ├── skills/
│   │   ├── financial-coach.skill.ts   # Main coaching skill
│   │   └── tools/
│   │       └── FinancialCoachTools.ts # All 4 coaching tools
│   │
│   └── utils/
│       └── loadRAGContent.ts       # Data loading utility (setup only)
│
├── scripts/
│   └── loadData.ts                 # CLI script to load RAG content
│
├── lua.skill.yaml                  # Skill registry and configuration
├── package.json                    # Dependencies and scripts
└── README.md                       # This file

Key Files

File Purpose When Used
src/index.ts Agent definition with persona Always (core)
src/skills/financial-coach.skill.ts Groups coaching tools Always (core)
src/skills/tools/FinancialCoachTools.ts All 4 coaching tools Always (core)
src/data/levelContentMap.ts Embedded metadata (fallback) Always (compiled in)
src/data/rag_level*.md Full educational content Optional (for Data Primitive)
src/utils/loadRAGContent.ts Loads markdown to Data Primitive Setup only
scripts/loadData.ts CLI wrapper for data loading Setup only

Skills & Tools

Financial Coach Skill

Name: financial-coach-skill
Version: 1.0.0
Purpose: Provides all tools needed to assess, track, and coach users through financial maturity levels

Tools (4 total)


1. MaturityAssessmentTool

Tool Name: run_maturity_assessment

Purpose: Evaluates user's current financial practices through 5 questions and assigns them to a starting level (1-5).

Input Schema:

{
  q1_score: number (1-5),  // Separate business account?
  q2_score: number (1-5),  // Capture expenses digitally?
  q3_score: number (1-5),  // Review finances regularly?
  q4_score: number (1-5),  // Forecast/plan for taxes?
  q5_score: number (1-5)   // Systems for growth?
}

Scoring Logic:

  • 5-8 points → Level 1 (Financial Starter)
  • 9-12 points → Level 2 (Tracker)
  • 13-16 points → Level 3 (Planner)
  • 17-20 points → Level 4 (Scaler)
  • 21-25 points → Level 5 (Master)

What It Does:

  1. Calculates total score
  2. Assigns appropriate level
  3. Initializes habit_tracking (all modules marked incomplete)
  4. Saves to User Primitive
  5. Creates first proactive ping job (7 days out)

Output:

{
  success: true,
  total_score: 8,
  assigned_level: 1,
  level_name: "The Financial Starter",
  level_description: "Focus on basic compliance...",
  message: "Assessment complete! You've been assigned...",
  next_steps: "Start with Module 1...",
  ping_scheduled: "Habit check scheduled for Nov 14, 2025"
}

Important: This should only run ONCE per user. Always check check_level_progress first.


2. CompleteModuleTool

Tool Name: complete_module

Purpose: Marks a module as complete after user demonstrates competency, checks for level-up, and creates next reminder job.

Input Schema:

{
  level: number (1-5),                         // Which level
  module: number (1-3),                        // Which module
  verification_method: "quiz" | "action_confirmation" | "user_input",
  verification_details: string                 // What user provided
}

Verification Methods:

  • quiz: User answered a knowledge question correctly
  • action_confirmation: User confirmed completing an action
  • user_input: User provided required information

What It Does:

  1. Validates module is for current level or below
  2. Marks module as complete in habit_tracking
  3. Checks if all 3 modules in level are complete
  4. If complete → Level up! Initialize next level's modules
  5. Creates dynamic job for next milestone (7 days out)
  6. Updates User Primitive

Output (Level Up):

{
  success: true,
  module_completed: "Level 1, Module 3",
  verification_method: "action_confirmation",
  all_modules_complete: true,
  leveled_up: true,
  new_level: 2,
  new_level_name: "The Tracker",
  message: "🎉 Congratulations! You've completed all modules..."
}

Output (Module Complete, Not Level Up):

{
  success: true,
  module_completed: "Level 2, Module 1",
  verification_method: "quiz",
  all_modules_complete: false,
  leveled_up: false,
  new_level: 2,
  message: "Module 1 of Level 2 marked complete! Continue with..."
}

Dynamic Job Creation:

  • After module completion → Job for next module
  • After level-up → Job for new level's Module 1
  • All jobs scheduled for 7 days in the future

3. CheckLevelProgressTool

Tool Name: check_level_progress

Purpose: Retrieves user's current level, progress, and module completion status. Call this FIRST at the start of every conversation.

Input Schema:

{
  include_details: boolean (optional, default: true)  // Include all module details?
}

What It Does:

  1. Fetches user's state from User Primitive
  2. Checks if they've been assessed
  3. Calculates progress percentage
  4. Returns detailed module status

Output (Assessed User):

{
  success: true,
  assessed: true,
  current_level: 2,
  level_name: "The Tracker",
  current_level_progress: {
    completed_modules: 1,
    total_modules: 3,
    progress_percentage: 33,
    modules: [
      { module: 1, completed: true },
      { module: 2, completed: false },
      { module: 3, completed: false }
    ]
  },
  all_modules: {
    level_1: [...],
    level_2: [...]
  },
  assessment_date: "2025-11-07T10:00:00Z",
  last_module_completed: "2025-11-08T14:30:00Z",
  ready_for_level_up: false,
  message: "User is at Level 2: The Tracker. Progress: 1/3 modules..."
}

Output (Not Assessed):

{
  success: true,
  assessed: false,
  message: "User has not yet completed the maturity assessment...",
  recommendation: "Use run_maturity_assessment tool..."
}

Critical: This is the FIRST tool to call in every conversation to avoid re-assessing users.


4. GetLevelContentTool

Tool Name: get_level_content

Purpose: Retrieves educational content for a specific level to ground AI responses in the curriculum.

Input Schema:

{
  level: number (1-5)  // Which level's content to retrieve
}

How It Works:

  1. Try Data Primitive first (if npm run load-data was executed)
  2. Fallback to embedded metadata (always available, compiled with agent)

Output (Full Content - Data Primitive):

{
  success: true,
  level: 2,
  levelName: "The Tracker",
  description: "Consistent tracking, monthly reviews...",
  content: "# Level 2: The Tracker\n\n[Full markdown content]...",
  contentLength: 12543,
  source: "data_primitive",
  message: "Retrieved full educational content for Level 2..."
}

Output (Metadata Fallback):

{
  success: true,
  level: 2,
  levelName: "The Tracker",
  description: "Consistent tracking, monthly reviews...",
  modules: [
    { module: 1, name: "Monthly Filing Cycle", focus: "..." },
    { module: 2, name: "Revenue Stream Definition", focus: "..." },
    { module: 3, name: "Fixed Cost Budgeting", focus: "..." }
  ],
  source: "embedded_metadata",
  content_summary: "Level 2: The Tracker\n\nModules:\n...",
  message: "Retrieved metadata for Level 2...",
  note: "Using embedded metadata. For full content, run npm run load-data"
}

Use Case: Agent calls this to understand what to teach at each level and ground responses in curriculum.


How It Works

User Journey Example

Day 0: Sarah Starts

Sarah: "Hi, I need help with my business finances."
Agent: [Calls check_level_progress] → Not assessed
Agent: "Let me understand your current situation with 5 quick questions..."
Sarah: [Answers 5 questions]
Agent: [Calls run_maturity_assessment with scores]
Result: Sarah assigned Level 1 (Financial Starter)
Action: Job created for Day 7

Day 3: Sarah Completes Module 1

Sarah: "I opened my business bank account!"
Agent: [Calls complete_module(level: 1, module: 1, method: "action_confirmation")]
Result: Module 1 marked complete
Action: Job created for Day 10 (Module 2 reminder)

Day 7: First Job Fires

Job: Checks Sarah's progress
      → Module 1 already complete!
      → Sends: "✅ Well done! You've already completed this module..."
(Smart: Job detected completion and sent encouragement instead of redundant reminder)

Day 10: Sarah Completes Module 2

Sarah: "I set up my expense tracker in QuickBooks."
Agent: [Calls complete_module(level: 1, module: 2, method: "action_confirmation")]
Result: Module 2 marked complete
Action: Job created for Day 17 (Module 3 reminder)

Day 15: Sarah Completes Module 3 (Final in Level 1)

Sarah: "I captured 7 receipts this week!"
Agent: [Calls complete_module(level: 1, module: 3, method: "action_confirmation")]
Result: All Level 1 modules complete → LEVEL UP!
New Level: Level 2 (The Tracker)
Action: Job created for Day 22 (Level 2, Module 1 reminder)

Day 22: Level 2 Job Fires

Job: Sends "🎯 The Tracker - Time to Start! You leveled up a week ago. Ready to dive into Module 1?"

Key Behaviors

  1. One-Time Assessment: Assessment never runs twice (checked via check_level_progress)
  2. Dynamic Jobs: Each action creates the next reminder (7 days out)
  3. Smart Job Execution: Jobs check actual progress before sending messages
  4. Automatic Level-Up: Completing all 3 modules triggers level advancement
  5. Personalized Timing: Jobs based on THEIR actions, not global schedule
  6. Graceful Fallback: Agent works even if Data Primitive content not loaded

Smart Job Execution Logic

When a job fires, it doesn't blindly send a reminder. Instead, it:

  1. Checks user's current state (level, module completion)
  2. Detects if module is already complete or if user has leveled up
  3. Adapts the message based on actual progress:
    • Module incomplete → Send original reminder
    • Module complete → Send encouragement
    • User leveled up → Congratulate progress
    • All modules complete → Suggest level-up conversation

This prevents redundant reminders and keeps messages relevant!


Deployment

Pre-Deployment Checklist

  • Code compiles: npm run build
  • (Optional) Load RAG content: npm run load-data
  • Test locally: lua chat (sandbox)
  • Verify tools work: Test assessment and module completion

Deploy Steps

# 1. Compile TypeScript
npm run build

# 2. Compile for Lua platform
lua compile

# 3. Push all components
lua push all --force --auto-deploy

Verify Deployment

# Check production status
lua production

# Test in production
lua chat  # Select Production mode

Key Features

✅ Smart Assessment

  • One-time evaluation (never repeats)
  • 5 questions covering all financial areas
  • Automatic level assignment (1-5)
  • Saved permanently to user profile

✅ Progress Tracking

  • 15 total modules (5 levels × 3 modules each)
  • Three verification types: quiz, action, input
  • Automatic level-up when all modules complete
  • Real-time progress calculation

✅ Dynamic Reminders

  • Jobs created per user, per action
  • 7-day spacing between action and reminder
  • Context-aware messages (knows which module)
  • No global cron jobs (scales infinitely)

✅ Educational Grounding

  • Full RAG content available (optional)
  • Embedded metadata (always works)
  • Fallback mechanism (never fails)
  • Cautious Mentor philosophy (educate, don't prescribe)

✅ Production-Ready

  • TypeScript for type safety
  • Zod schemas for input validation
  • Error handling throughout
  • No file system access at runtime

Development

Adding a New Level

  1. Create src/data/rag_level6.md with content
  2. Update src/data/levelContentMap.ts:
    6: {
      level: 6,
      levelName: "The Expert",
      description: "...",
      modules: [...]
    }
  3. Update tool schemas to accept level 6
  4. Run npm run load-data (if using Data Primitive)

Modifying Module Verification

Edit the module messages in CompleteModuleTool or add new verification logic as needed.

Adjusting Reminder Timing

Change the 7-day interval in MaturityAssessmentTool and CompleteModuleTool:

nextPingDate.setDate(nextPingDate.getDate() + 7);  // Change this number

Architecture Decisions

Why Dynamic Jobs Instead of Global Schedule?

  • ✅ Personalized timing (respects each user's pace)
  • ✅ Context-aware (knows their level/module)
  • ✅ Scalable (works for 1 or 10,000 users)
  • ✅ No wasted resources (only runs when needed)

Why Check Progress First?

  • ✅ Prevents re-assessing returning users
  • ✅ Maintains continuity (pick up where they left off)
  • ✅ Better user experience (no redundant questions)

Why Embed Metadata?

  • ✅ Always works (no dependency on Data Primitive)
  • ✅ Graceful degradation (full content if available, metadata otherwise)
  • ✅ Fast (compiled with agent code)

Why No File System Access at Runtime?

  • ✅ Security (agents shouldn't access local files)
  • ✅ Cloud-native (works in any deployment environment)
  • ✅ Performance (Data Primitive optimized for reads)

Troubleshooting

"Content not found" Error

Solution: The agent now uses embedded metadata as fallback. This error shouldn't occur, but if it does:

npm run load-data  # Load full content to Data Primitive

User Gets Re-Assessed

Problem: Agent not checking progress first
Solution: Ensure agent persona includes "Always check check_level_progress FIRST"

Job Not Firing

Problem: Job creation might have failed
Check: Look for errors in CompleteModuleTool or MaturityAssessmentTool output

Module Won't Mark Complete

Problem: Verification details missing or user not at that level
Solution: Ensure module being completed is for user's current level


Support & Documentation

Official Lua Documentation

Commands Reference

# Development
npm run build         # Compile TypeScript
npm run load-data     # Load RAG content to Data Primitive

# Lua CLI
lua test              # Test tools locally
lua chat              # Interactive chat (sandbox or production)
lua compile           # Compile for deployment
lua push all          # Push all components
lua deploy            # Deploy to production
lua production        # Check production status

License

ISC


Summary

The Mesh Financial Coach is a complete, production-ready AI coaching system that:

  • Assesses users once and tracks their journey through 5 levels
  • Provides 15 modules of progressive financial education
  • Sends personalized reminders based on each user's timeline
  • Grounds all advice in educational principles
  • Works reliably with built-in fallbacks

Ready to deploy and start coaching! 🚀

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors