← Back to Articles & Artefacts
artefactseast

Design Proposal: Integrating a Prompt Decomposition Engine (PDE) into `mia-code`

IAIP Research
mia-code--contextual_research--archives

Design Proposal: Integrating a Prompt Decomposition Engine (PDE) into mia-code

Document Purpose: This document outlines a detailed design for integrating a Prompt Decomposition Engine (PDE) into the mia-code CLI tool. The objective is to evolve mia-code from a direct prompt-response wrapper into an intelligent, plan-driven agentic orchestrator, aligning with the principles of structured thinking and ceremonial development.

1. Analysis of Current mia-code Architecture

Based on a review of the /a/src/mia-code repository, the current architecture is as follows:

  • Technology: A Node.js application written in TypeScript, using commander.js for CLI command parsing.
  • Core Functionality: It serves as a user-friendly terminal interface that wraps the Gemini and Claude CLI tools in their headless modes.
  • Execution Flow:
    1. The user runs mia-code chat or mia-code prompt.
    2. src/cli.ts and src/index.ts parse the command and manage the interactive session.
    3. User input is passed to the runGeminiHeadless function in src/geminiHeadless.ts.
    4. This function spawns the appropriate backend CLI (e.g., gemini) as a child process, passing the user's raw prompt and other flags.
    5. It captures and parses the stream-json or json output from the backend, optionally running it through a unifier for ceremonial interpretation.
  • Limitation: The current design sends the user's prompt directly to the backend LLM. It lacks a mechanism to decompose complex, multi-step user intents, leading to potential failures, incomplete responses, or a lack of transparency for the user.

2. Proposed Architectural Vision: PDE Integration

We propose embedding the PDE directly into the mia-code CLI's command execution lifecycle. This transforms mia-code into a "thinking" client that plans its work before executing it.

High-Level Workflow:

sequenceDiagram
    participant User
    participant MiaCodeCLI as `mia-code` CLI
    participant PDE as Prompt Decomposition Engine (API)
    participant Gemini as Gemini/Claude Backend

    User->>+MiaCodeCLI: mia-code chat --pde "Complex multi-step request"
    MiaCodeCLI->>+PDE: Decompose(request)
    PDE-->>-MiaCodeCLI: Return Structured Plan (ExecutionPlan)
    MiaCodeCLI->>User: Display Ceremonial Plan for Approval<br/>(EAST, SOUTH, WEST, NORTH stages)
    User->>+MiaCodeCLI: "y" (approves plan)
    
    loop For Each Step in Plan
        MiaCodeCLI->>+Gemini: Execute Step N (prompt from plan)
        Gemini-->>-MiaCodeCLI: Return Step N Result
        MiaCodeCLI->>User: Display Step N Result/Status
    end
    
    MiaCodeCLI-->>-User: Final Summary

3. Detailed Technical Design

This section details the specific code-level changes and additions required to implement the PDE integration.

3.1. New src/pde/ Module

A new directory will be created at /a/src/mia-code/src/pde/ to encapsulate all PDE-related logic.

  • pde-types.ts: This file will define the TypeScript interfaces for the data structures exchanged with the PDE, primarily the ExecutionPlan.

    // /a/src/mia-code/src/pde/pde-types.ts
    
    export type MedicineWheelDirection = "EAST" | "SOUTH" | "WEST" | "NORTH";
    
    export interface PdeTask {
      id: string;
      description: string;
      agentCommand: string; // e.g., "gemini" or "claude"
      prompt: string;       // The specific prompt for this step
      expectedOutputs: string[];
      dependencies: string[];
    }
    
    export interface PdeStage {
      stageId: string;
      direction: MedicineWheelDirection;
      directionDescription: string; // e.g., "Vision & Inquiry"
      tasks: PdeTask[];
    }
    
    export interface ExecutionPlan {
      workflowId: string;
      overallIntention: string;
      stages: PdeStage[];
    }
    
  • pde-client.ts: This client will handle communication with the PDE API. Initially, it can be a mock that returns a hardcoded plan for testing.

    // /a/src/mia-code/src/pde/pde-client.ts
    import { ExecutionPlan } from "./pde-types";
    
    export async function decomposePrompt(prompt: string): Promise<ExecutionPlan> {
      // In the future, this will make an HTTP call to the PDE API
      // For now, return a mock plan for development
      console.log(`[PDE Client] Decomposing: "${prompt}"`);
      // ... Mock implementation
      // Example:
      const mockPlan: ExecutionPlan = { /* ... structured plan ... */ };
      return mockPlan;
    }
    

3.2. CLI Command Enhancements (src/cli.ts)

  1. Add --pde Flag: The chat command will be updated to include a --pde flag to activate the planning workflow.

    // in src/cli.ts, inside the 'chat' command action
    await runInteractiveCli({
      // ... existing options
      usePde: opts.pde // new option
    });
    
  2. Add decompose Command: A new command will be added for users who only want to see the plan without executing it.

    // in src/index.ts, add a new command
    program
      .command("decompose <text>")
      .description("Decompose a complex prompt into an executable plan using PDE")
      .action(async (text) => {
        const plan = await decomposePrompt(text);
        displayPlan(plan); // A new rendering function
      });
    

3.3. Core Logic Modification (src/index.ts & a new pde-executor.ts)

The primary change will be in runInteractiveCli. It needs a new conditional path for PDE-enabled prompts.

  1. Modify runInteractiveCli:

    // in src/cli.ts
    // ... inside processInput function
    if (config.usePde) { // Assume config is updated with the flag
        console.log(chalk.magenta("🧬 Decomposing prompt via PDE..."));
        const plan = await decomposePrompt(trimmed);
        
        displayPlan(plan); // Render the ceremonial plan
        
        const { enquirer } = await import('enquirer');
        const { confirm } = await enquirer.prompt({
            type: 'confirm',
            name: 'confirm',
            message: 'Proceed with execution?'
        });
    
        if (confirm) {
            await executePdePlan(plan, config, rl);
        } else {
            console.log(chalk.yellow("Execution cancelled."));
        }
    } else {
        // ... existing runGeminiHeadless logic
    }
    
  2. Create pde-executor.ts: To keep the logic clean, a new file will handle the step-by-step execution.

    // /a/src/mia-code/src/pde-executor.ts
    import { ExecutionPlan, PdeStage } from "./pde/pde-types";
    import { runGeminiHeadless } from "./geminiHeadless";
    // ... other imports
    
    export async function executePdePlan(plan: ExecutionPlan, config: MiaCodeConfig, rl: Interface) {
        console.log("\n" + chalk.bold.green("🚀 Starting Execution..."));
        const context: Record<string, any> = {}; // To store results of steps
    
        for (const stage of plan.stages) {
            displayStageHeader(stage);
            for (const task of stage.tasks) {
                // ... logic to check if dependencies are met from `context`
                
                console.log(chalk.dim(`  - Executing task: ${task.description}`));
                const result = await runGeminiHeadless({
                    prompt: task.prompt,
                    config,
                    // Session management needs to be adapted for multi-step execution
                });
    
                // Store result in context for dependent tasks
                context[task.id] = result; 
                
                // ... render task result
            }
        }
        console.log("\n" + chalk.bold.green("✅ Plan execution complete."));
    }
    

3.4. Ceremonial UI Integration (src/formatting.ts)

New functions will be added to render the plan in a way that reflects its ceremonial structure.

// /a/src/mia-code/src/formatting.ts

const directionColors = {
    EAST: chalk.hex('#FFD700'),  // Gold for Vision
    SOUTH: chalk.hex('#32CD32'), // Green for Growth
    WEST: chalk.hex('#4682B4'),  // SteelBlue for Integration
    NORTH: chalk.hex('#FFFFFF')   // White for Wisdom
};

export function displayPlan(plan: ExecutionPlan) {
    console.log(`\n${chalk.bold.magenta('🧬 Decomposed Plan:')} ${plan.overallIntention}`);
    for (const stage of plan.stages) {
        const color = directionColors[stage.direction] || chalk.white;
        console.log(color(`\n${stage.direction}: ${stage.directionDescription}`));
        for (const task of stage.tasks) {
            console.log(chalk.dim(`  - [ ] ${task.description}`));
            if (task.dependencies.length > 0) {
                console.log(chalk.dim(`        (depends on: ${task.dependencies.join(', ')})`));
            }
        }
    }
    console.log("");
}

4. Phased Implementation Roadmap

  1. Phase 1: Foundation & Mocking

    • Implement the pde/ directory with types and a mocked pde-client.
    • Implement the UI rendering functions in formatting.ts.
    • Add the decompose command to cli.ts to test the plan rendering.
  2. Phase 2: Core Execution Logic

    • Add the --pde flag and the conditional logic in cli.ts.
    • Implement the pde-executor.ts file with the core loop for step-by-step execution.
    • Adapt session handling in geminiHeadless.ts to work across multiple calls within a single plan.
  3. Phase 3: Live Integration & Refinement

    • Replace the mocked pde-client with a real HTTP client to call the live PDE API.
    • Implement robust error handling, dependency management, and state tracking in the pde-executor.
    • Conduct user testing to refine the CLI's interactive experience for plan approval and execution feedback.

5. Conclusion

Integrating the Prompt Decomposition Engine into mia-code represents a significant architectural evolution. It elevates the tool from a simple command-line wrapper to a sophisticated agentic assistant that brings transparency, control, and resilience to complex development tasks. By grounding this technical design in the project's ceremonial philosophy, we create a tool that is not only more powerful but also more intuitive and aligned with its intended purpose.