---
name: gtm-audit
description: |
  GTM container audit using Chrome DevTools and DTM Agent for tag verification.
  Triggers: audit GTM, GTM analysis, tag debugging, dataLayer inspection.
---

# GTM Audit Skill

Automated audit workflow for GTM containers using **Chrome DevTools MCP** for browser inspection and **DTM Agent MCP** for GTM API operations.

## Prerequisites

### Chrome GTM Debug Profile (Required)

Before starting any GTM audit, launch the dedicated Chrome GTM Debug profile:

```bash
chrome-gtm
```

This launches Chrome with remote debugging enabled on port 9222, which is required for the chrome-devtools MCP server to connect.

| Item | Value |
|------|-------|
| **Profile Location** | `~/Library/Application Support/Chrome-GTM-Debug` |
| **Debug Port** | 9222 |
| **Launch Script** | `~/Utilities/chrome-gtm-debug.sh` |

**Note**: This is a separate Chrome instance from your regular browser. Install GTM-related extensions (Tag Assistant, etc.) in this profile for debugging work.

## Required MCP Servers

This skill requires the following MCP servers to be configured:

| MCP Server | Purpose | Tools Used |
|------------|---------|------------|
| **chrome-devtools** | Browser debugging & inspection | `navigate_page`, `evaluate_script`, `list_network_requests`, `list_console_messages`, `click`, `hover`, `take_screenshot`, `performance_start_trace` |
| **dtm-agent** | GTM API operations | `dtm_status`, `dtm_list_tags`, `dtm_get_tag`, `dtm_list_triggers`, `dtm_get_trigger`, `dtm_list_variables`, `dtm_debug_performance`, `dtm_debug_preview` |

**Important**: The chrome-devtools MCP server requires Chrome to be running with `--remote-debugging-port=9222`. Always run `chrome-gtm` first before attempting to use chrome-devtools tools.

## Critical Workflow Rule

**ALWAYS use Chrome DevTools MCP FIRST before making GTM configuration changes.**

GTM triggering and parameter capturing issues are highly dependent on:
- DOM structure and CSS selectors
- Dynamic element loading and timing
- DataLayer event sequences
- JavaScript execution order
- Network request timing

## Standard Debugging Workflow

```
┌─────────────────────────────────────────────────────────────────┐
│  PHASE 0: SETUP                                                 │
├─────────────────────────────────────────────────────────────────┤
│  Run `chrome-gtm` to launch Chrome GTM Debug profile            │
│  Verify: curl http://127.0.0.1:9222/json/version                │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  PHASE 1: INSPECT (Chrome DevTools MCP)                        │
├─────────────────────────────────────────────────────────────────┤
│  1. navigate_page → Load target URL                             │
│  2. evaluate_script → Check window.dataLayer state              │
│  3. list_network_requests → Identify GTM/tag requests           │
│  4. list_console_messages → Check for JS errors                 │
│  5. click/hover → Simulate user interactions                    │
│  6. take_screenshot → Document current state                    │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  PHASE 2: DIAGNOSE                                              │
├─────────────────────────────────────────────────────────────────┤
│  • Identify DOM/timing/selector issues from browser state       │
│  • Compare expected vs actual dataLayer events                  │
│  • Check network request payloads for missing parameters        │
│  • Review console for GTM/tag errors                            │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  PHASE 3: CONFIGURE (DTM Agent MCP)                             │
├─────────────────────────────────────────────────────────────────┤
│  1. dtm_status → Verify authentication                          │
│  2. dtm_list_tags → Review current tag configuration            │
│  3. dtm_get_trigger → Inspect trigger conditions                │
│  4. dtm_list_variables → Check variable mappings                │
│  5. dtm_update_tag/trigger → Make configuration changes         │
│  6. dtm_create_version → Create version for testing             │
└─────────────────────────────────────────────────────────────────┘
                              ↓
┌─────────────────────────────────────────────────────────────────┐
│  PHASE 4: VERIFY (Chrome DevTools MCP)                          │
├─────────────────────────────────────────────────────────────────┤
│  • Repeat Phase 1 inspection steps                              │
│  • Confirm issue is resolved                                    │
│  • Document before/after comparison                             │
└─────────────────────────────────────────────────────────────────┘
```

## Chrome DevTools MCP Commands

### Essential Inspection Commands

```javascript
// 1. Check dataLayer state
evaluate_script: "JSON.stringify(window.dataLayer || [], null, 2)"

// 2. Get GTM container info
evaluate_script: "Object.keys(window.google_tag_manager || {})"

// 3. Monitor dataLayer pushes (inject listener)
evaluate_script: `
  window.__gtmPushLog = [];
  const originalPush = window.dataLayer.push;
  window.dataLayer.push = function(...args) {
    window.__gtmPushLog.push({timestamp: Date.now(), data: args[0]});
    return originalPush.apply(this, args);
  };
`

// 4. Get captured pushes
evaluate_script: "JSON.stringify(window.__gtmPushLog || [], null, 2)"

// 5. Check for GTM debug mode
evaluate_script: "window.google_tag_manager?.['GTM-XXXXXX']?.preview?.active"
```

