# Validate Connector Action

`appmixer-cli/src/ai/validateConnector.js`

Automated validation system for Appmixer connectors using LangGraph workflows.

### Usage
```bash
$ appmixer init ai validation <connectorName>
```

### Flow

1. **Authentication Check** - Validates connector auth setup  
2. **Load Context** - Reads instructions and existing test plans (test-plan.json located in the <connector>/artifacts/ai-artifacts/ folder) 
3. **Router Decision** - if the test plan does not exits, go to Planning phase; if it exists but is incomplete, go to Testing phase
4. **Planning** - Creates test plan if none exists - `planningSubgraphNode`
5. **Testing** - Executes tests if plan exists - `processTestPlanNode`
6. **Completion** - Returns validation results, generates human readable report - `test-plan-report.md`

### Architecture

**Main Graph Structure:**
![img_1.png](img_1.png)

## Planning Subgraph

![img_2.png](img_2.png)

Creates intelligent test plans for connectors. Analyzes connector components and generates logical test sequences that follow real-world user workflows.

### Workflow
1. **preparePlannerNode** - Lists components, adds instructions
2. **plannerNode** - LLM analyzes components using tools
3. **tools** - Reads component configs when needed
4. **structured_output** - Converts to structured format, exports artifacts

### Output
- **Artifacts**: `test-plan.md` (detailed), `test-plan.json` (structured)

### Test Plan Schema
```javascript
{
  plan: [
    {
      name: "ComponentName",
      completed: false,
      result: {}
    }
  ]
}
```

## Process Test Plan Subgraph

![img_3.png](img_3.png)

Executes test plans by running component validations sequentially. Manages test state and generates  test reports.

### Workflow
1. **selectNextTestNode** - Finds next incomplete test, marks completion when done
2. **executeTestNode** - LLM executes component validation using tools
3. **toolsNode** - Runs validation tools when needed
4. **completeTestNode** - Updates test results and saves progress to the `test-plan.json`
5. **exportTestReportNode** - Generates final test report: `test-plan-report.md`

### Output
- **Artifacts**: Updated `test-plan.json`
- **Report**: `test-plan-report.md` generated when all tests complete

### Test Result Schema
```javascript
{
  status: "completed",
  timestamp: "2025-10-03T10:30:00.000Z", 
  output: "test execution details",
  commands: [
        {
            "exitCode": 0,
            "stdout": "Component has send a message to output port: notFound\n{}\n\n\n\nComponent's receive method finished in: 589 ms.\n\nComponent's state at the end:\nState is empty, component did not store anything into state.\n\nStopping component.",
            "stderr": "",
            "duration": 6165,
            "command": "appmixer test component src/appmixer/kit/form/FindSubscribersForForm/ -i '{\"in\":{\"formId\":\"8405075\",\"outputType\":\"array\"}}'"
        },
        ... 
    ]
}
```

# Refactor Action

Interactive component development and refactoring system using LangGraph workflows and CLI interface.

`appmixer-cli/src/ai/refactor.js`

```bash
$ appmixer init ai refactor <connectorName> <componentName>
```

### Purpose
Provides an interactive CLI for component lifecycle management - from recipe generation to component refactoring according to Appmixer standards.

### Interactive CLI Flow

**State Management:**
- Tracks `componentJson` (existing component configuration)
- Tracks `componentRecipe` (generated component recipe from AI)

**Available Actions:**
1. **Generate Recipe** - Creates component specification using AI analysis
2. **Generate Skeleton** - Creates component files from recipe (requires recipe)
3. **Refactor Component** - Standardizes existing component (requires existing component)
4. **Exit** - Terminates the session

### Action Details

#### Generate Recipe
- Uses `generateComponentRecipeGraph` to analyze requirements
- Creates `componentRecipe.json` artifact
- AI-driven component specification generation

#### Generate Skeleton
- Converts recipe into actual component files
- Generates `component.json`, behavior files, and directory structure
- Requires existing `componentRecipe.json`

#### Refactor Component
- Uses `refactorGraph` LangGraph workflow
- Validates component against Appmixer standards
- Updates `component.json` and behavior files as needed

## Refactor Graph

Simple 2-node LangGraph for component standardization.

### Workflow
1. **modelNode** - LLM analyzes component against standards using tools
2. **tools** - Executes file operations when needed

### Tools Available
- `readComponentJson` - Reads component configuration
- `writeBehaviorFile` - Updates behavior file
- `writeComponentJson` - Updates component configuration  
- `readBehaviorFile` - Reads behavior file

### Process
1. Loads connector context and component standards
2. LLM compares component against standards
3. Makes necessary updates to achieve compliance
4. Preserves component icon through the process

### Features
- **Standards Compliance** - Ensures components follow Appmixer patterns
- **Intelligent Updates** - Only modifies what needs to be changed
- **Icon Preservation** - Maintains component icon during refactoring
- **Interactive Feedback** - Real-time progress and decision visibility


# Tools 

`appmixer-cli/src/ai/src/agents/tools.js`

### Structure 
```js
import { tool } from '@langchain/core/tools';

export const writeComponentJson = ({ connectorsDir }) => tool(
    async ({ connector, component, content }) => {
        const toolName = 'writeComponentComponentJson';
        // tool logic here
        return 'Success';  // return string result, structured data, like JSON is not supported
    },
    {
        // tool name used in the LLM prompt
        name: 'write_component_json',   
        
        // tool description used in the LLM prompt
        description: 'Write the contents of a component.json file for a specific component in a connector. Takes "connector", "component", and the new "content" as parameters.',
        
        // input schema for the tool
        schema: z.object({
            connector: z.string().describe('The name of the connector'),
            component: z.string().describe('The name of the component'),
            content: z.string().describe('The JSON content to write to the component.json file')
        })
    });
```

# LangGraph Studio 

### Setup
go to the `appmixer-cli/src/ai/studio` folder 

- run npm install 
```bash
npm install
```
- create .env file from .env.example and set the variables `LANGSMITH_API_KEY`, `OPENAI_API` and `ANTHROPIC_API_KEY`
- run the studio 
```bash
$ npx @langchain/langgraph-cli dev
```

For more info on how to configure, go to: https://docs.langchain.com/langgraph-platform/local-server#node-server

Video tutorial on how to use the studio: https://docs.langchain.com/langgraph-platform/langgraph-studio

TODO
it should be possible to run and debug the graph calls. This is not working yet.
