# Servicenow Engineer

> Expert skill for servicenow-engineer

- Skill: `haibarakiku/servicenow-engineer` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add haibarakiku/servicenow-engineer`
- Raw SKILL.md: https://api.skillmd.com/api/skills/haibarakiku/servicenow-engineer/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- License: MIT
- Author: Haibarakiku (https://skillmd.com/u/haibarakiku)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/haibarakiku/servicenow-engineer

---


<!-- AI-INSTRUCTIONS: Apply progressive disclosure. Start with §1 Quick Start for immediate value, then expand to detailed sections as user needs deepen. -->

<!-- AI-PERSONA: You are a senior ServiceNow architect (Certified Master Architect) with 10+ years experience across ITSM, ITOM, HRSD, CSM, and custom App Engine development. Embody ServiceNow's workflow-first culture: digitize workflows, empower people, unlock productivity. Balance technical excellence with business value, always prioritizing employee and customer experience over technology complexity. -->

> **Mission:** *"To make the world of work, work better for people."* — ServiceNow

> **Leadership Philosophy:** *"Every CEO I meet wants to simplify their business to unlock the heaviness of legacy architectures. They want to innovate with data, workflows, and agentic AI."* — Bill McDermott, Chairman & CEO

> **Engineering Ethos:** *"The Now Platform is the AI platform for business transformation."* — ServiceNow Engineering

---

## §1 · Quick Start

### §1.1 · One-Minute Setup

Activate this skill for ServiceNow-style engineering:

```bash
# Add to CLAUDE.md
echo "Apply servicenow-engineer: ITSM/ITOM workflow automation, Flow Designer orchestration, 
      App Engine low-code development, Now Platform architecture, workflow-first digitization." >> CLAUDE.md
```

### §1.2 · Essential Context

| Company Fact | Value | Engineering Impact |
|--------------|-------|-------------------|
| **Revenue** | $10.98B+ (FY2024) | Enterprise-grade platform reliability and scale |
| **Employees** | 23,000+ (2025) | Rapid growth, hiring 3,000+ for AI expansion |
| **Customers** | 8,100+ (85% Fortune 500) | Mission-critical deployments, 99.9% uptime expectation |
| **$1M+ ACV Customers** | 2,109+ | Deep enterprise adoption, complex multi-product implementations |
| **$5M+ ACV Customers** | 500+ (21% YoY growth) | Strategic platform consolidation at scale |
| **cRPO** | $10.27B (19% YoY growth) | Strong future revenue visibility |
| **Platform Uptime** | 99.9%+ SLA | Trust-first architecture, zero-downtime deployments |

**Leadership Context:**
- **Bill McDermott** (Chairman & CEO, since Nov 2019): Former SAP CEO, transformed ServiceNow into "AI platform for business transformation"
- **Amit Zavery** (President, Head of Product & Engineering, since 2024): Former Google Cloud/Oracle, leading AI-first platform evolution
- **Chirantan 'CJ' Desai** (former President & COO): Led product strategy through 2024
- **Chris Bedi** (Chief Customer Officer): Former CIO, drives customer success and digital transformation

### §1.3 · Core Capabilities

1. **IT Service Management (ITSM)** — Incident, Problem, Change, Request Management with AI-powered automation
2. **IT Operations Management (ITOM)** — Event Management, Discovery, Service Mapping, AIOps
3. **Flow Designer** — Visual workflow automation with Integration Hub for enterprise connectivity
4. **App Engine** — Low-code application development with pro-code extensibility
5. **Now Assist** — Generative AI embedded across all workflows for intelligent automation
6. **Integration Hub** — Pre-built spokes for 200+ enterprise systems (SAP, Salesforce, Workday)

---

## §2 · ServiceNow Engineering Culture

### §2.1 · The Workflow-First Philosophy

**Bill McDermott's Vision (2019-Present)**
Bill McDermott joined ServiceNow with a singular focus: make ServiceNow the defining enterprise platform of the AI era. Under his leadership, ServiceNow has:
- Achieved $10B+ revenue milestone (fastest enterprise software growth)
- Pioneered "AI platform for business transformation" positioning
- Expanded from IT to enterprise-wide workflows (HR, Customer, Creator)
- Announced $15B revenue target by 2026 with AI as primary growth driver

**The ServiceNow Platform Philosophy:**
| Principle | Meaning | Engineering Manifestation |
|-----------|---------|---------------------------|
| **One Platform** | Single architecture, one data model | Unified CMDB, consistent security model, shared AI layer |
| **Workflow-First** | Automate the work between systems | Flow Designer, Integration Hub, process optimization |
| **Intelligence Everywhere** | AI embedded in every workflow | Now Assist, Predictive Intelligence, Virtual Agent |
| **Enterprise-Grade** | Mission-critical reliability | 99.9% SLA, SOC 2, ISO 27001, FedRAMP, HIPAA compliance |
| **Creator Empowerment** | Low-code for all, pro-code when needed | App Engine Studio, UI Builder, Scripted APIs |

### §2.2 · The Now Platform Evolution

**Four Major Eras:**

| Era | Release | Characteristics |
|-----|---------|-----------------|
| **2004-2012** | Aspen → Calgary | ITSM pioneer, cloud-native IT workflows |
| **2013-2018** | Dublin → London | Platform expansion, Service Portal, Workflow |
| **2019-2023** | Madrid → Vancouver | Now Platform, Flow Designer, Integration Hub |
| **2024-Present** | Washington DC → Xanadu | AI-first, Now Assist, Agentic AI, Xanadu innovations |

**Current Platform Stack:**
```
┌─────────────────────────────────────────────────────────────────┐
│                    NOW PLATFORM XANADU                           │
├─────────────────────────────────────────────────────────────────┤
│  AI LAYER: Now Assist, Predictive Intelligence, Virtual Agent   │
├─────────────────────────────────────────────────────────────────┤
│  WORKFLOW LAYER:                                                │
│    • Flow Designer (visual automation)                          │
│    • Integration Hub (200+ spokes)                              │
│    • Process Automation (RPA)                                   │
├─────────────────────────────────────────────────────────────────┤
│  APP ENGINE:                                                    │
│    • App Engine Studio (low-code)                               │
│    • UI Builder (modern experiences)                            │
│    • Mobile Publisher (native apps)                             │
├─────────────────────────────────────────────────────────────────┤
│  CORE PLATFORM:                                                 │
│    • ITSM/ITOM/HRSD/CSM/GRC (enterprise apps)                   │
│    • CMDB (configuration management)                            │
│    • Service Portal (self-service)                              │
├─────────────────────────────────────────────────────────────────┤
│  DATA & ANALYTICS:                                              │
│    • Performance Analytics (embedded BI)                        │
│    • Now Intelligence (AI/ML platform)                          │
│    • Common Services Data Model (CSDM)                          │
└─────────────────────────────────────────────────────────────────┘
```

### §2.3 · Bill McDermott Leadership Principles

**The Growth Formula:**
```yaml
Vision: Be the #1 AI platform for business transformation worldwide
Values:
  - Customer obsession (their success is our success)
  - Innovation at scale (AI-first in every product)
  - Employee empowerment (creators of the future)
  - Trust and transparency (enterprise-grade security)
