Skip to content

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 

Repository files navigation

ServiceNow-GitLab-n8n_Autonomous-Agent

n8n_workflow

Overview

This project is an advanced, fully autonomous n8n workflow that bridges IT Service Management (ServiceNow) and version control (GitLab). It operates as an AI-driven software engineer, automatically responding to ServiceNow issue tickets, analyzing the GitLab repository, writing code fixes via Google Gemini (PaLM) API, pushing the changes, and creating Merge Requests (MRs)—all with zero human intervention.

Furthermore, it features an intelligent Feedback Loop: if a human reviewer leaves a comment on the generated Merge Request, the AI agent automatically parses the feedback, applies the requested changes, and pushes a revised commit.

Key Achievements & Breakthroughs

  • End-to-End Autonomous Resolution: Transforms n8n from a simple task runner into an autonomous operational brain capable of resolving software bugs from ticket creation to MR submission.
  • Smart File Detection & Hallucination Prevention: Implements multi-layered logic to identify affected files. If the ticket doesn't specify a file, the AI scans the repo tree and scores files based on keyword density. It actively filters out LLM "hallucinations" (invented file names) by cross-referencing real repository data.
  • Multi-File Patching (GNU diff -u): Capable of parsing complex tickets, instructing Gemini to generate unified diff patches for multiple files simultaneously, and reliably parsing the +++ boundaries to apply patches locally.
  • Code Syntax Guardrails: Includes language-specific Regex validation (covering 15+ languages including Python, JS, TS, Go, Rust, Java, etc.) to ensure the AI output is actual code and not conversational prose (e.g., rejecting outputs starting with "Here is the fix...").
  • Pre-Flight AI Review: Implements a "second opinion" AI pass. Before committing, the AI reviews its own patch for logic errors and security vulnerabilities. If confidence is below the threshold, it halts the pipeline to prevent bad code from entering the repository.
  • Intelligent Escalation Routing: If the AI encounters vague tickets (e.g., "rewrite everything"), exceeds retry limits, or fails pre-flight checks, it gracefully aborts the automated fix. It performs a git blame to find the last human contributor and creates a GitLab Issue escalating the problem for manual review.

Core Workflow Architecture

The pipeline is triggered by incoming webhooks (either from ServiceNow or GitLab comments) and executes through several distinct phases:

Phase 1: Ingestion & Intent Parsing

  • Webhook Triggers: Listens for new ServiceNow incident webhooks or GitLab MR comment webhooks.
  • Extract Issue Data: Parses the ticket summary and description. Uses Regex patterns (e.g., in auth/helpers.py, file: config.json) to smartly extract explicit file references.
  • Smart File Detection: Analyzes the entropy of the request. It flags impossibly vague tickets (e.g., "optimize entire codebase") for immediate escalation and determines if the fix requires single or multi-file modifications.

Phase 2: Repository Analysis & AI Prompting

  • List Repo Files: Makes an API call to GitLab to fetch the entire repository tree structure.
  • Identify Affected Files: If the file isn't explicitly named, Gemini is provided with the repo tree and the bug description to deduce which files require patching.
  • Decode Files: Fetches the actual base64 content of the target files from GitLab and decodes them for local manipulation.
  • Build AI Prompt: Constructs a highly specific prompt containing the bug description, the repository context, and the raw code of the files, enforcing a strict GNU unified diff output format.

Phase 3: AI Generation & Application

  • Call Google Gemini: Sends the context to gemini-flash-latest configured with a low temperature (0.1) for deterministic, code-focused output.
  • Parse & Apply Diff Patch: Strips markdown fences, parses the unified diff formatting (@@ -X,Y +A,B @@), and applies the mathematical offsets to inject the fixed code into the original source strings.
  • Code Syntax Guard: Runs strict Regex checks against the patched code based on file extensions to ensure structural validity.

Phase 4: Validation & Deployment

  • Pre-Flight Evaluate: A secondary Gemini call reviews the applied patch. If it detects severe logic or security flaws, the pipeline is blocked.
  • GitLab API Integration: * Fetches the main branch SHA.
    • Creates a new branch (e.g., fix/INC000).
    • Encodes the patched files back to base64.
    • Commits the changes using the GitLab Commits API.
    • Automatically opens a Merge Request detailing the AI's changes.

Tech Stack & Requirements

Component Technology / Platform
Automation Engine n8n
AI / LLM Google Gemini (PaLM API) gemini-flash-latest
Source Control GitLab API v4
ITSM Trigger ServiceNow (via Webhook)
Scripting Node.js (inside n8n Code Nodes)

