Task: workarena.servicenow.create-problem
Goal: Create a new problem with a value of "USB port has stopped working" for field "Problem statement", a value of "refoundation trophoplasmic diode scend steerman" for field "Description", a value of "Hardware" for field "Category", a value of "" for field "Service offering", a value of "Problem Solving" for field "Assignment group", and a value of "" for field "Service".
Task configuration: {'table_name': 'problem', 'task_fields': ['short_description', 'description', 'category', 'service_offering', 'assignment_group', 'business_service'], 'template_record': {'active': 'false', 'activity_due': 'UNKNOWN', 'additional_assignee_list': '', 'approval': 'Not Yet Requested', 'approval_history': '', 'approval_set': '', 'assigned_to': {'display_value': 'Problem Coordinator A', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/73ab3f173b331300ad3cc9bb34efc4df'}, 'assignment_group': 'Problem Solving', 'business_duration': '16801 Days', 'business_service': '', 'calendar_duration': '16801 Days 5 Minutes', 'category': 'Hardware', 'cause_notes': ' <p>This is a timing issue caused when you plug and unplug USB devices quickly</p> ', 'close_notes': 'OS and hardware vendor cannot find the root cause as it is intermittent. So they recommend restarting the PC', 'closed_at': '2023-08-01 00:09:20', 'closed_by': {'display_value': 'Problem Coordinator A', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/73ab3f173b331300ad3cc9bb34efc4df'}, 'cmdb_ci': '*BETH-IBM', 'comments': '', 'comments_and_work_notes': '', 'company': '', 'confirmed_at': '2023-08-01 00:08:58', 'confirmed_by': {'display_value': 'Problem Coordinator A', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/73ab3f173b331300ad3cc9bb34efc4df'}, 'contact_type': None, 'contract': '', 'correlation_display': '', 'correlation_id': '', 'delivery_plan': '', 'delivery_task': '', 'description': 'refoundation trophoplasmic diode scend steerman', 'due_date': '', 'duplicate_of': '', 'escalation': 'Normal', 'expected_start': '', 'first_reported_by_task': {'display_value': 'INC0000601', 'link': 'https://dev215901.service-now.com/api/now/table/task/9e7f9864532023004247ddeeff7b121f'}, 'fix_at': '', 'fix_by': '', 'fix_communicated_at': '', 'fix_communicated_by': '', 'fix_notes': None, 'follow_up': '', 'group_list': '', 'impact': '3 - Low', 'knowledge': 'false', 'known_error': 'false', 'location': '', 'made_sla': 'true', 'major_problem': 'false', 'number': 'PRB0000109', 'opened_at': '2023-08-01 00:03:54', 'opened_by': {'display_value': 'Ron Kettering', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user/62d78687c0a8010e00b3d84178adc913'}, 'order': '', 'parent': '', 'priority': '5 - Planning', 'problem_state': 'Closed', 'reassignment_count': '0', 'related_incidents': '1', 'reopen_count': '0', 'reopened_at': '', 'reopened_by': '', 'resolution_code': 'Risk Accepted', 'resolved_at': '', 'resolved_by': '', 'review_outcome': '', 'rfc': '', 'route_reason': '', 'service_offering': '', 'short_description': 'USB port has stopped working', 'sla_due': 'UNKNOWN', 'state': 'Closed', 'subcategory': None, 'sys_class_name': 'Problem', 'sys_created_by': 'admin', 'sys_created_on': '2023-08-01 00:05:42', 'sys_domain': {'display_value': 'global', 'link': 'https://dev215901.service-now.com/api/now/table/sys_user_group/global'}, 'sys_domain_path': '/', 'sys_id': '8f74a828532023004247ddeeff7b1295', 'sys_mod_count': '7', 'sys_tags': '', 'sys_updated_by': 'admin', 'sys_updated_on': '2024-03-11 09:25:21', 'task_effective_number': 'PRB0000109', 'time_worked': '', 'universal_request': '', 'upon_approval': 'Proceed to Next Task', 'upon_reject': 'Cancel all future Tasks', 'urgency': '3 - Low', 'user_input': '', 'watch_list': '', 'work_end': '', 'work_notes': '', 'work_notes_list': '', 'work_start': '', 'workaround': '\n\t\t\t <p>As this is intermittent. Restarting the PC fixes this.</p>', 'workaround_applied': 'true', 'workaround_communicated_at': '', 'workaround_communicated_by': ''}}

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