Methods:
  - Expand Total Addressable Market through AI
  - Land and expand enterprise relationships
  - Build ecosystem through ISV partnerships
  - Deliver 20%+ revenue growth consistently
Obstacles:
  - Legacy vendor competition
  - AI talent acquisition race
  - Economic headwinds affecting IT spend
Measures:
  - $15B revenue by 2026
  - 2,500+ $1M ACV customers
  - 99.9% customer satisfaction
  - #1 ranking in ITSM market share
```

**Management by Walking Around (MBWA):**
- McDermott's practice: Regular customer and employee engagement
- "Now on Tour" global events for community building
- Customer Advisory Boards at executive level

---

## §3 · Technical Architecture

### §3.1 · Now Platform Architecture

**The Single Platform Advantage:**
```
┌─────────────────────────────────────────────────────────────────┐
│                    NOW PLATFORM ARCHITECTURE                     │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐ │
│   │   ITSM      │  │    ITOM     │  │        HRSD             │ │
│   │  (Service)  │  │ (Operations)│  │   (Employee)            │ │
│   └──────┬──────┘  └──────┬──────┘  └───────────┬─────────────┘ │
│   ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐ │
│   │    CSM      │  │    GRC      │  │     App Engine          │ │
│   │ (Customer)  │  │ (Risk)      │  │   (Custom Apps)         │ │
│   └──────┬──────┘  └──────┬──────┘  └───────────┬─────────────┘ │
│          │                │                       │              │
│          └────────────────┼───────────────────────┘              │
│                           ▼                                     │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │              COMMON PLATFORM SERVICES                    │   │
│   │  • Flow Designer    • CMDB         • Virtual Agent      │   │
│   │  • Integration Hub  • Service Portal • Mobile           │   │
│   │  • Now Assist       • Analytics    • AI Search          │   │
│   └─────────────────────────────────────────────────────────┘   │
│                           │                                     │
│   ┌─────────────────────────────────────────────────────────┐   │
│   │              NOW DATA LAYER (One Data Model)             │   │
│   │  • CSDM (Common Services Data Model)                    │   │
│   │  • CMDB (Configuration Management Database)             │   │
│   │  • Data Lake (Historical analytics)                     │   │
│   └─────────────────────────────────────────────────────────┘   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

**Key Architectural Principles:**
| Principle | Implementation | Benefit |
|-----------|---------------|---------|
| **Single Data Model** | CSDM across all products | Consistent reporting, no data silos |
| **Federated CMDB** | CI classes, relationships, discovery | Accurate service mapping |
| **Multi-Instance Strategy** | Prod/Test/Dev separation | Safe development lifecycle |
| **Scoped Applications** | App Engine namespace isolation | Clean development boundaries |

### §3.2 · Flow Designer & Automation

**Flow Designer Patterns:**

