Task: workarena.servicenow.create-incident
Goal: Create a new incident with a value of "SAP Financial Accounting application appears to be down" for field "Short description", a value of "Bud Richman" for field "Caller", a value of "false" for field "Knowledge", a value of "1 - High" for field "Impact", a value of "Phone" for field "Channel", a value of "balladeer spayard cheering postulnar Anguimorpha" for field "Resolution notes", a value of "PRB0000011" for field "Problem", a value of "" for field "Service", a value of "1 - High" for field "Urgency", a value of "Software" for field "Assignment group", a value of "INC0000052" for field "Number", a value of "" for field "Resolved by", a value of "" for field "Service offering", and a value of "" for field "Caused by Change".
Task configuration: {'table_name': 'incident', 'task_fields': ['short_description', 'caller_id', 'knowledge', 'impact', 'contact_type', 'close_notes', 'problem_id', 'business_service', 'urgency', 'assignment_group', 'number', 'resolved_by', 'service_offering', 'caused_by'], 'template_record': {'active': 'true', 'activity_due': '2023-10-02 16:50:20', 'additional_assignee_list': '', 'approval': 'Not Yet Requested', 'approval_history': '', 'approval_set': '', 'assigned_to': {'display_value': 'Fred Luddy', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/5137153cc611227c000bbd1bd8cd2005'}, 'assignment_group': 'Software', 'business_duration': '', 'business_impact': '', 'business_service': '', 'business_stc': '', 'calendar_duration': '', 'calendar_stc': '', 'caller_id': 'Bud Richman', 'category': 'Software', 'cause': '', 'caused_by': '', 'child_incidents': '', 'close_code': 'User error', 'close_notes': 'balladeer spayard cheering postulnar Anguimorpha', 'closed_at': '', 'closed_by': '', 'cmdb_ci': 'SAP Financial Accounting', 'comments': '2023-09-25 11:16:12 - System Administrator (Additional comments)\nyou\n\n2023-09-25 11:15:58 - System Administrator (Additional comments)\nhey\n\n2023-09-17 21:42:08 - ITIL User (Additional comments)\nSAP Financial Accounting application appears to be down\n\n', 'comments_and_work_notes': '2023-10-02 10:50:20 - Rob Phillips (Work notes)\nI got this\n\n2023-09-30 08:59:47 - System Administrator (Work notes)\nThis machine is broken\n\n2023-09-25 11:16:12 - System Administrator (Additional comments)\nyou\n\n2023-09-25 11:15:58 - System Administrator (Additional comments)\nhey\n\n2023-09-17 21:42:09 - ITIL User (Work notes)\nit appears that this SAP application is down or very slow.\n\t\t\n\n2023-09-17 21:42:08 - ITIL User (Additional comments)\nSAP Financial Accounting application appears to be down\n\n', 'company': {'display_value': 'ACME North America', 'link': 'https://dev215901.service-now.com/api/now/table/core_company/31bea3d53790200044e0bfc8bcbe5dec'}, 'contact_type': 'Phone', 'contract': '', 'correlation_display': '', 'correlation_id': '', 'delivery_plan': '', 'delivery_task': '', 'description': "Main menu doesn't load when I open the SAP Financial Accounting application.", 'due_date': '', 'escalation': 'Overdue', 'expected_start': '', 'follow_up': '', 'group_list': '', 'hold_reason': '', 'impact': '1 - High', 'incident_state': 'In Progress', 'knowledge': 'false', 'location': {'display_value': '261 North Highway 101, Solana Beach,CA', 'link': 'https://dev215901.service-now.com/api/now/table/cmn_location/db96a8480a0a0a65019da337d4a89edc'}, 'made_sla': 'true', 'notify': 'Do Not Notify', 'number': 'INC0000052', 'opened_at': '2023-09-18 13:48:40', 'opened_by': {'display_value': 'ITIL User', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/681b365ec0a80164000fb0b05854a0cd'}, 'order': '', 'origin_id': '', 'origin_table': '', 'parent': '', 'parent_incident': '', 'priority': '1 - Critical', 'problem_id': 'PRB0000011', 'reassignment_count': '0', 'reopen_count': '', 'reopened_by': '', 'reopened_time': '', 'resolved_at': '', 'resolved_by': '', 'rfc': '', 'route_reason': '', 'service_offering': '', 'severity': '3 - Low', 'short_description': 'SAP Financial Accounting application appears to be down', 'sla_due': '2023-09-18 05:40:39', 'state': 'In Progress', 'subcategory': None, 'sys_class_name': 'Incident', 'sys_created_by': 'itil', 'sys_created_on': '2023-09-18 13:48:40', 'sys_domain': {'display_value': 'global', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user_group/global'}, 'sys_domain_path': '/', 'sys_id': 'd7195138c0a8016700fd68449cfcd484', 'sys_mod_count': '94', 'sys_tags': '', 'sys_updated_by': 'system', 'sys_updated_on': '2023-10-02 14:50:24', 'task_effective_number': 'INC0000052', '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': '2023-10-02 10:50:20 - Rob Phillips (Work notes)\nI got this\n\n2023-09-30 08:59:47 - System Administrator (Work notes)\nThis machine is broken\n\n2023-09-17 21:42:09 - ITIL User (Work notes)\nit appears that this SAP application is down or very slow.\n\t\t\n\n', '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