{
  "name": "UTM Naming Enforcer",
  "nodes": [
    {
      "id": "5c98df97-5f92-4e2e-bc65-d3dc6169bcf4",
      "name": "Daily Tag Check",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        100,
        300
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 9 * * 1-5"
            }
          ]
        }
      }
    },
    {
      "id": "c5ff055d-0f79-427d-8447-5184bad68cb9",
      "name": "Get Taxonomy",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        300,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "DWU7dnbL1Z1XHBxj",
          "cachedResultName": "UTM Taxonomy"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "69161a3e-a8ad-4efd-9b24-e07a33bc4623",
      "name": "Get New Touches",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        500,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "cPdw9VsQ5hKDiSjM",
          "cachedResultName": "Inbound Touch Log"
        },
        "returnAll": true
      },
      "executeOnce": true,
      "alwaysOutputData": true
    },
    {
      "id": "278a7758-34db-4717-8267-3d819df08c67",
      "name": "Check Tags",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        700,
        300
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Check every new touch's UTM source, medium and campaign against the taxonomy. In order: an exact allowed value is\n// clean; a value that matches once lower-cased and trimmed, or a known alias, is fixed automatically; anything else goes\n// to Claude, which may only suggest a value already in the allowed list (or none). Missing values are flagged.\nconst runDate = $today.toFormat('yyyy-MM-dd');\nconst FIELDS = { source: 'utmSource', medium: 'utmMedium', campaign: 'utmCampaign' };\nconst allowed = { source: [], medium: [], campaign: [] }, alias = { source: {}, medium: {}, campaign: {} };\nfor (const t of $('Get Taxonomy').all().map(i => i.json).filter(t => t.field && t.value)) {\n  if (t.kind === 'allowed') allowed[t.field].push(t.value); else if (t.kind === 'alias') alias[t.field][String(t.value).trim().toLowerCase()] = t.aliasOf;\n}\nconst touches = $('Get New Touches').all().map(i => i.json).filter(t => t.touchId && (t.status || 'new') === 'new');\nconst ask = {};\nconst rows = touches.map(t => {\n  const fields = {};\n  for (const [f, col] of Object.entries(FIELDS)) {\n    const raw = t[col] == null ? '' : String(t[col]), n = raw.trim().toLowerCase();\n    if (!n) fields[f] = { raw, kind: 'missing', value: '' };\n    else if (allowed[f].includes(raw)) fields[f] = { raw, kind: 'clean', value: raw };\n    else if (allowed[f].includes(n)) fields[f] = { raw, kind: 'auto', value: n, why: raw !== raw.trim() ? 'extra spaces' : 'capitals' };\n    else if (alias[f][n]) fields[f] = { raw, kind: 'auto', value: alias[f][n], why: 'known alias' };\n    else { fields[f] = { raw, kind: 'ask', value: '' }; ask[f + '|' + n] = { field: f, value: n }; }\n  }\n  return { touchId: t.touchId, capturedOn: t.capturedOn, linkId: t.linkId, fields };\n});\nreturn [{ json: { runDate, rows, allowed, forClaude: { values: Object.values(ask), allowed } } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "2d63f328-fde4-4fa4-afd2-a8896fc54dce",
      "name": "Tag Matcher",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        300,
        450
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ JSON.stringify($json.forClaude, null, 1) }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You clean marketing campaign tags (UTM parameters) for Fortavault, Inc. (a fictional data protection company). You get values that do not match the naming standard, each with its field (source, medium or campaign), and the list of allowed values per field.\n\nFor each value return field, value (exactly as given), suggestion and reason. suggestion must be copied exactly from the allowed list for that field, and only when the value clearly means that allowed value: a typo, a different spelling or format, a product or ad-platform name for the same source, or a campaign name that describes the same campaign. If the value is a different source or campaign than anything on the list (for example a new channel or a campaign that is not in the plan), return an empty suggestion; never force a match. reason: a plain phrase of at most 10 words."
        }
      },
      "executeOnce": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "id": "27faeb32-e87e-4493-baea-faac6c864673",
      "name": "Claude Sonnet",
      "type": "@n8n/n8n-nodes-langchain.lmChatAnthropic",
      "typeVersion": 1.3,
      "position": [
        100,
        450
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "claude-sonnet-4-6",
          "cachedResultName": "Claude Sonnet 4.6"
        },
        "options": {
          "temperature": 0
        }
      },
      "credentials": {
        "anthropicApi": {
          "id": "3d3ZiTi7BwnkFwqU",
          "name": "Anthropic account"
        }
      }
    },
    {
      "id": "d81235bf-cc25-47bd-bbb8-375c4eaf7a32",
      "name": "Tag Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        100,
        600
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\"type\":\"object\",\"properties\":{\"fixes\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"field\":{\"type\":\"string\",\"enum\":[\"source\",\"medium\",\"campaign\"]},\"value\":{\"type\":\"string\"},\"suggestion\":{\"type\":\"string\"},\"reason\":{\"type\":\"string\"}},\"required\":[\"field\",\"value\",\"suggestion\",\"reason\"]}}},\"required\":[\"fixes\"]}"
      }
    },
    {
      "id": "6aab0cfe-fc88-45c1-88b7-dd230a7f08eb",
      "name": "Build Fixes",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        500,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Accept Claude's suggestion only if it is an allowed value for that field. Then sort each touch into clean, fixed\n// automatically, needs approval (a Claude match) or unknown, and report which links keep producing bad tags.\nconst c = $('Check Tags').first().json;\nconst out = $('Tag Matcher').first().json.output || {};\nconst sug = {}; let rejected = 0;\nfor (const x of (out.fixes || [])) {\n  const key = x.field + '|' + String(x.value || '').trim().toLowerCase();\n  if (x.suggestion && (c.allowed[x.field] || []).includes(x.suggestion)) sug[key] = { value: x.suggestion, reason: x.reason }; else if (x.suggestion) rejected++;\n}\nconst learned = {};\nconst rows = c.rows.map(r => {\n  const f = {};\n  for (const [k, v] of Object.entries(r.fields)) {\n    if (v.kind !== 'ask') { f[k] = v; continue; }\n    const s = sug[k + '|' + v.raw.trim().toLowerCase()];\n    if (s) { f[k] = { ...v, kind: 'claude', value: s.value, why: s.reason }; learned[k + '|' + v.raw.trim().toLowerCase()] = { field: k, value: v.raw.trim().toLowerCase(), aliasOf: s.value, why: s.reason }; }\n    else f[k] = { ...v, kind: 'unknown' };\n  }\n  const kinds = Object.values(f).map(v => v.kind);\n  const status = kinds.some(k => k === 'unknown' || k === 'missing') ? 'unknown' : kinds.includes('claude') ? 'needs approval' : kinds.includes('auto') ? 'auto-fixed' : 'clean';\n  return { ...r, fields: f, status };\n});\nconst by = s => rows.filter(r => r.status === s);\nconst links = {};\nfor (const r of rows.filter(r => r.status !== 'clean')) {\n  const l = links[r.linkId] = links[r.linkId] || { linkId: r.linkId, touches: 0, issues: new Set() };\n  l.touches++;\n  for (const [k, v] of Object.entries(r.fields)) if (v.kind !== 'clean') l.issues.add(v.kind === 'missing' ? k + ' missing' : k + ' \\u201c' + v.raw + '\\u201d' + (v.value ? ' \\u2192 ' + v.value : ' (no match)'));\n}\nconst linkList = Object.values(links).map(l => ({ linkId: l.linkId, touches: l.touches, issues: [...l.issues] })).sort((a, b) => b.touches - a.touches);\nconst L = Object.values(learned);\nlet text = ':label: *UTM Naming Enforcer* (' + c.runDate + '): ' + rows.length + ' new touches checked. ' + by('clean').length + ' clean, ' + by('auto-fixed').length + ' fixed automatically (capitals, spaces, known aliases), ' + by('needs approval').length + ' need your approval, ' + by('unknown').length + ' need an owner.\\n' +\n  (L.length ? '\\n*Proposed matches* (approve to apply them and remember each as an alias, so next time they fix themselves)\\n' + L.map(m => '• ' + m.field + ' “' + m.value + '” → *' + m.aliasOf + '*: ' + m.why).join('\\n') + '\\n' : '') +\n  (by('unknown').length ? '\\n*No match, needs an owner*\\n' + by('unknown').map(r => '• ' + r.touchId + ' (' + r.linkId + '): ' + Object.entries(r.fields).filter(([k, v]) => v.kind === 'unknown' || v.kind === 'missing').map(([k, v]) => k + ' ' + (v.kind === 'missing' ? 'is missing' : '“' + v.raw + '” is not in the plan')).join('; ')).join('\\n') + '\\n' : '') +\n  '\\n*Fix these links at the source* (' + linkList.length + ')\\n' + linkList.slice(0, 8).map(l => '• *' + l.linkId + '* (' + l.touches + ' touch' + (l.touches > 1 ? 'es' : '') + '): ' + l.issues.join('; ')).join('\\n') +\n  (rejected ? '\\n_' + rejected + ' suggestion(s) from Claude ignored: not an allowed value._' : '');\nif (text.length > 2900) text = text.slice(0, 2850).slice(0, text.slice(0, 2850).lastIndexOf('\\n')) + '\\n_…cut to fit Slack._';\nreturn [{ json: { approvalText: text, rows, learned: L, links: linkList } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "1e025a46-f0ae-481a-aa9a-73c4fab8ed3e",
      "name": "Ask Approval in Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.3,
      "position": [
        700,
        450
      ],
      "parameters": {
        "resource": "message",
        "operation": "sendAndWait",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "C0BQ3G96HL6",
          "cachedResultName": "general"
        },
        "message": "={{ $json.approvalText }}",
        "responseType": "approval",
        "approvalOptions": {
          "values": {
            "approvalType": "double",
            "approveLabel": "Apply matches",
            "disapproveLabel": "Decline"
          }
        },
        "options": {
          "limitWaitTime": {
            "values": {
              "limitType": "afterTimeInterval",
              "resumeAmount": 48,
              "resumeUnit": "hours"
            }
          },
          "appendAttribution": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "c01d6d7f-a7b4-456c-b704-ae2d0674917e",
      "name": "Apply Decision",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        900,
        450
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// Automatic fixes always apply. Claude's matches apply only if a person approved them in Slack, and are then saved as\n// aliases so the same tag is fixed automatically next time. Unknown values are left for an owner.\nconst p = $('Build Fixes').first().json;\nconst approved = !!(($('Ask Approval in Slack').first().json.data || {}).approved);\nconst runDate = $('Check Tags').first().json.runDate;\nconst updates = p.rows.map(r => {\n  const v = k => { const x = r.fields[k]; return x.kind === 'clean' || x.kind === 'auto' || (x.kind === 'claude' && approved) ? x.value : ''; };\n  const status = r.status === 'needs approval' ? (approved ? 'fixed (approved)' : 'declined') : r.status === 'auto-fixed' ? 'fixed (automatic)' : r.status;\n  return { touchId: r.touchId, cleanSource: v('source'), cleanMedium: v('medium'), cleanCampaign: v('campaign'), status };\n});\nconst aliases = approved ? p.learned.map(m => ({ field: m.field, value: m.value, kind: 'alias', aliasOf: m.aliasOf, addedOn: runDate, seedNote: 'Learned by the UTM Naming Enforcer, approved in Slack' })) : [];\nconst good = updates.filter(u => /^fixed|^clean$/.test(u.status)).length;\nconst resultText = (approved ? ':white_check_mark: Approved. ' : ':no_entry_sign: Declined; only the automatic fixes were applied. ') + good + ' of ' + updates.length + ' touches now carry clean tags' +\n  (approved ? '; ' + aliases.length + ' new aliases saved to the taxonomy, so these tags fix themselves next time.' : '.') +\n  ' ' + updates.filter(u => u.status === 'unknown').length + ' still need an owner.';\nreturn [{ json: { approved, updates, aliases, resultText } }];\n"
      },
      "executeOnce": true
    },
    {
      "id": "da1fc698-32f4-434a-a8d7-fbf3c40c23cc",
      "name": "Post Result to Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.7,
      "position": [
        1100,
        450
      ],
      "parameters": {
        "resource": "message",
        "operation": "post",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "C0BQ3G96HL6",
          "cachedResultName": "general"
        },
        "text": "={{ $json.resultText }}",
        "otherOptions": {
          "includeLinkToWorkflow": false
        }
      },
      "credentials": {
        "slackApi": {
          "id": "mv7TIi8kucFPqPg6",
          "name": "Slack account"
        }
      }
    },
    {
      "id": "aea00810-1e82-4814-98f8-01525b50b2ef",
      "name": "Split Touch Updates",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        600
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Apply Decision').first().json.updates.map(json => ({ json }));"
      }
    },
    {
      "id": "7870e939-70d0-4ee6-9026-3c591cea13ee",
      "name": "Write Clean Tags",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1300,
        600
      ],
      "parameters": {
        "resource": "row",
        "operation": "upsert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "cPdw9VsQ5hKDiSjM",
          "cachedResultName": "Inbound Touch Log"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "touchId",
              "condition": "eq",
              "keyValue": "={{ $json.touchId }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    },
    {
      "id": "64991da7-c0a6-49c2-b3a3-70febd0c6246",
      "name": "Split New Aliases",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        750
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $('Apply Decision').first().json.aliases.map(json => ({ json }));"
      }
    },
    {
      "id": "d8e0343d-bc53-4a5d-8fae-6d3d6cc2bec9",
      "name": "Save Learned Aliases",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1300,
        750
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "id",
          "value": "DWU7dnbL1Z1XHBxj",
          "cachedResultName": "UTM Taxonomy"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {}
        }
      }
    }
  ],
  "connections": {
    "Daily Tag Check": {
      "main": [
        [
          {
            "node": "Get Taxonomy",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Taxonomy": {
      "main": [
        [
          {
            "node": "Get New Touches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get New Touches": {
      "main": [
        [
          {
            "node": "Check Tags",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Tags": {
      "main": [
        [
          {
            "node": "Tag Matcher",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tag Matcher": {
      "main": [
        [
          {
            "node": "Build Fixes",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Claude Sonnet": {
      "ai_languageModel": [
        [
          {
            "node": "Tag Matcher",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Tag Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Tag Matcher",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Build Fixes": {
      "main": [
        [
          {
            "node": "Ask Approval in Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ask Approval in Slack": {
      "main": [
        [
          {
            "node": "Apply Decision",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply Decision": {
      "main": [
        [
          {
            "node": "Post Result to Slack",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split Touch Updates",
            "type": "main",
            "index": 0
          },
          {
            "node": "Split New Aliases",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Touch Updates": {
      "main": [
        [
          {
            "node": "Write Clean Tags",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split New Aliases": {
      "main": [
        [
          {
            "node": "Save Learned Aliases",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}