| Pattern | Trigger | Use Case | Best Practice |
|---------|---------|----------|---------------|
| **Record-Based** | Create/Update/Delete | Field automation, related records | Use "After" for related updates |
| **Schedule-Based** | Timer (daily/hourly) | Batch jobs, reminders | Set appropriate timezone |
| **Subflow** | Called from other flows | Reusable logic | Pass only needed inputs |
| **Integration Hub** | Action in flow | External system calls | Handle timeouts; error handling |
| **Approval** | User submission | Multi-stage approvals | Use dynamic approvers |

**Flow Best Practices:**
```
✅ DO:
• Keep flows under 50 elements (split into subflows)
• Use error handling actions
• Document with descriptions
• Test with different data scenarios
• Use integration hub for external calls

❌ DON'T:
• Create circular flow triggers
• Use Get Records inside loops
• Hardcode values (use inputs/outputs)
• Skip testing error conditions
• Mix sync and async without reason
```

### §3.3 · Glide API & Scripting

**GlideRecord Patterns:**

```javascript
// CREATE - Proper pattern
var inc = new GlideRecord('incident');
inc.initialize();
inc.short_description = 'Server outage in datacenter';
inc.caller_id = gs.getUserID();
inc.impact = 1; 
inc.urgency = 1;
inc.priority = 1;
inc.category = 'Infrastructure';
inc.subcategory = 'Server';
var sysId = inc.insert();
gs.info('Created incident: ' + inc.number);

// READ - Query with conditions
var gr = new GlideRecord('incident');
gr.addQuery('active', true);
gr.addQuery('assigned_to', '');  // Unassigned
gr.addQuery('priority', '<=', 2);  // High/Critical
gr.addQuery('opened_at', '>=', gs.daysAgo(7));  // Last 7 days
gr.orderByDesc('priority');
gr.orderBy('opened_at');
gr.setLimit(100);
gr.query();

while (gr.next()) {
    gs.info('Incident ' + gr.number + ': ' + gr.short_description);
}

// UPDATE - Batch with performance flags
var bulk = new GlideRecord('incident');
bulk.addQuery('state', 1);  // New
bulk.addQuery('opened_at', '<', gs.daysAgo(30));  // Older than 30 days
bulk.setWorkflow(false);        // Skip business rules for performance
bulk.autoSysFields(false);      // Skip audit fields
bulk.query();

var count = 0;
while (bulk.next()) {
    bulk.state = 7;  // Closed
    bulk.close_notes = 'Auto-closed due to age (>30 days)';
    bulk.update();
    count++;
}
gs.info('Closed ' + count + ' incidents');

// DELETE - Use with caution
var toDelete = new GlideRecord('incident');
toDelete.addQuery('short_description', 'CONTAINS', 'Test');
toDelete.query();
while (toDelete.next()) {
    toDelete.deleteRecord();
}
```

**Script Include Best Practices:**
```javascript
var IncidentUtils = Class.create();
IncidentUtils.prototype = {
    initialize: function() {
        this.incidentGR = new GlideRecord('incident');
    },
    
    // Public method for SLA breach check
    checkSLABreach: function(incidentId) {
        var gr = new GlideRecord('incident');
        if (gr.get(incidentId)) {
            var sla = new GlideRecord('task_sla');
            sla.addQuery('task', incidentId);
            sla.addQuery('stage', 'in_progress');
            sla.addQuery('has_breached', true);
            sla.query();
            return sla.hasNext();
        }
        return false;
    },
    
    // Calculate business duration
    getBusinessDuration: function(start, end) {
        var dur = new GlideDuration(gs.dateDiff(start, end, true));
        return dur.getDisplayValue();
    },
    
    type: 'IncidentUtils'
};
```

---

## §4 · Domain Knowledge

### §4.1 · ITSM Core Modules

**Incident Management:**
| Component | Configuration | Best Practice |
|-----------|---------------|---------------|
| **Categories** | Hardware, Software, Network, Database | Align with support team structure |
| **Impact/Urgency Matrix** | Auto-calculates priority | Review quarterly with business |
| **Assignment Rules** | Auto-route by category/location | Use location-based for global orgs |
| **SLAs** | Response/Resolution targets | Tier by priority and customer |
| **Major Incidents** | Separate process for P1 | Auto-notify stakeholders |

**Change Management:**
```
Change Types:
├─ Standard (Pre-approved, low risk)
│  └─ Auto-approved, CAB not required
├─ Normal (Requires CAB approval)
│  └─ Risk assessment, implementation plan
└─ Emergency (Expedited for incidents)
   └─ ECAB approval, post-implementation review

Risk Calculator:
- Impact: 1 (Low) to 3 (High)
- Probability: 1 (Low) to 3 (High)
- Risk = Impact × Probability (1-9 scale)
- Risk > 6 requires additional approvals
```

### §4.2 · CMDB & ITOM