Getting Started

Prerequisites

  • n8n Instance: Self-hosted or Cloud version capable of importing JSON workflows.
  • GitLab Account: An API access token with api and write_repository scopes.
  • Google Gemini API Key: Access to Google AI Studio for PaLM/Gemini API credentials.
  • ServiceNow Instance: Configured to fire outbound REST Webhooks on incident creation.

Installation

  1. Download the workflow.json file.
  2. Open your n8n workspace, click Add Workflow, select the dropdown menu in the top right, and choose Import from File.
  3. Select the downloaded JSON file.
  4. Configure Credentials:
    • Open the Call Google Gemini node and configure your googlePalmApi credentials.
    • Open the GitLab nodes (e.g., Get Main Branch, Commit Code) and select your gitlabApi credentials.
  5. Update Variables:
    • In the Extract Issue Data node, update the gitlabNamespace and gitlabRepo variables to point to your target repository.
  6. Activate the Workflow using the toggle in the top right of the n8n UI. Ensure your webhooks in ServiceNow and GitLab are pointing to the provided n8n Webhook URLs.

ServiceNow Configuration (Webhook Setup)

To trigger the automated pipeline, ServiceNow must be configured to push new incidents to your n8n instance.

  1. Create an Outbound REST Message:
    • Navigate to System Web Services > Outbound > REST Message.
    • Name it n8n AI Automation and set the Endpoint to the Production URL from your first n8n Webhook node.
    • Create an HTTP Method (POST) and configure the HTTP Request to send application/json.
  2. Create a Business Rule:
    • Navigate to System Definition > Business Rules.
    • Create a rule on the Incident table. Set it to run after an Insert or Update (e.g., condition: Assignment group changes to AI Automation).
  3. Advanced Scripting:
    • In the Advanced tab, write a script to execute the REST message, passing the required fields as a JSON payload:
var request = new sn_ws.RESTMessageV2('n8n AI Automation', 'POST');
var body = {
    "issue_key": current.number.toString(),
    "summary": current.short_description.toString(),
    "description": current.description.toString()
};
request.setRequestBody(JSON.stringify(body));
request.execute();

GitLab Webhook Configuration (Feedback Loop)

To enable the AI agent to automatically respond to human reviewer feedback on Merge Requests, configure the following webhook in your GitLab repository.

Step 1: Navigate to Webhooks

Go to:

GitLab Repository
→ Settings
→ Webhooks

Step 2: Configure Webhook URL

Set the webhook URL to the Production URL generated by the MR Comment Webhook node inside n8n.

Example:

https://your-n8n-instance/webhook/gitlab-mr-feedback

Step 3: Enable Trigger Events

Under Trigger, enable:

  • ✅ Comments
    Captures Note Events when reviewers leave feedback on Merge Requests.

  • ✅ Merge Request Events
    Provides contextual information regarding the Merge Request state.

Step 4: Save Configuration

Click:

Add Webhook

The AI agent can now:

  1. Read reviewer comments
  2. Interpret requested changes
  3. Generate updated patches
  4. Commit fixes automatically
  5. Push revised code to the existing Merge Request

Branching Strategy Configuration

By default, this workflow creates branches from main and merges changes back into main.

If your repository uses another default branch such as:

master
develop
production
staging

you must update the following n8n nodes.


1. Update "Get Main Branch" Node

Open:

Get Main Branch

Change:

.../branches/main

to:

.../branches/master

(or your target branch)


2. Update "Create Branch" Node

Open:

{
  "ref": "main"
}

Change to:

{
  "ref": "master"
}

Replace master with your repository's default branch.


3. Update "Create PR" Node

Open Body Parameters and change:

target_branch = main

to:

target_branch = master

(or your target branch)


Important

All three nodes must reference the same default branch.

Incorrect branch configuration may cause:

  • Failed Merge Requests
  • Invalid branch creation
  • Broken deployment workflows
  • Commits targeting nonexistent branches

Supported Branch Workflows

Examples:

Repository Strategy Configure Branch As
GitHub Standard main
Legacy Git master
GitFlow develop
Production Workflow production
Custom Teams Your internal branch

After configuration, activate the workflow and verify:

ServiceNow → n8n → AI Patch Generation → GitLab Branch → Merge Request → Reviewer Feedback → Auto Fix Loop

The pipeline is now fully autonomous.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors