Task: workarena.servicenow.create-incident
Goal: Create a new incident with a value of "Defect tracking tool is down." for field "Short description", a value of "David Miller" for field "Caller", a value of "" for field "Assignment group", a value of "While launching the defect tracking base URL, it is redirecting to an error page." for field "Description", a value of "" for field "Configuration item", a value of "" for field "Problem", a value of "false" for field "Knowledge", a value of "System Administrator" for field "Resolved by", a value of "Resolved by caller" for field "Resolution code", a value of "" for field "Service offering", a value of "" for field "Change Request", a value of "1 - High" for field "Urgency", a value of "INC0009004" for field "Number", a value of "Reverted to a previous version." for field "Resolution notes", a value of "" for field "Service", a value of "Walk-in" for field "Channel", a value of "" for field "Parent Incident", a value of "3 - Low" for field "Impact", and a value of "Software" for field "Category".
Task configuration: {'table_name': 'incident', 'task_fields': ['short_description', 'caller_id', 'assignment_group', 'description', 'cmdb_ci', 'problem_id', 'knowledge', 'resolved_by', 'close_code', 'service_offering', 'rfc', 'urgency', 'number', 'close_notes', 'business_service', 'contact_type', 'parent_incident', 'impact', 'category'], 'template_record': {'active': 'false', 'activity_due': 'UNKNOWN', 'additional_assignee_list': '', 'approval': 'Not Yet Requested', 'approval_history': '', 'approval_set': '', 'assigned_to': '', 'assignment_group': '', 'business_duration': '0 Seconds', 'business_impact': '', 'business_service': '', 'business_stc': '0', 'calendar_duration': '5 Minutes', 'calendar_stc': '323', 'caller_id': 'David Miller', 'category': 'Software', 'cause': '', 'caused_by': '', 'child_incidents': '0', 'close_code': 'Resolved by caller', 'close_notes': 'Reverted to a previous version.', 'closed_at': '2018-12-09 19:29:09', 'closed_by': {'display_value': 'System Administrator', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441'}, 'cmdb_ci': '', 'comments': '', 'comments_and_work_notes': '', 'company': '', 'contact_type': 'Walk-in', 'contract': '', 'correlation_display': '', 'correlation_id': '', 'delivery_plan': '', 'delivery_task': '', 'description': 'While launching the defect tracking base URL, it is redirecting to an error page.', 'due_date': '', 'escalation': 'Normal', 'expected_start': '', 'follow_up': '', 'group_list': '', 'hold_reason': '', 'impact': '3 - Low', 'incident_state': 'Closed', 'knowledge': 'false', 'location': '', 'made_sla': 'true', 'notify': 'Do Not Notify', 'number': 'INC0009004', 'opened_at': '2018-09-01 06:13:30', 'opened_by': {'display_value': 'System Administrator', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/6816f79cc0a8016401c5a33be04be441'}, 'order': '', 'origin_id': '', 'origin_table': '', 'parent': '', 'parent_incident': '', 'priority': '3 - Moderate', 'problem_id': '', 'reassignment_count': '0', 'reopen_count': '0', 'reopened_by': '', 'reopened_time': '', 'resolved_at': '2018-09-01 06:18:53', 'resolved_by': 'System Administrator', 'rfc': '', 'route_reason': '', 'service_offering': '', 'severity': '3 - Low', 'short_description': 'Defect tracking tool is down.', 'sla_due': 'UNKNOWN', 'state': 'Closed', 'subcategory': None, 'sys_class_name': 'Incident', 'sys_created_by': 'admin', 'sys_created_on': '2018-09-01 06:14:04', 'sys_domain': {'display_value': 'global', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user_group/global'}, 'sys_domain_path': '/', 'sys_id': 'e329de99731423002728660c4cf6a73c', 'sys_mod_count': '9', 'sys_tags': '', 'sys_updated_by': 'system', 'sys_updated_on': '2023-10-10 16:19:01', 'task_effective_number': 'INC0009004', 'time_worked': '', 'universal_request': '', 'upon_approval': 'Proceed to Next Task', 'upon_reject': 'Cancel all future Tasks', 'urgency': '1 - High', 'user_input': '', 'watch_list': '', 'work_end': '', 'work_notes': '', 'work_notes_list': '', 'work_start': ''}}

Validation code:
import json
import os
import re
import urllib.parse as parse
from typing import Any, Dict, List

import requests


def validate(messages: List[Dict[str, str]], config: Dict[str, Any]) -> int:
    """
    Validate that a record was created with expected field values.
    Returns 1 on success, else 0.

    Expected config keys:
      - task_fields (list[str])                  # fields to validate
      - template_record (dict)                   # expected display values for those fields
    """

    # Check whether we have the necessary information to validate
    print(config)
    if "table_name" not in config or "task_fields" not in config or "template_record" not in config:
        raise ValueError("Target must contain 'table_name', 'task_fields' and 'template_record'")

    # Check whether we have messages
    if not messages:
        raise ValueError("Messages must not be empty")

    # Extract last message content
    content = messages[-1].get("content", "")

    # Extract all URLs — markdown links first, then bare URLs
    seen = set()
    urls = []
    for m in re.finditer(r"\[.*?\]\((https?://[^)]+)\)", content):
        url = m.group(1)
        if url not in seen:
            seen.add(url)
            urls.append(url)
    for m in re.finditer(r"https?://\S+", content):
        url = m.group(0).rstrip(")].,")
        if url not in seen:
            seen.add(url)
            urls.append(url)
    if not urls:
        return 0

    def extract_sys_id(url: str) -> str | None:
        """
        Return the 32-hex sys_id from a ServiceNow URL, or None if not found.
        Handles encoded target URLs like .../params/target/incident.do%3Fsys_id%3D<id>
        """
        # Unquote repeatedly (some SN URLs are doubly-encoded)
        for _ in range(3):
            new = parse.unquote(url)
            if new == url:
                break
            url = new

        m = re.search(r"(?:[?&])sys_id=([0-9a-f]{32})", url, re.IGNORECASE)
        return m.group(1) if m else None

    sys_id = None
    for raw_url in urls:
        current_url = parse.urlunparse(parse.urlparse(parse.unquote(raw_url)))
        sys_id = extract_sys_id(current_url)
        if sys_id:
            break
    if not sys_id:
        return 0

    # Query instance to get record
    response = requests.request(
        method="GET",
        url=os.getenv("SERVICENOW_INSTANCE_URL", "").rstrip("/") + f"/api/now/table/{config['table_name']}",
        headers={
            "Content-Type": "application/json",
            "Accept": "application/json",
            **json.loads(os.getenv("SERVICENOW_EXTRA_HTTP_HEADERS", "{}")),
        },
        params={
            "sysparm_query": f"sys_id={sys_id}",
            "sysparm_display_value": "true",
            "sysparm_fields": ",".join(config["task_fields"]),
        },
    )
    response.raise_for_status()
    if type(response) == dict:
        record = response
    else:
        record = response.json()

    if "result" in record:
        record = record["result"]

    if isinstance(record, list):
        if len(record) == 0:
            return 0
        record = record[0]

    # Check that the record matches the expected values
    for f in config["task_fields"]:
        val = record.get(f)
        # Handle nested display_value dicts from the API
        if isinstance(val, dict) and "display_value" in val:
            val = val["display_value"]
        if val is None:
            return 0
        if val != config["template_record"][f]:
            return 0
    return 1