ADR-051: AI-Driven Application Generator

Status: Accepted (Phase 1 Complete) Date: 2025-12-11 Implementation: v1.61.0 (Foundation), v1.62.0+ (Full Features) Related: ADR-050 (Command Restructuring), ADR-049 (Project Rebranding)


Context

Problem Statement:

Creating a complete iDempiere application (plugin) currently requires 20-30 hours of manual work:

  1. Requirements Analysis (2 hours) - Manual document review
  2. Database Design (4 hours) - Schema design, relationships
  3. Application Dictionary (3 hours) - Create tables, columns manually in AD
  4. Database Synchronization (1 hour) - Run sync scripts
  5. Model Generation (1 hour) - Generate I_, X_, M_ classes
  6. Window/Tab Creation (4 hours) - Create UI definitions in AD
  7. Business Logic (8 hours) - Write processes, callouts, validators
  8. Testing (4 hours) - Manual testing
  9. Documentation (2 hours) - Write docs
  10. 2Pack Export (1 hour) - Package for distribution

Total: ~29 hours per application

Current Capability:

iDempiere AI Hub v1.59.0 provides individual tools:

Missing: No holistic application generation from requirements

Vision: AI-driven workflow that generates complete applications in minutes instead of hours (10x productivity gain).


Decision

Implement AI-Driven Application Generator that transforms natural language requirements into complete, production-ready iDempiere applications.

New Command:

idempiere-cli app generate \
  --name "Warehouse Management" \
  --description "Multi-zone WMS with barcode scanning" \
  --requirements ./requirements.md \
  --output ./plugins/com.cloudempiere.wms \
  --interactive

Generated Artifacts:

plugins/com.cloudempiere.wms/
├── META-INF/
│   ├── MANIFEST.MF                    # OSGi bundle manifest
│   └── 2Pack_*.zip                    # 2Pack export (AD metadata)
├── src/main/java/
│   └── com/cloudempiere/wms/
│       ├── model/                     # Model classes
│       │   ├── I_CE_WMS_Warehouse.java
│       │   ├── X_CE_WMS_Warehouse.java
│       │   ├── M_CE_WMS_Warehouse.java
│       │   └── ...                    # Other tables
│       ├── factory/
│       │   └── WMSModelFactory.java   # Model factory
│       ├── process/                   # Business processes
│       │   ├── BarcodeScanProcess.java
│       │   ├── LocationTransferProcess.java
│       │   └── ...
│       ├── callout/                   # Callouts
│       │   └── CapacityCalculation.java
│       └── validator/                 # Model validators
│           └── WMSValidator.java
├── migration/                         # Database migrations
│   ├── postgresql/
│   │   ├── 001_create_wms_tables.sql
│   │   └── 002_create_seed_data.sql
│   └── oracle/
│       └── 001_create_wms_tables.sql
├── docs/
│   ├── README.md                      # Application documentation
│   ├── USER_GUIDE.md                  # User guide
│   └── TECHNICAL_SPEC.md              # Technical specification
├── pom.xml                            # Maven build file
├── build.properties                   # Eclipse build config
└── plugin.xml                         # Plugin configuration

Architecture

High-Level Workflow