### Network Request Patterns

| Tag Type | URL Pattern to Monitor |
|----------|------------------------|
| GA4 | `google-analytics.com/g/collect` |
| Google Ads | `googleads.g.doubleclick.net` |
| Meta Pixel | `facebook.com/tr` |
| LinkedIn | `px.ads.linkedin.com` |
| TikTok | `analytics.tiktok.com` |
| Kakao | `track.tiara.kakao.com` |
| Naver | `wcs.naver.net` |

## DTM Agent MCP Commands

### Container Analysis

```bash
# Check authentication and active container
dtm_status

# List all tags with optional filter
dtm_list_tags --name_filter "GA4"

# Get specific tag details
dtm_get_tag --tag_id "123"

# List triggers and their conditions
dtm_list_triggers

# Container performance analysis
dtm_debug_performance

# Validate container configuration
dtm_debug_preview
```

### Configuration Changes

```bash
# Update tag configuration
dtm_update_tag --tag_id "123" --config {...}

# Create new trigger
dtm_create_trigger --name "Button Click" --type "CLICK"

# Create version for testing
dtm_create_version --name "Debug Session 2025-01-03"
```

## Audit Checklist

### Container Health
- [ ] GTM script loads without errors (Chrome DevTools: console)
- [ ] Container ID matches expected (Chrome DevTools: evaluate_script)
- [ ] No duplicate containers (Chrome DevTools: network requests)
- [ ] Script in correct position (Chrome DevTools: DOM inspection)

### DataLayer Quality
- [ ] dataLayer initialized before GTM (Chrome DevTools: evaluate_script)
- [ ] Event names follow conventions (Chrome DevTools: dataLayer inspection)
- [ ] Required parameters present (DTM Agent: dtm_get_tag to check expected params)
- [ ] Data types correct (Chrome DevTools: typeof checks)
- [ ] E-commerce objects cleared before new push
- [ ] No duplicate events firing (Chrome DevTools: network request count)

### Tag Configuration
- [ ] Tags properly configured (DTM Agent: dtm_list_tags)
- [ ] Triggers have correct conditions (DTM Agent: dtm_get_trigger)
- [ ] Variables mapped correctly (DTM Agent: dtm_list_variables)
- [ ] Firing sequence appropriate (DTM Agent: dtm_debug_performance)

### Tag Firing Verification
- [ ] Pageview fires on all pages (Chrome DevTools: network requests)
- [ ] Events fire on correct triggers (Chrome DevTools: click + network)
- [ ] E-commerce events have required params (Chrome DevTools: request payload)
- [ ] Conversion tags fire once (Chrome DevTools: request count)

## Common Issue Patterns

### Issue: Tag Not Firing

**Diagnosis (Chrome DevTools MCP first)**:
1. `navigate_page` → Load the page
2. `list_network_requests` → Check if ANY request to tag endpoint
3. `evaluate_script` → Verify dataLayer event exists
4. `list_console_messages` → Check for errors

**Fix (DTM Agent MCP)**:
1. `dtm_get_trigger` → Review trigger conditions
2. `dtm_update_trigger` → Adjust selector/event name
3. `dtm_debug_preview` → Validate configuration

### Issue: Missing Parameters

**Diagnosis (Chrome DevTools MCP first)**:
1. `list_network_requests` → Capture the actual request
2. Parse request payload to see what's sent
3. `evaluate_script` → Check dataLayer for expected values

**Fix (DTM Agent MCP)**:
1. `dtm_list_variables` → Check variable configuration
2. `dtm_update_tag` → Fix parameter mappings

### Issue: Duplicate Firing

**Diagnosis (Chrome DevTools MCP first)**:
1. `list_network_requests` → Count requests to same endpoint
2. `evaluate_script` → Check dataLayer for duplicate pushes

**Fix (DTM Agent MCP)**:
1. `dtm_list_triggers` → Check for overlapping triggers
2. `dtm_get_tag` → Review tag firing options

## Performance Analysis

Use Chrome DevTools MCP for performance:
```
performance_start_trace → Run page load → Analyze trace
```

Compare with DTM Agent static analysis:
```
dtm_debug_performance → Get container complexity grade
```

## Output Format

Audit generates structured report:

```json
{
  "audit_metadata": {
    "url": "https://example.com",
    "timestamp": "2025-01-03T10:30:00Z",
    "container_id": "GTM-XXXXXX",
    "tools_used": ["chrome-devtools", "dtm-agent"]
  },
  "browser_inspection": {
    "dataLayer_events": [...],
    "network_requests": [...],
    "console_errors": [...],
    "performance_metrics": {...}
  },
  "gtm_configuration": {
    "tags": [...],
    "triggers": [...],
    "variables": [...],
    "container_grade": "B"
  },
  "issues": [...],
  "recommendations": [...]
}
```

## Integration with Other Skills

- **seo-core-web-vitals**: Use performance traces for Core Web Vitals impact analysis
- **notion-writer**: Export audit reports to Notion database
- **seo-schema-validator**: Validate e-commerce structured data alongside GTM