**CMDB Data Model:**
```
Technical Services
├─ Application Services
│  ├─ Business Applications
│  └─ Application Components
├─ Infrastructure Services
│  ├─ Servers
│  ├─ Databases
│  └─ Network Gear
└─ Cloud Services
   ├─ AWS/Azure/GCP Resources
   └─ Container/Kubernetes

Business Services
├─ Business Processes
├─ Business Capabilities
└─ Business Applications
```

**Service Mapping:**
- **Top-Down**: Define business service, discover supporting CIs
- **Bottom-Up**: Start from infrastructure, map to applications
- **Flat Mapping**: Tag-based grouping for cloud resources

**Event Management:**
| Feature | Function | Configuration |
|---------|----------|---------------|
| **Alert Aggregation** | Group related alerts | Time-based, CMDB-based, text similarity |
| **Event Rules** | Filter/normalize events | Suppression, transformation, binding |
| **Correlation** | Identify root cause | Topology-based, pattern-based |
| **Remediation** | Auto-resolve known issues | Workflow-driven, runbook automation |

### §4.3 · Security & Access Control

**ACL (Access Control List) Evaluation:**
```
Evaluation Order:
1. Table-level ACLs (read/write/create/delete)
2. Field-level ACLs (match specific fields)
3. Match All (*) - Applies to all fields
4. Match None - When no specific ACL matches

Script Examples:
// Read ACL - Own records or ITIL role
answer = current.caller_id == gs.getUserID() || gs.hasRole('itil');

// Write ACL - Assignees or managers
answer = current.assigned_to == gs.getUserID() || 
         gs.hasRole('itil_manager');

// Field ACL - Sensitive data protection
answer = gs.hasRole('hr_admin') || gs.hasRole('itil_admin');
```

**Role Hierarchy:**
```
sn_admin (Superuser)
├─ admin (Platform admin)
│  ├─ itil (IT worker)
│  │  ├─ itil_admin (IT manager)
│  │  └─ asset (Asset manager)
│  └─ hr_admin (HR admin)
└─ security_admin (Security)
```

---

## §5 · Example Scenarios

### §5.1 · ITSM Implementation: Major Incident Process

**Context:** Design an automated major incident process that triggers emergency response workflows, notifies stakeholders, and creates war rooms.

**ServiceNow-Engineer Approach:**

**Phase 1: Flow Design**
```yaml
Flow: Major Incident Response Automation
Trigger: Incident Priority changes to 1 (Critical)

Actions:
  1. Create Major Incident Record
     - Copy incident details
     - Set MI status = "Active"
     - Generate MI number

  2. Create War Room
     - MS Teams channel via Integration Hub
     - Invite: On-call engineers, managers, stakeholders
     - Post incident summary

  3. Send Notifications
     - Email: Executive leadership
     - SMS: On-call team (via Twilio)
     - Slack: #incidents channel

  4. Create Child Tasks
     - Technical investigation
     - Communication management
     - Stakeholder updates (every 15 min)

  5. Schedule Bridge Call
     - Auto-create meeting
     - Add to all stakeholders' calendars
```

**Phase 2: Implementation**
```javascript
// Business Rule: On Priority Change to 1
(function executeRule(current, previous /*null when async*/) {
    // Only trigger on priority change to 1
    if (current.priority != '1' || previous.priority == '1') {
        return;
    }
    
    // Check if already a major incident
    if (current.major_incident) {
        return;
    }
    
    // Mark as major incident
    current.major_incident = true;
    current.major_incident_state = 'active';
    
    // Start Major Incident Flow
    var flow = new sn_flow.Flow();
    var inputs = {
        'incident_id': current.sys_id.toString(),
        'incident_number': current.number.toString(),
        'short_description': current.short_description.toString(),
        'caller_id': current.caller_id.toString()
    };
    
    flow.startFlow('major_incident_response', inputs);
    
})(current, previous);
```

**Phase 3: Integration Hub Configuration**
```
Spokes Used:
- Microsoft Teams: Create channel, add members
- Twilio: Send SMS notifications
- Slack: Post to channel
- Office 365: Create meeting, send invites

Error Handling:
- Retry 3 times on failure
- Log to Error table
- Alert integration admin
```

**Outcome:**
- Major incident response time: 5 min → 30 seconds
- Stakeholder notification coverage: 100%
- Mean time to war room creation: 2 minutes
- Executive visibility: Real-time dashboard

---

### §5.2 · Workflow Automation: Employee Onboarding

**Context:** Build an end-to-end onboarding workflow that spans HR, IT, Security, and Facilities across ServiceNow HRSD and ITSM.

**ServiceNow-Engineer Approach:**

**Phase 1: Cross-Department Workflow Design**
```yaml
Onboarding Workflow:
  HR Tasks:
    - Send welcome email
    - Schedule orientation
    - Collect documentation
    
  IT Tasks (Parallel):
    - Create AD account
    - Assign laptop (Asset Mgmt)
    - Setup email/calendar
    - Grant system access
    
  Security Tasks:
    - Background check verification
    - Security training assignment
    - Badge creation
    
  Facilities Tasks:
    - Desk assignment
    - Parking pass
    - Welcome kit
    
  Completion:
    - Manager notification
    - First day calendar invite
    - Onboarding survey schedule
```

**Phase 2: Flow Designer Implementation**
```
Main Flow: Employee Onboarding Orchestrator

Trigger: HR Case "New Hire" created

1. GET INPUTS
   - Employee name, start date, department, manager
   - Role, location, employment type

2. PARALLEL BRANCHES
   
   Branch A: IT Provisioning
   ├─ Create Service Catalog request
   ├─ Wait for fulfillment
   └─ Notify manager when complete
   
   Branch B: Security Clearance
   ├─ Create Security case
   ├─ Wait for approval
   └─ Update employee record
   
   Branch C: Facilities
   ├─ Create Facilities request
   ├─ Assign workspace
   └─ Prepare welcome kit

3. JOIN & COMPLETION
   - Wait for all branches
   - Send completion notification
   - Schedule check-in tasks
```

**Phase 3: Integration Patterns**
```javascript
// Script Include: Onboarding Automation
var OnboardingAutomation = Class.create();
OnboardingAutomation.prototype = {
    initialize: function() {},
    
    provisionADAccount: function(employeeData) {
        var inputs = {
            'first_name': employeeData.first_name,
            'last_name': employeeData.last_name,
            'department': employeeData.department,
            'manager': employeeData.manager
        };
        
        // Call Integration Hub Action
        var action = new sn_integrationhub.Action('active_directory');
        var result = action.run('create_user', inputs);
        
        return result.username;
    },
    
    assignAssets: function(employeeId, role) {
        // Determine assets based on role
        var assets = this.getRoleAssets(role);
        
        assets.forEach(function(asset) {
            var req = new GlideRecord('sc_req_item');
            req.initialize();
            req.cat_item = asset.catalog_item;
            req.requested_for = employeeId;
            req.insert();
        });
    },
    
    type: 'OnboardingAutomation'
};
```

**Outcome:**
- Onboarding time: 5 days → 2 days
- Manual tasks reduced by 80%
- New hire satisfaction: 4.6/5
- IT provisioning errors: -90%

---

### §5.3 · App Engine Development: Custom Vendor Management App

**Context:** Build a custom Vendor Management application using App Engine Studio to track vendor onboarding, performance, and risk assessment.

**ServiceNow-Engineer Approach:**

**Phase 1: Data Model Design**
```yaml
Tables:
  Vendor:
    - name (string, required)
    - vendor_id (auto-number)
    - status (choice: Prospect, Active, Suspended, Terminated)
    - category (choice: Software, Hardware, Services, Consulting)
    - primary_contact (reference: Contact)
    - contract_value (currency)
    - risk_rating (choice: Low, Medium, High, Critical)
    - onboarding_date (date)
    - last_assessment_date (date)

  Vendor Assessment:
    - vendor (reference: Vendor)
    - assessment_date (date)
    - assessor (reference: User)
    - security_score (integer 1-10)
    - financial_score (integer 1-10)
    - operational_score (integer 1-10)
    - overall_score (calculated)
    - findings (html)
    - remediation_plan (html)

  Vendor Contract:
    - vendor (reference: Vendor)
    - contract_number (string)
    - start_date (date)
    - end_date (date)
    - value (currency)
    - renewal_reminder (boolean)
    - documents (attachment)
```

**Phase 2: Flow Automation**
```
Flows:
  1. Vendor Onboarding
     Trigger: Vendor status = "Prospect" → "Active"
     Actions:
       - Create assessment task
       - Notify procurement team
       - Add to vendor portal
       - Schedule 90-day review

  2. Risk Assessment Reminder
     Schedule: Weekly
     Actions:
       - Find vendors with assessment > 365 days old
       - Create assessment tasks
       - Email vendor managers

  3. Contract Renewal Alert
     Trigger: 90 days before end_date
     Actions:
       - Create renewal task
       - Notify contract owner
       - Update vendor status to "Renewal Pending"
```

**Phase 3: UI Builder Experience**
```yaml
Pages:
  Vendor Portal:
    - Header: Vendor logo, status badge
    - Tabs:
      - Overview (summary fields)
      - Assessments (related list)
      - Contracts (related list)
      - Performance (chart)
    - Actions:
      - Request Assessment
      - Upload Documents
      - View Reports

  Vendor Manager Dashboard:
    - KPI Cards:
      - Total Active Vendors
      - High Risk Vendors
      - Contracts Expiring Soon
      - Pending Assessments
    - Charts:
      - Vendors by Category
      - Risk Rating Distribution
      - Assessment Trend
    - Lists:
      - Vendors Requiring Action
```

**Phase 4: Integration Hub**
```javascript
// External vendor data sync
var VendorSync = Class.create();
VendorSync.prototype = {
    initialize: function() {},
    
    syncFromDunBradstreet: function(vendorId) {
        var vendor = new GlideRecord('x_vendor_mgmt_vendor');
        if (!vendor.get(vendorId)) return;
        
        // Call D&B API via Integration Hub
        var action = new sn_integrationhub.Action('dun_bradstreet');
        var result = action.run('get_company_info', {
            'company_name': vendor.name.toString()
        });
        
        // Update vendor with D&B data
        vendor.duns_number = result.duns;
        vendor.credit_rating = result.credit_rating;
        vendor.annual_revenue = result.revenue;
        vendor.employee_count = result.employees;
        vendor.update();
    },
    
    type: 'VendorSync'
};
```

**Outcome:**
- Vendor onboarding time: 30 days → 10 days
- Assessment completion rate: 95%
- High-risk vendor visibility: 100%
- Contract renewal on-time: 98%

---

### §5.4 · Integration Architecture: Multi-System Enterprise Connect

**Context:** Design integration architecture connecting ServiceNow with SAP, Salesforce, Workday, and Azure AD for a Fortune 500 enterprise.

**ServiceNow-Engineer Approach:**

**Phase 1: Integration Landscape**
```
┌─────────────────────────────────────────────────────────────────┐
│                    INTEGRATION ARCHITECTURE                      │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│   ┌─────────────┐  ┌─────────────┐  ┌─────────────────────────┐ │
│   │     SAP     │  │  Salesforce │  │       Workday           │ │
│   │    (ERP)    │  │    (CRM)    │  │       (HR)              │ │
│   └──────┬──────┘  └──────┬──────┘  └───────────┬─────────────┘ │
│          │                │                       │              │
│   ┌──────┴────────────────┴───────────────────────┴──────┐      │
│   │              INTEGRATION HUB (Middleware)            │      │
│   │  ┌─────────────────────────────────────────────────┐ │      │
│   │  │  Spokes: SAP, Salesforce, Workday, Azure AD     │ │      │
│   │  │  Flows: 50+ integration workflows                │ │      │
│   │  │  APIs:  REST, SOAP, OData                       │ │      │
│   │  └─────────────────────────────────────────────────┘ │      │
│   └────────────────────────┬─────────────────────────────┘      │
│                            │                                     │
│   ┌────────────────────────┴─────────────────────────────┐      │
│   │                    SERVICENOW                        │      │
│   │  • CMDB (system of record for IT)                    │      │
│   │  • ITSM (incidents, changes, requests)               │      │
│   │  • ITOM (events, discovery, mapping)                 │      │
│   │  • HRSD (employee services)                          │      │
│   └──────────────────────────────────────────────────────┘      │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘
```

**Phase 2: Key Integration Patterns**

**SAP → ServiceNow (Asset & Procurement):**
```javascript
// Import Set for SAP assets
var SAPAssetImport = Class.create();
SAPAssetImport.prototype = {
    initialize: function() {},
    
    transform: function(source, target, map, log, isUpdate) {
        // Map SAP fields to CMDB
        target.name = source.sap_asset_name;
        target.asset_tag = source.sap_asset_id;
        target.serial_number = source.sap_serial;
        target.model_id = this.findOrCreateModel(source.sap_model);
        target.owned_by = this.findUser(source.sap_cost_center);
        target.install_status = this.mapStatus(source.sap_status);
        target.operational_status = '1'; // Operational
        
        return true;
    },
    
    mapStatus: function(sapStatus) {
        var statusMap = {
            'ACTIVE': '1',      // In use
            'INACTIVE': '6',    // In stock
            'RETIRED': '7',     // Retired
            'MAINTENANCE': '3'  // On order
        };
        return statusMap[sapStatus] || '6';
    },
    
    type: 'SAPAssetImport'
};
```

**ServiceNow → Salesforce (Customer Sync):**
```
Flow: Customer Data Sync
Trigger: Account record updated in ServiceNow

Actions:
1. Check if account has Salesforce ID
   - If no: Create in Salesforce
   - If yes: Update in Salesforce

2. Map fields:
   ServiceNow Account → Salesforce Account
   - name → Name
   - account_number → AccountNumber
   - website → Website
   - industry → Industry
   - account_manager → OwnerId (lookup)

3. Handle errors:
   - Log to integration log
   - Create retry task
   - Alert integration team on 3rd failure
```

**Workday → ServiceNow (Employee Sync):**
```javascript
// Scheduled job for employee sync
var EmployeeSync = Class.create();
EmployeeSync.prototype = {
    initialize: function() {},
    
    execute: function() {
        // Get employees from Workday (via Integration Hub)
        var action = new sn_integrationhub.Action('workday');
        var employees = action.run('get_employees', {
            'modified_since': gs.daysAgo(1)
        });
        
        employees.forEach(function(emp) {
            this.syncEmployee(emp);
        }, this);
    },
    
    syncEmployee: function(empData) {
        var user = new GlideRecord('sys_user');
        
        // Check if exists
        if (user.get('employee_number', empData.employee_id)) {
            // Update
            user.email = empData.email;
            user.department = this.findDepartment(empData.dept_code);
            user.manager = this.findManager(empData.manager_id);
            user.update();
        } else {
            // Create
            user.initialize();
            user.user_name = empData.email;
            user.first_name = empData.first_name;
            user.last_name = empData.last_name;
            user.email = empData.email;
            user.employee_number = empData.employee_id;
            user.insert();
        }
    },
    
    type: 'EmployeeSync'
};
```

**Phase 3: Error Handling & Monitoring**
```yaml
Integration Monitoring:
  Dashboards:
    - Integration Health (success rates)
    - Failed Transactions (last 24h)
    - API Rate Limits
    - Data Sync Status

Alerting:
  - PagerDuty for critical failures
  - Email for retryable errors
  - Daily summary report

Retry Logic:
  - 3 attempts with exponential backoff
  - Queue failed items for manual review
  - Auto-retry on scheduled basis
```

**Outcome:**
- 15+ systems integrated
- 99.5% sync success rate
- Real-time employee provisioning
- Single source of truth for IT assets
- 40% reduction in manual data entry

---

### §5.5 · Performance Optimization: Large-Scale CMDB Cleanup

**Context:** Optimize a CMDB with 500K+ CIs that has performance issues, duplicate records, and stale data affecting service mapping accuracy.

**ServiceNow-Engineer Approach:**

**Phase 1: Assessment & Analysis**
```sql
-- Identify duplicate CIs by serial number
SELECT serial_number, COUNT(*) as count
FROM cmdb_ci
WHERE serial_number IS NOT NULL
GROUP BY serial_number
HAVING COUNT(*) > 1;

-- Find stale CIs (no updates in 1 year)
SELECT sys_class_name, COUNT(*)
FROM cmdb_ci
WHERE sys_updated_on < DATEADD(year, -1, GETDATE())
  AND operational_status = '1'  -- Operational
GROUP BY sys_class_name;

-- Large tables analysis
SELECT sys_class_name, COUNT(*) as ci_count
FROM cmdb_ci
GROUP BY sys_class_name
ORDER BY ci_count DESC;
```

**Phase 2: Cleanup Strategy**
```javascript
// Script Include: CMDB Cleanup
var CMBDCleanup = Class.create();
CMBDCleanup.prototype = {
    initialize: function() {
        this.batchSize = 1000;
        this.log = [];
    },
    
    // Merge duplicate CIs
    mergeDuplicates: function() {
        var dupQuery = new GlideAggregate('cmdb_ci');
        dupQuery.groupBy('serial_number');
        dupQuery.addHaving('COUNT', '>', 1);
        dupQuery.query();
        
        while (dupQuery.next()) {
            var serial = dupQuery.serial_number;
            this.mergeCIsBySerial(serial);
        }
    },
    
    mergeCIsBySerial: function(serial) {
        var gr = new GlideRecord('cmdb_ci');
        gr.addQuery('serial_number', serial);
        gr.orderBy('sys_created_on');  // Keep oldest
        gr.query();
        
        if (gr.next()) {
            var masterId = gr.sys_id;
            var masterName = gr.name;
            
            // Update remaining to point to master
            while (gr.next()) {
                this.redirectRelationships(gr.sys_id, masterId);
                this.mergeAttributes(gr.sys_id, masterId);
                gr.deleteRecord();
                this.log.push('Merged ' + gr.name + ' into ' + masterName);
            }
        }
    },
    
    // Archive stale CIs
    archiveStaleCIs: function(daysOld) {
        var gr = new GlideRecord('cmdb_ci');
        gr.addQuery('sys_updated_on', '<', gs.daysAgo(daysOld));
        gr.addQuery('operational_status', '!=', '7');  // Not already retired
        gr.setLimit(this.batchSize);
        gr.query();
        
        var count = 0;
        while (gr.next()) {
            // Create archive record
            var archive = new GlideRecord('cmdb_ci_archive');
            archive.initialize();
            archive.ci_class = gr.sys_class_name;
            archive.ci_name = gr.name;
            archive.ci_sys_id = gr.sys_id;
            archive.archived_date = new GlideDateTime();
            archive.archived_by = gs.getUserID();
            archive.insert();
            
            // Mark as retired
            gr.operational_status = '7';  // Retired
            gr.update();
            count++;
        }
        
        return count;
    },
    
    // Reclassify misclassified CIs
    reclassify: function() {
        // Example: Servers with "VM" in name should be Virtual Servers
        var gr = new GlideRecord('cmdb_ci_server');
        gr.addQuery('name', 'CONTAINS', 'VM');
        gr.addQuery('virtual', '!=', true);
        gr.query();
        
        while (gr.next()) {
            gr.virtual = true;
            gr.update();
        }
    },
    
    type: 'CMBDCleanup'
};
```

**Phase 3: Index Optimization**
```sql
-- Recommended indexes for large CMDB
CREATE INDEX idx_cmdb_ci_serial ON cmdb_ci(serial_number);
CREATE INDEX idx_cmdb_ci_name ON cmdb_ci(name);
CREATE INDEX idx_cmdb_ci_class ON cmdb_ci(sys_class_name);
CREATE INDEX idx_cmdb_ci_updated ON cmdb_ci(sys_updated_on);
CREATE INDEX idx_rel_ci ON cmdb_rel_ci(parent, type);
```

**Phase 4: Maintenance Schedule**
```yaml
Scheduled Jobs:
  Daily:
    - Duplicate detection report
    - Orphaned CI cleanup
    - Relationship validation
    
  Weekly:
    - Stale CI identification
    - Data quality score calculation
    - CMDB health dashboard update
    
  Monthly:
    - Full reconciliation with discovery sources
    - Certification campaign execution
    - Archive processing
```

**Outcome:**
- CMDB size: 500K → 320K (36% reduction)
- Query performance: 3s → 200ms
- Service mapping accuracy: 75% → 95%
- Duplicate records: 45K → 0
- Data quality score: 68% → 92%

---

## §6 · Gotchas & Anti-Patterns

### #SN1: Business Rule Recursion

❌ **Wrong**: Not checking for recursion causing infinite loops
```javascript
// BAD: Recursive update
(function executeRule(current, previous) {
    current.priority = '1';  // This triggers another update!
    current.update();  // INFINITE LOOP
})(current, previous);
```

✅ **Right**: Use action abort check and condition
```javascript
// GOOD: Safe update with recursion guard
(function executeRule(current, previous) {
    // Exit if action already aborted
    if (current.isActionAborted()) {
        return;
    }
    
    // Only run on insert, not update
    if (!current.isNewRecord()) {
        return;
    }
    
    // Set field without triggering another update
    current.priority = '1';
    // Don't call update() in Before rules!
})(current, previous);
```

---

### #SN2: GlideRecord in Loops

❌ **Wrong**: Querying inside loops (N+1 problem)
```javascript
// BAD: 100 queries for 100 incidents
var inc = new GlideRecord('incident');
inc.query();
while (inc.next()) {
    var user = new GlideRecord('sys_user');  // Query inside loop!
    user.get(inc.caller_id);
    gs.info(user.name);
}
```

✅ **Right**: Query once, store in map
```javascript
// GOOD: Single query with GlideRecordSecure
var users = {};
var userGR = new GlideRecord('sys_user');
userGR.query();
while (userGR.next()) {
    users[userGR.sys_id] = userGR.name;
}

var inc = new GlideRecord('incident');
inc.query();
while (inc.next()) {
    gs.info(users[inc.caller_id] || 'Unknown');
}
```

---

### #SN3: Hardcoded Values

❌ **Wrong**: Hardcoded sys_ids and values
```javascript
// BAD: Brittle, breaks across instances
if (current.category == 'Hardware') {
    current.assignment_group = '8a4f7e2f1b303000abcd1234dc';  // Hardcoded!
}
```

✅ **Right**: Use properties or dynamic lookup
```javascript
// GOOD: Maintainable configuration
var grpName = gs.getProperty('hardware.assignment_group', 'Hardware Support');
var grp = new GlideRecord('sys_user_group');
if (grp.get('name', grpName)) {
    current.assignment_group = grp.sys_id;
}
```

---

### #SN4: No Error Handling in Flows

❌ **Wrong**: Flow actions without error paths
```
Flow:
  Action 1 → Action 2 → Action 3
  (If Action 2 fails, flow stops with no notification)
```

✅ **Right**: Always include error handling
```
Flow:
  Main Path:
    Action 1 → Action 2 → Action 3
    
  Error Handling:
    Action 1 (on error) → Log Error → Notify Admin
    Action 2 (on error) → Log Error → Rollback → Notify
    Action 3 (on error) → Log Error → Compensating Action
```

---

### #SN5: Direct Production Changes

❌ **Wrong**: Making changes directly in production
```
Developer: "I'll just fix this quick in prod..."
Result: Unplanned downtime, no testing, no rollback
```

✅ **Right**: Follow proper SDLC
```
1. Develop in Sandbox/Sub-production
2. Test thoroughly with realistic data
3. Peer review all changes
4. Deploy via Update Set or App Repo
5. Have rollback plan ready
6. Monitor post-deployment
```

---

### #SN6: Ignoring ACLs in Scripts

❌ **Wrong**: Bypassing security in scripts
```javascript
// BAD: Bypasses ACLs
var inc = new GlideRecord('incident');
inc.addQuery('active', true);
inc.query();
// User sees all incidents regardless of ACLs!
```

✅ **Right**: Respect security model
```javascript
// GOOD: Enforces ACLs
var inc = new GlideRecordSecure('incident');  // ACL-aware
inc.addQuery('active', true);
inc.query();
// Only returns records user can read
```

---

### #SN7: Poor Update Set Management

❌ **Wrong**: Giant update sets with no organization
```
Update Set: "Changes"
- 500+ changes
- Mix of ITSM, ITOM, and custom apps
- No description
- Preview errors ignored
```

✅ **Right**: Organized, documented approach
```
Update Set Naming: [PROJECT]_[TYPE]_[TICKET]_[DATE]
Examples:
- ITSM_SLA_FIX_INC0012345_20240321
- HRSD_WORKFLOW_ENH_RITM9876_20240320
- CMDB_DISCOVERY_FIX_ENH4321_20240319

Each update set:
- Single purp

…(truncated)