┌────────────────────────────────────────────────────────────────┐
│                    Application Generator                       │
├────────────────────────────────────────────────────────────────┤
│                                                                │
│  1. Requirements Analysis (AI)                                │
│     ├─ Parse natural language requirements                    │
│     ├─ Extract entities and relationships                     │
│     ├─ Identify business rules                                │
│     └─ Propose database schema                                │
│                                                                │
│  2. User Review & Approval (Interactive)                      │
│     ├─ Display proposed schema                                │
│     ├─ Allow modifications                                    │
│     └─ Confirm generation plan                                │
│                                                                │
│  3. Database Schema Generation                                │
│     ├─ Generate Application Dictionary entries (2Pack XML)    │
│     ├─ Generate SQL DDL scripts                               │
│     └─ Validate schema constraints                            │
│                                                                │
│  4. Model Class Generation                                    │
│     ├─ Generate I_* interfaces                                │
│     ├─ Generate X_* base classes                              │
│     ├─ Generate M_* custom classes                            │
│     └─ Generate model factory                                 │
│                                                                │
│  5. Business Logic Generation (AI)                            │
│     ├─ Generate process classes                               │
│     ├─ Generate callouts                                      │
│     ├─ Generate validators                                    │
│     └─ Apply iDempiere best practices                         │
│                                                                │
│  6. UI Definition Generation                                  │
│     ├─ Generate window definitions (2Pack)                    │
│     ├─ Generate tab definitions                               │
│     ├─ Generate field groups                                  │
│     └─ Configure field display logic                          │
│                                                                │
│  7. Plugin Assembly                                           │
│     ├─ Create OSGi bundle structure                           │
│     ├─ Generate MANIFEST.MF                                   │
│     ├─ Generate pom.xml                                       │
│     ├─ Export 2Pack                                           │
│     └─ Generate documentation                                 │
│                                                                │
│  8. Validation & Testing                                      │
│     ├─ Validate generated code                                │
│     ├─ Check naming conventions                               │
│     ├─ Verify dependencies                                    │
│     └─ Generate test stubs                                    │
│                                                                │
└────────────────────────────────────────────────────────────────┘

AI Integration

@ApplicationScoped
public class ApplicationGenerator {

    @Inject
    LangChain4jService aiService;

    @Inject
    RequirementsAnalyzer requirementsAnalyzer;

    @Inject
    SchemaDesigner schemaDesigner;

    @Inject
    MetamodelGenerator metamodelGenerator;

    @Inject
    ModelGenerator modelGenerator;

    @Inject
    CodeGenerator codeGenerator;

    @Inject
    PluginAssembler pluginAssembler;

    public ApplicationResult generate(ApplicationSpec spec) {

        // 1. Analyze requirements with AI
        log.info("Analyzing requirements...");
        RequirementsAnalysis analysis = analyzeRequirements(spec);

        // 2. Design database schema (AI-assisted)
        log.info("Designing database schema...");
        DatabaseSchema schema = schemaDesigner.design(analysis);

        // 3. Interactive review (if enabled)
        if (spec.isInteractive()) {
            schema = interactiveReview(schema);
        }

        // 4. Generate Application Dictionary (2Pack)
        log.info("Generating Application Dictionary...");
        TwoPackDefinition twopack = metamodelGenerator.generate(schema);

        // 5. Generate SQL DDL
        log.info("Generating SQL scripts...");
        List<SQLScript> sqlScripts = metamodelGenerator.generateSQL(schema);

        // 6. Generate model classes
        log.info("Generating model classes...");
        List<ModelClass> models = modelGenerator.generateBatch(schema.getTables());

        // 7. Generate business logic (AI-driven)
        log.info("Generating business logic...");
        BusinessLogic logic = codeGenerator.generateBusinessLogic(analysis, schema);

        // 8. Generate UI definitions
        log.info("Generating UI definitions...");
        UIDefinition ui = codeGenerator.generateUI(schema, analysis);

        // 9. Assemble plugin
        log.info("Assembling plugin...");
        Plugin plugin = pluginAssembler.assemble(
            spec, schema, twopack, sqlScripts, models, logic, ui
        );

        // 10. Generate documentation
        log.info("Generating documentation...");
        Documentation docs = generateDocumentation(analysis, schema, plugin);

        return ApplicationResult.builder()
            .plugin(plugin)
            .documentation(docs)
            .buildTime(Duration.between(start, Instant.now()))
            .build();
    }

    private RequirementsAnalysis analyzeRequirements(ApplicationSpec spec) {

        String prompt = buildAnalysisPrompt(spec);

        AiMessage response = aiService.chat(prompt);

        return parseRequirementsAnalysis(response.text());
    }
}

AI Prompts

Requirements Analysis Prompt:

You are an expert iDempiere consultant analyzing application requirements.

Application: {name}
Description: {description}

Requirements:
{requirements}

Analyze and provide:

