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.
- 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 blameto find the last human contributor and creates a GitLab Issue escalating the problem for manual review.
The pipeline is triggered by incoming webhooks (either from ServiceNow or GitLab comments) and executes through several distinct phases:
- 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.
- 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.
- Call Google Gemini: Sends the context to
gemini-flash-latestconfigured 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.
- 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.
- Creates a new branch (e.g.,
| 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) |
- n8n Instance: Self-hosted or Cloud version capable of importing JSON workflows.
- GitLab Account: An API access token with
apiandwrite_repositoryscopes. - 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.
- Download the
workflow.jsonfile. - Open your n8n workspace, click Add Workflow, select the dropdown menu in the top right, and choose Import from File.
- Select the downloaded JSON file.
- Configure Credentials:
- Open the Call Google Gemini node and configure your
googlePalmApicredentials. - Open the GitLab nodes (e.g., Get Main Branch, Commit Code) and select your
gitlabApicredentials.
- Open the Call Google Gemini node and configure your
- Update Variables:
- In the Extract Issue Data node, update the
gitlabNamespaceandgitlabRepovariables to point to your target repository.
- In the Extract Issue Data node, update the
- 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.
To trigger the automated pipeline, ServiceNow must be configured to push new incidents to your n8n instance.
- Create an Outbound REST Message:
- Navigate to System Web Services > Outbound > REST Message.
- Name it
n8n AI Automationand 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.
- Create a Business Rule:
- Navigate to System Definition > Business Rules.
- Create a rule on the
Incidenttable. Set it to run after an Insert or Update (e.g., condition:Assignment groupchanges toAI Automation).
- 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();To enable the AI agent to automatically respond to human reviewer feedback on Merge Requests, configure the following webhook in your GitLab repository.
Go to:
GitLab Repository
→ Settings
→ Webhooks
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
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.
Click:
Add Webhook
The AI agent can now:
- Read reviewer comments
- Interpret requested changes
- Generate updated patches
- Commit fixes automatically
- Push revised code to the existing Merge Request
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.
Open:
Get Main Branch
Change:
.../branches/main
to:
.../branches/master
(or your target branch)
Open:
{
"ref": "main"
}Change to:
{
"ref": "master"
}Replace master with your repository's default branch.
Open Body Parameters and change:
target_branch = main
to:
target_branch = master
(or your target branch)
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
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.