1. Database Schema
   - Tables needed (with prefix {entityType}_)
   - Columns for each table (name, type, mandatory, description)
   - Relationships (foreign keys, reference types)
   - Indexes and constraints

2. Business Logic
   - Processes needed (name, description, parameters)
   - Callouts needed (table, column, logic)
   - Model validators needed (events, logic)

3. UI Components
   - Windows needed (name, description)
   - Tabs for each window (name, table, display logic)
   - Special fields (buttons, custom displays)

4. Integration Points
   - REST API endpoints needed
   - Event handlers needed
   - External system integrations

Output as JSON following this schema:
{schema}

Code Generation Prompt:

Generate iDempiere {component_type} for:

Table: {table_name}
Business Rule: {business_rule}
Context: {context}

Follow iDempiere best practices:
- Use PO.get_Value* methods for field access
- Handle transactions properly (Trx.get)
- Log with CLogger
- Return ProcessInfoParameter for processes
- Use proper error handling

Generate production-ready code with:
- Javadoc comments
- Input validation
- Error handling
- Transaction management
- Logging

Output only Java code, no explanations.

Implementation Details

Phase 1: Requirements Analysis

Input Formats:

  1. Natural Language (Markdown)
# Warehouse Management System

## Overview
Multi-zone warehouse management with barcode scanning

## Features
- Warehouse zones and locations
- Bin capacity tracking
- Barcode scanning for locations
- Location transfer workflows
- Inventory visibility by location
  1. Structured YAML
application:
  name: Warehouse Management
  entity_type: CE_WMS

entities:
  - name: Warehouse
    description: Physical warehouse
    fields:
      - name: Name
        type: String
        length: 60
        mandatory: true
      - name: Description
        type: Text

  - name: Zone
    description: Warehouse zone
    fields:
      - name: Warehouse_ID
        type: TableDir
        reference: CE_WMS_Warehouse
      - name: Name
        type: String
  1. Interactive Mode
$ idempiere-cli app generate --interactive

🤖 Application Generator
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📝 Application name: Warehouse Management
📝 Description: Multi-zone WMS with barcode scanning
📝 Entity type (e.g., CE): CE_WMS

🤔 What features do you need?
  1. Warehouse zones
  2. Bin locations
  3. Barcode scanning
  4. Location transfers
  5. Capacity tracking

✓ Features selected

🧠 Analyzing requirements with AI...

Phase 2: Schema Design

AI Output:

{
  "tables": [
    {
      "name": "CE_WMS_Warehouse",
      "description": "Physical warehouse",
      "accessLevel": "3",
      "columns": [
        {
          "name": "Name",
          "type": "String",
          "length": 60,
          "mandatory": true,
          "description": "Warehouse name"
        },
        {
          "name": "Description",
          "type": "Text",
          "mandatory": false,
          "description": "Warehouse description"
        }
      ]
    },
    {
      "name": "CE_WMS_Zone",
      "description": "Warehouse zone",
      "accessLevel": "3",
      "columns": [
        {
          "name": "CE_WMS_Warehouse_ID",
          "type": "TableDir",
          "reference": "CE_WMS_Warehouse",
          "mandatory": true
        },
        {
          "name": "Name",
          "type": "String",
          "length": 60,
          "mandatory": true
        }
      ]
    }
  ],
  "processes": [
    {
      "name": "Location Transfer",
      "description": "Transfer inventory between locations",
      "className": "LocationTransferProcess",
      "parameters": [
        {"name": "FromLocation_ID", "type": "Search"},
        {"name": "ToLocation_ID", "type": "Search"},
        {"name": "Product_ID", "type": "Search"},
        {"name": "Qty", "type": "Quantity"}
      ]
    }
  ],
  "windows": [
    {
      "name": "Warehouse Management",
      "description": "Manage warehouses and zones",
      "tabs": [
        {
          "name": "Warehouse",
          "table": "CE_WMS_Warehouse",
          "level": 0
        },
        {
          "name": "Zones",
          "table": "CE_WMS_Zone",
          "level": 1,
          "tabLevel": 1
        }
      ]
    }
  ]
}

Phase 3: Code Generation

Generated Process Example:

package com.cloudempiere.wms.process;

import org.compiere.process.ProcessInfoParameter;
import org.compiere.process.SvrProcess;
import org.compiere.model.MStorage;
import org.compiere.util.Env;

/**
 * Location Transfer Process
 *
 * Transfer inventory between warehouse locations.
 *
 * Generated by iDempiere AI Hub
 * @version 1.60
 */
public class LocationTransferProcess extends SvrProcess {

    private int p_FromLocation_ID = 0;
    private int p_ToLocation_ID = 0;
    private int p_Product_ID = 0;
    private BigDecimal p_Qty = Env.ZERO;

    @Override
    protected void prepare() {
        ProcessInfoParameter[] params = getParameter();
        for (ProcessInfoParameter param : params) {
            String name = param.getParameterName();
            switch (name) {
                case "FromLocation_ID":
                    p_FromLocation_ID = param.getParameterAsInt();
                    break;
                case "ToLocation_ID":
                    p_ToLocation_ID = param.getParameterAsInt();
                    break;
                case "Product_ID":
                    p_Product_ID = param.getParameterAsInt();
                    break;
                case "Qty":
                    p_Qty = (BigDecimal) param.getParameter();
                    break;
                default:
                    log.warning("Unknown parameter: " + name);
            }
        }
    }

    @Override
    protected String doIt() throws Exception {

        // Validate parameters
        if (p_FromLocation_ID == 0)
            throw new IllegalArgumentException("@FromLocation_ID@ @NotFound@");
        if (p_ToLocation_ID == 0)
            throw new IllegalArgumentException("@ToLocation_ID@ @NotFound@");
        if (p_Product_ID == 0)
            throw new IllegalArgumentException("@Product_ID@ @NotFound@");
        if (p_Qty.signum() <= 0)
            throw new IllegalArgumentException("@Qty@ @Invalid@");

        // Business logic (AI-generated with iDempiere best practices)
        // TODO: Implement transfer logic

        return "@Success@";
    }
}

User Experience

Example Session

$ idempiere-cli app generate --interactive

🤖 iDempiere AI Hub - Application Generator v1.60
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📋 Step 1: Requirements
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Application name: Warehouse Management System
Description: Multi-zone warehouse with barcode scanning
Entity type: CE_WMS

📄 Provide requirements:
  1. Write requirements now (interactive)
  2. Load from file (./requirements.md)

Choice [1]: 2
✓ Loaded ./requirements.md

🧠 Step 2: AI Analysis
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Analyzing requirements with Claude Sonnet 4...
✓ Requirements analyzed (3.2s)

📊 Proposed Database Schema:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Tables (5):
  ✓ CE_WMS_Warehouse (7 columns)
  ✓ CE_WMS_Zone (6 columns)
  ✓ CE_WMS_Location (10 columns)
  ✓ CE_WMS_Capacity (8 columns)
  ✓ CE_WMS_Barcode (5 columns)

Relationships:
  ├─ Warehouse → Zones (1:N)
  ├─ Zone → Locations (1:N)
  ├─ Location → Capacity (1:1)
  └─ Location → Barcodes (1:N)

Business Logic:
  ├─ 3 Processes (Transfer, Scan, Replenish)
  ├─ 2 Callouts (Capacity calculation, Zone validation)
  └─ 1 Validator (Location integrity)

UI Components:
  └─ 1 Window with 5 tabs

Review schema? (Y/n/edit): y

🏗️  Step 3: Generation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  ✓ Generated Application Dictionary (2Pack)       2.1s
  ✓ Generated SQL migration scripts                0.8s
  ✓ Generated model classes (15 files)             3.4s
  ✓ Generated model factory                        0.5s
  ✓ Generated business logic (6 classes)           5.2s
  ✓ Generated UI definitions                       1.9s
  ✓ Generated plugin structure                     0.4s
  ✓ Generated documentation                        1.2s
  ✓ Validated generated code                       0.7s

📦 Application Generated
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Location: ./plugins/com.cloudempiere.wms/
Files: 32
Lines of code: 2,847
⏱️  Total time: 16.2 seconds

🚀 Next Steps:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. Review generated code:
   cd ./plugins/com.cloudempiere.wms

2. Apply database migrations:
   psql -d idempiere -f migration/postgresql/001_create_wms_tables.sql

3. Build plugin:
   mvn clean package

4. Install to iDempiere:
   cp target/com.cloudempiere.wms-1.0.0.jar $IDEMPIERE_HOME/plugins/

5. Import 2Pack:
   iDempiere → Pack In → META-INF/2Pack_WMS.zip

6. Restart iDempiere

📚 Documentation: ./plugins/com.cloudempiere.wms/docs/README.md

Consequences

Positive

  1. 10x Productivity

    • 29 hours → 4.5 hours (15 min AI + 2hr review + 2hr testing)
    • Monthly capacity: 5 apps → 50 apps
  2. Consistent Quality

    • AI follows best practices
    • Template-based generation
    • Automated validation
    • Fewer human errors
  3. Knowledge Preservation

    • Best practices encoded in prompts
    • Patterns reused automatically
    • Less dependency on senior developers
  4. Faster Time to Market

    • Rapid prototyping
    • Quick iterations
    • Earlier stakeholder feedback
  5. Reduced Learning Curve

    • Generated code is learning material
    • Consistent patterns
    • Well-documented

Negative

  1. AI Dependency

    • Requires LLM API access
    • Cost per generation
    • Quality depends on AI model
    • Mitigation: Cache, fallbacks, local models
  2. Review Burden

    • Generated code needs review
    • May require refactoring
    • Mitigation: High-quality prompts, validation
  3. Complex Requirements

    • AI may misunderstand
    • Edge cases not handled
    • Mitigation: Interactive mode, human review
  4. Maintenance

    • Prompt engineering ongoing
    • Template maintenance
    • Mitigation: Version prompts, A/B testing

Alternatives Considered

Alternative 1: Manual Scaffolding Only

Description: Provide empty templates, developers fill in logic

Pros:

Cons:

Decision: ❌ Rejected - Doesn't achieve goals

Alternative 2: Wizard-Based Generation

Description: GUI wizard asking step-by-step questions

Pros:

Cons:

Decision: ❌ Rejected - Not aligned with AI Hub vision

Alternative 3: Template-Only Generation

Description: Select template, customize parameters

Pros:

Cons:

Decision: ❌ Rejected - Too rigid

Alternative 4: AI-Driven Generation (Selected)

✅ Full AI-driven generation with human review

Pros:

Cons:

Decision: ✅ Accepted - Best balance


Implementation Roadmap

v1.61.0 - Foundation ✅ COMPLETE (2025-12-11)

Core Infrastructure ✅

Data Transfer Objects ✅

Service Implementations ✅

CLI Integration ✅

Generation Pipeline 🚧 IN PROGRESS

Documentation ✅

Commit: f8d58c2 (12 files, 2,350+ lines)

v1.62.0 - Core Generation 🚧 IN PROGRESS

Generation Integration (Next)

v1.61+ (Continuous Improvement)


Success Metrics

Track via observability:

  1. Generation Success Rate

    • Target: >90% generate without errors
    • Track: Failures, error types
  2. Time Savings

    • Target: 80% reduction (29h → 5h)
    • Track: Generation time, review time
  3. Code Quality

    • Target: >95% pass code review
    • Track: Review comments, refactoring needed
  4. Adoption

    • Target: 50% of new apps use generator by Q2 2025
    • Track: Manual vs generated apps
  5. Cost

    • Target: <$5 per application
    • Track: LLM API costs

References

Related ADRs:

Vision Documents:

Tools:


Document Status: Accepted Implementation Status: v1.61.0 Foundation Complete (2025-12-11) Next Phase: v1.62.0 Core Generation

Path: /docs/developers/architecture/idempiere-hub/051-application-generator