Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(connectors): WS8 bidirectional ITSM — push_case + push_status_change

Beenu Arora9911980352c4
diff --git a/services/connectors/app/api/router.py b/services/connectors/app/api/router.py
index 7fa577c32..23015588e 100644
--- a/services/connectors/app/api/router.py
+++ b/services/connectors/app/api/router.py
@@ -34,6 +34,7 @@ from pydantic import BaseModel
from pydantic import Field as PydField
from app.connectors import CONNECTOR_REGISTRY, list_connector_schemas
+from app.connectors.base import Capability
from app.federated.query import QueryError, parse_unified_query
logger = structlog.get_logger()
@@ -86,6 +87,87 @@ class FederatedQueryRequest(BaseModel):
)
+# ---------------------------------------------------------------------------
+# WS8: bidirectional ITSM push.
+# ---------------------------------------------------------------------------
+#
+# These two payloads carry the AiSOC case (already serialized to a dict by
+# the API layer) plus the same auth/runtime config envelope as the test and
+# query endpoints. Trust model is identical: ``auth_config`` arrives in
+# plaintext because the API service decrypted it via ``CredentialVault``
+# before forwarding.
+
+
+class PushCaseRequest(BaseModel):
+ """Mint or update an external ticket from an AiSOC case.
+
+ ``case`` is the dict the API layer assembled from the ``aisoc_cases``
+ row (id, case_number, title, description, severity, status, plus any
+ relevant joins). ``external_ref`` is optional and only set when the
+ caller already has a ``case_external_refs`` row to update — the
+ connector will treat it as "first-time push" otherwise.
+ """
+
+ auth_config: dict[str, Any] = PydField(default_factory=dict)
+ connector_config: dict[str, Any] = PydField(default_factory=dict)
+ case: dict[str, Any] = PydField(
+ ...,
+ description="AiSOC case payload to project onto the external ITSM.",
+ )
+ external_ref: dict[str, Any] | None = PydField(
+ default=None,
+ description="Existing case_external_refs row for idempotent updates.",
+ )
+
+
+class PushStatusChangeRequest(BaseModel):
+ """Project an AiSOC status transition onto an external ticket."""
+
+ auth_config: dict[str, Any] = PydField(default_factory=dict)
+ connector_config: dict[str, Any] = PydField(default_factory=dict)
+ case: dict[str, Any] = PydField(...)
+ old_status: str = PydField(..., description="AiSOC status the case is moving from.")
+ new_status: str = PydField(..., description="AiSOC status the case is moving to.")
+ external_ref: dict[str, Any] | None = PydField(
+ default=None,
+ description="Existing case_external_refs row. None falls through to push_case.",
+ )
+
+
+def _instantiate_or_422(cls: type, kwargs: dict[str, Any]) -> Any:
+ """Construct ``cls(**kwargs)`` and convert config errors to HTTP 422.
+
+ Pulled out into a helper because four endpoints now share the exact
+ same construction path; keeping it inline meant duplicating the
+ ``TypeError`` handling four times.
+ """
+ try:
+ return cls(**kwargs)
+ except TypeError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail=f"connector config does not match schema: {exc}",
+ ) from exc
+
+
+def _require_capability(cls: type, capability: Capability, connector_id: str) -> None:
+ """Reject calls to a connector that doesn't declare ``capability``.
+
+ ``BaseConnector`` already raises ``NotImplementedError`` from the
+ default ``push_case`` / ``push_status_change`` bodies, but failing
+ fast here gives a friendlier 501 with the connector_id pre-filled
+ instead of bubbling an opaque exception out of the runtime.
+ """
+ if capability not in cls.capabilities():
+ raise HTTPException(
+ status_code=status.HTTP_501_NOT_IMPLEMENTED,
+ detail=(
+ f"connector '{connector_id}' does not declare capability "
+ f"'{capability.value}'"
+ ),
+ )
+
+
@router.get("/connectors")
async def list_connectors():
"""List every connector registered with this build."""
@@ -252,6 +334,101 @@ async def run_federated_query(connector_id: str, payload: FederatedQueryRequest)
}
[email protected]("/connectors/{connector_id}/push_case")
+async def push_case(connector_id: str, payload: PushCaseRequest):
+ """Mint or upsert an external ITSM ticket from an AiSOC case.
+
+ Idempotency is the connector's responsibility: when ``external_ref``
+ is set, the connector should patch the existing ticket; when it's
+ None, it should create one and return enough metadata for the caller
+ to persist a ``case_external_refs`` row (``external_id``,
+ ``external_url``, ``vendor``, ``external_status``).
+
+ Returns the connector's ``{"external_id", "external_url", "vendor",
+ "external_status"}`` envelope. The API service maps that into the
+ ``case_external_refs`` table; we never persist anything here.
+ """
+ cls = CONNECTOR_REGISTRY.get(connector_id)
+ if cls is None:
+ raise HTTPException(status_code=404, detail=f"Connector '{connector_id}' not found")
+ _require_capability(cls, Capability.PUSH_CASE, connector_id)
+
+ kwargs = {**payload.auth_config, **payload.connector_config}
+ connector = _instantiate_or_422(cls, kwargs)
+
+ try:
+ result = await connector.push_case(payload.case)
+ except NotImplementedError as exc:
+ raise HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED, detail=str(exc)) from exc
+ except Exception:
+ # Don't leak vendor errors verbatim — they sometimes echo request
+ # headers / payload fragments. The connector logs the full detail
+ # via structlog; the API service just sees a generic 502.
+ logger.exception(
+ "connector.push_case.runtime_error",
+ connector_id=_safe_log_val(connector_id),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail="Push to external ITSM failed. Check connector configuration and connectivity.",
+ )
+
+ if not isinstance(result, dict):
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"connector '{connector_id}' returned unexpected push_case payload",
+ )
+ return result
+
+
[email protected]("/connectors/{connector_id}/push_status_change")
+async def push_status_change(connector_id: str, payload: PushStatusChangeRequest):
+ """Project an AiSOC status transition onto a previously-pushed ticket.
+
+ If ``external_ref`` is None we delegate to ``push_case`` (i.e. the
+ case is being reported to this ITSM for the first time as part of
+ the same status update). Otherwise we patch the existing ticket.
+ The connector decides which fields to map (state code, resolution,
+ close notes, etc.).
+ """
+ cls = CONNECTOR_REGISTRY.get(connector_id)
+ if cls is None:
+ raise HTTPException(status_code=404, detail=f"Connector '{connector_id}' not found")
+ _require_capability(cls, Capability.PUSH_STATUS, connector_id)
+
+ kwargs = {**payload.auth_config, **payload.connector_config}
+ connector = _instantiate_or_422(cls, kwargs)
+
+ try:
+ result = await connector.push_status_change(
+ payload.case,
+ payload.old_status,
+ payload.new_status,
+ external_ref=payload.external_ref,
+ )
+ except NotImplementedError as exc:
+ raise HTTPException(status_code=status.HTTP_501_NOT_IMPLEMENTED, detail=str(exc)) from exc
+ except ValueError as exc:
+ # e.g. servicenow.push_status_change rejecting a missing sys_id.
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+ except Exception:
+ logger.exception(
+ "connector.push_status_change.runtime_error",
+ connector_id=_safe_log_val(connector_id),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail="Status sync to external ITSM failed. Check connector configuration and connectivity.",
+ )
+
+ if not isinstance(result, dict):
+ raise HTTPException(
+ status_code=status.HTTP_502_BAD_GATEWAY,
+ detail=f"connector '{connector_id}' returned unexpected push_status_change payload",
+ )
+ return result
+
+
@router.get("/health")
async def health():
return {"status": "healthy", "service": "aisoc-connectors"}
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index e45838109..085557f4f 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -377,3 +377,71 @@ class BaseConnector(ABC):
be indistinguishable from "no matches" and is a footgun).
"""
raise NotImplementedError(f"connector '{self.connector_id}' does not support federated search")
+
+ # ----------------------------- bidirectional ITSM (Workstream 8) ----------
+ #
+ # ``push_case`` mints an external ticket from an AiSOC case. Implementations
+ # MUST return an ``ExternalTicketRef`` so the API layer can persist the
+ # mapping in ``case_external_refs`` and avoid double-creation on retry.
+ #
+ # ``push_status_change`` projects an AiSOC status transition onto the
+ # external system (e.g. AiSOC ``resolved`` → Jira "Done", ServiceNow
+ # ``state=6``). Implementations are expected to be idempotent and tolerate
+ # the case where ``external_ref`` was created before the connector knew
+ # about the case (e.g. inbound webhook flow).
+ #
+ # Both methods are *gated* by ``Capability.PUSH_CASE`` /
+ # ``Capability.PUSH_STATUS`` from WS4. Connectors that don't declare those
+ # capabilities raise ``NotImplementedError`` from the defaults so the
+ # actions worker fails closed instead of silently skipping a case fan-out.
+
+ async def push_case(self, case: dict[str, Any]) -> dict[str, Any]:
+ """Create or update an external ticket from an AiSOC case.
+
+ Args:
+ case: A dict with at least ``id``, ``case_number``, ``title``,
+ ``description``, ``severity``, ``status``, plus optional
+ ``assignee``, ``tags``, ``mitre_techniques``, ``alert_ids``,
+ and any prior ``external_ref`` (if this is an update / retry
+ rather than a first-time push).
+
+ Returns:
+ ``{"external_id": str, "external_url": str|None, "vendor": str}``
+ so the API layer can persist the link.
+
+ Raises:
+ NotImplementedError: connector did not declare ``Capability.PUSH_CASE``.
+ """
+ raise NotImplementedError(
+ f"connector '{self.connector_id}' does not implement push_case"
+ )
+
+ async def push_status_change(
+ self,
+ case: dict[str, Any],
+ old_status: str,
+ new_status: str,
+ external_ref: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Project an AiSOC status transition onto the external ticket.
+
+ Args:
+ case: Same shape as ``push_case``'s argument.
+ old_status: AiSOC status the case is moving *from*. Useful for
+ detecting "open → closed" transitions that some ITSMs model
+ as a workflow action rather than a field write.
+ new_status: AiSOC status the case is moving *to*.
+ external_ref: ``{"external_id", "external_url", "vendor"}`` row
+ from ``case_external_refs``. ``None`` means "this case has
+ never been pushed before" — implementations may choose to
+ fall back to ``push_case`` in that situation.
+
+ Returns:
+ ``{"external_id", "external_url", "vendor", "external_status"}``.
+
+ Raises:
+ NotImplementedError: connector did not declare ``Capability.PUSH_STATUS``.
+ """
+ raise NotImplementedError(
+ f"connector '{self.connector_id}' does not implement push_status_change"
+ )
diff --git a/services/connectors/app/connectors/jira_connector.py b/services/connectors/app/connectors/jira_connector.py
index c69f2ae09..48d01f1bd 100644
--- a/services/connectors/app/connectors/jira_connector.py
+++ b/services/connectors/app/connectors/jira_connector.py
@@ -1,6 +1,7 @@
"""
Jira connector.
-Fetches security-relevant issues from Jira Cloud via the REST API.
+Fetches security-relevant issues from Jira Cloud via the REST API and,
+under Workstream 8, projects AiSOC cases / status changes back into Jira.
"""
from __future__ import annotations
@@ -24,6 +25,31 @@ _PRIORITY_SEVERITY = {
"Lowest": "info",
}
+# WS8: AiSOC severity → Jira priority. We invert ``_PRIORITY_SEVERITY``
+# but map ``critical`` → ``Highest`` because Jira doesn't have a separate
+# critical band and ``Highest`` is the highest tier available out of the
+# box. ``info`` collapses to ``Lowest`` for the same reason.
+_SEVERITY_TO_PRIORITY = {
+ "critical": "Highest",
+ "high": "High",
+ "medium": "Medium",
+ "low": "Low",
+ "info": "Lowest",
+}
+
+# WS8: AiSOC status → Jira status name. The values on the right match
+# the default Jira workflow ("To Do" / "In Progress" / "Done"). Customers
+# with custom workflows can override via ``connector_config.status_map``
+# in the future; for now we ship the defaults so the happy path Just Works.
+_STATUS_MAP_JIRA = {
+ "new": "To Do",
+ "triaged": "To Do",
+ "investigating": "In Progress",
+ "contained": "In Progress",
+ "resolved": "Done",
+ "closed": "Done",
+}
+
class JiraConnector(BaseConnector):
connector_id = "jira"
@@ -69,14 +95,20 @@ class JiraConnector(BaseConnector):
@classmethod
def capabilities(cls) -> tuple[Capability, ...]:
- # Today the Jira connector only pulls security-tagged issues as alerts.
- # Bidirectional ticketing (PUSH_CASE / PUSH_STATUS) lands in WS8.
- return (Capability.PULL_ALERTS,)
+ # WS8: bidirectional ticketing landed; Jira can now mint issues
+ # from AiSOC cases (PUSH_CASE) and project status transitions
+ # onto them (PUSH_STATUS) in addition to pulling alerts.
+ return (Capability.PULL_ALERTS, Capability.PUSH_CASE, Capability.PUSH_STATUS)
- def __init__(self, base_url: str, email: str, api_token: str):
+ def __init__(self, base_url: str, email: str, api_token: str, project_key: str | None = None):
self._base_url = base_url.rstrip("/")
self._email = email
self._api_token = api_token
+ # ``project_key`` is required for ``push_case`` (Jira REST won't
+ # accept an issue without one) but optional for the read path
+ # because pull-alerts works across all projects the user can
+ # see. We accept it lazily and only enforce it where it matters.
+ self._project_key = (project_key or "").strip() or None
def _auth_header(self) -> dict[str, str]:
creds = b64encode(f"{self._email}:{self._api_token}".encode()).decode()
@@ -142,3 +174,182 @@ class JiraConnector(BaseConnector):
"raw_event": raw,
"created_at": fields.get("created"),
}
+
+ # ------------------------------------------------------------------
+ # WS8: bidirectional ticket sync.
+ # ------------------------------------------------------------------
+ #
+ # Jira's REST API is well-documented but has a few gotchas the
+ # implementation defends against:
+ #
+ # 1. ``description`` MUST be in the Atlassian Document Format
+ # (ADF) on issue create — passing a raw string returns 400.
+ # We wrap whatever the case has in a minimal ADF doc.
+ # 2. Transitions (status changes) are NOT field writes. You have
+ # to ask Jira ``GET /issue/{key}/transitions`` to discover the
+ # transition ID for the target status, then POST it. We resolve
+ # that on each call rather than caching, because customers add
+ # transitions to their workflows all the time.
+ # 3. Issue keys (``ABC-123``) are stable identifiers we persist;
+ # the ``id`` field is an opaque numeric ID we do NOT use.
+
+ @staticmethod
+ def _adf_text(text: str) -> dict[str, Any]:
+ """Wrap plain text into a minimal Atlassian Document Format doc."""
+ return {
+ "type": "doc",
+ "version": 1,
+ "content": [
+ {"type": "paragraph", "content": [{"type": "text", "text": text or ""}]},
+ ],
+ }
+
+ def _issue_url(self, key: str) -> str:
+ """Best-effort browser URL for a Jira issue key."""
+ return f"{self._base_url}/browse/{key}"
+
+ async def push_case(self, case: dict[str, Any]) -> dict[str, Any]:
+ """Mint a Jira issue from an AiSOC case."""
+ if not self._project_key:
+ raise ValueError(
+ "jira.push_case: project_key not configured on connector instance"
+ )
+
+ severity = (case.get("severity") or "medium").lower()
+ title = case.get("title") or f"AiSOC case {case.get('case_number') or case.get('id')}"
+ description = case.get("description") or ""
+ case_id = case.get("id") or case.get("case_number")
+
+ payload = {
+ "fields": {
+ "project": {"key": self._project_key},
+ "summary": title[:255], # Jira summary cap.
+ "description": self._adf_text(description),
+ "issuetype": {"name": "Task"},
+ "priority": {"name": _SEVERITY_TO_PRIORITY.get(severity, "Medium")},
+ # ``labels`` is the cheapest way to round-trip the AiSOC
+ # case identifier without requiring a custom field. The
+ # inbound webhook can then strip the prefix to find us.
+ "labels": [f"aisoc-case-{case_id}", "aisoc"],
+ }
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(
+ f"{self._base_url}/rest/api/3/issue",
+ headers=self._auth_header(),
+ json=payload,
+ )
+ if resp.status_code >= 400:
+ raise httpx.HTTPStatusError(
+ f"jira.push_case failed: {resp.status_code} {resp.text[:300]}",
+ request=resp.request,
+ response=resp,
+ )
+ data = resp.json()
+
+ key = data.get("key")
+ return {
+ "external_id": key,
+ "external_url": self._issue_url(key) if key else None,
+ "vendor": self.connector_id,
+ "external_status": "To Do",
+ }
+
+ async def _resolve_transition_id(
+ self,
+ client: httpx.AsyncClient,
+ issue_key: str,
+ target_name: str,
+ ) -> str | None:
+ """Look up the transition ID whose target status matches ``target_name``.
+
+ Returns ``None`` if Jira's workflow doesn't expose a transition
+ to that status — the caller MUST treat that as a no-op rather
+ than retrying, because no amount of retrying will change the
+ workflow.
+ """
+ resp = await client.get(
+ f"{self._base_url}/rest/api/3/issue/{issue_key}/transitions",
+ headers=self._auth_header(),
+ )
+ resp.raise_for_status()
+ transitions = resp.json().get("transitions", [])
+ target_lower = target_name.lower()
+ for t in transitions:
+ # Match on either the transition name ("Done") or the target
+ # status name (``to.name``); customers rename one but not the
+ # other surprisingly often.
+ t_name = (t.get("name") or "").lower()
+ to_name = ((t.get("to") or {}).get("name") or "").lower()
+ if t_name == target_lower or to_name == target_lower:
+ return t.get("id")
+ return None
+
+ async def push_status_change(
+ self,
+ case: dict[str, Any],
+ old_status: str,
+ new_status: str,
+ external_ref: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Project an AiSOC status transition onto a Jira issue."""
+ if external_ref is None:
+ # First-time push: fall through to ``push_case`` so the
+ # caller doesn't have to special-case "no link yet".
+ return await self.push_case(case)
+
+ issue_key = (external_ref or {}).get("external_id")
+ if not issue_key:
+ raise ValueError("jira.push_status_change: external_ref missing external_id")
+
+ target_name = _STATUS_MAP_JIRA.get(new_status, "")
+ if not target_name:
+ # Unknown AiSOC status → no-op rather than throwing, since
+ # the contract is "best effort projection" not "schema match".
+ logger.info(
+ "jira.push_status_change.no_mapping",
+ external_id=issue_key,
+ old=old_status,
+ new=new_status,
+ )
+ return {
+ "external_id": issue_key,
+ "external_url": self._issue_url(issue_key),
+ "vendor": self.connector_id,
+ "external_status": (external_ref or {}).get("external_status"),
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ transition_id = await self._resolve_transition_id(client, issue_key, target_name)
+ if transition_id is None:
+ logger.warning(
+ "jira.push_status_change.no_transition",
+ external_id=issue_key,
+ target=target_name,
+ )
+ return {
+ "external_id": issue_key,
+ "external_url": self._issue_url(issue_key),
+ "vendor": self.connector_id,
+ "external_status": (external_ref or {}).get("external_status"),
+ }
+
+ resp = await client.post(
+ f"{self._base_url}/rest/api/3/issue/{issue_key}/transitions",
+ headers=self._auth_header(),
+ json={"transition": {"id": transition_id}},
+ )
+ if resp.status_code >= 400:
+ raise httpx.HTTPStatusError(
+ f"jira.push_status_change failed: {resp.status_code} {resp.text[:300]}",
+ request=resp.request,
+ response=resp,
+ )
+
+ return {
+ "external_id": issue_key,
+ "external_url": self._issue_url(issue_key),
+ "vendor": self.connector_id,
+ "external_status": target_name,
+ }
diff --git a/services/connectors/app/connectors/servicenow.py b/services/connectors/app/connectors/servicenow.py
index 144351de0..10eb3494d 100644
--- a/services/connectors/app/connectors/servicenow.py
+++ b/services/connectors/app/connectors/servicenow.py
@@ -1,6 +1,9 @@
"""
ServiceNow connector.
-Fetches security-relevant incidents from the ServiceNow Table API.
+
+Fetches security-relevant incidents from the ServiceNow Table API and,
+under Workstream 8, projects AiSOC cases / status changes back into
+ServiceNow as ``incident`` records.
"""
from __future__ import annotations
@@ -22,6 +25,34 @@ _IMPACT_SEVERITY = {
"3": "low",
}
+# WS8: AiSOC severity → ServiceNow ``impact`` numeric code. ServiceNow
+# uses 1=High, 2=Medium, 3=Low. We collapse ``critical`` and ``high``
+# onto 1 because the OOTB incident table doesn't have a separate
+# critical band, and ``info`` collapses onto 3 (Low) — there's no
+# "informational" tier in the standard schema.
+_SEVERITY_TO_IMPACT = {
+ "critical": "1",
+ "high": "1",
+ "medium": "2",
+ "low": "3",
+ "info": "3",
+}
+
+# WS8: AiSOC status → ServiceNow ``state`` numeric code. The default
+# ServiceNow incident state field is a numeric choice list:
+# 1=New, 2=In Progress, 3=On Hold, 6=Resolved, 7=Closed, 8=Canceled.
+# We map AiSOC's lifecycle onto that vocabulary. Customers with custom
+# state lists can override via ``connector_config.state_map`` in a
+# future iteration; the defaults below cover the OOTB table.
+_STATUS_MAP_SNOW = {
+ "new": "1",
+ "triaged": "2",
+ "investigating": "2",
+ "contained": "2",
+ "resolved": "6",
+ "closed": "7",
+}
+
class ServiceNowConnector(BaseConnector):
connector_id = "servicenow"
@@ -50,9 +81,11 @@ class ServiceNowConnector(BaseConnector):
@classmethod
def capabilities(cls) -> tuple[Capability, ...]:
- # Today the runtime only pulls incidents (alerts). Bidirectional ITSM
- # — PUSH_CASE / PUSH_STATUS — lands in WS8 once we wire writebacks.
- return (Capability.PULL_ALERTS,)
+ # WS8: bidirectional ticketing landed; ServiceNow can now mint
+ # incidents from AiSOC cases (PUSH_CASE) and project status
+ # transitions onto them (PUSH_STATUS) in addition to pulling
+ # incidents.
+ return (Capability.PULL_ALERTS, Capability.PUSH_CASE, Capability.PUSH_STATUS)
def __init__(self, instance_url: str, username: str, password: str):
self._base_url = instance_url.rstrip("/")
@@ -117,3 +150,142 @@ class ServiceNowConnector(BaseConnector):
"raw_event": raw,
"created_at": raw.get("sys_created_on"),
}
+
+ # ------------------------------------------------------------------
+ # WS8: bidirectional ticket sync.
+ # ------------------------------------------------------------------
+ #
+ # ServiceNow's Table API is uniform across record types — POST to
+ # ``/api/now/table/incident`` to create, PATCH to
+ # ``/api/now/table/incident/{sys_id}`` to update. The implementation
+ # below intentionally targets the OOTB ``incident`` table because
+ # that's what 95% of customers use for security work; an enterprise
+ # using ``sn_si_incident`` (Security Incident Response) can override
+ # ``_table`` once we expose it as a config field.
+ #
+ # Two ServiceNow-specific gotchas the code defends against:
+ #
+ # 1. Records are identified by ``sys_id`` (a 32-char hex GUID),
+ # NOT by ``number`` (e.g. ``INC0010023``). We persist
+ # ``sys_id`` as the external_id and surface ``number`` only
+ # in the URL the operator clicks.
+ # 2. State transitions can fail silently if the customer's UI
+ # policy requires a ``close_code`` / ``close_notes`` for
+ # Resolved/Closed states. We send minimal close metadata when
+ # transitioning to those states so the API call doesn't bounce.
+
+ _table = "incident"
+
+ def _record_url(self, sys_id: str, number: str | None = None) -> str:
+ """Best-effort browser URL for a ServiceNow incident."""
+ if number:
+ return f"{self._base_url}/nav_to.do?uri=incident.do?sys_id={sys_id}"
+ return f"{self._base_url}/{self._table}.do?sys_id={sys_id}"
+
+ async def push_case(self, case: dict[str, Any]) -> dict[str, Any]:
+ """Mint a ServiceNow incident from an AiSOC case."""
+ severity = (case.get("severity") or "medium").lower()
+ title = case.get("title") or f"AiSOC case {case.get('case_number') or case.get('id')}"
+ description = case.get("description") or ""
+ case_id = case.get("id") or case.get("case_number")
+
+ payload: dict[str, Any] = {
+ "short_description": title[:160], # ServiceNow short_description cap.
+ "description": description,
+ "impact": _SEVERITY_TO_IMPACT.get(severity, "2"),
+ "urgency": _SEVERITY_TO_IMPACT.get(severity, "2"),
+ # Round-trip the AiSOC case identifier in ``correlation_id``
+ # so the inbound webhook can find us without a custom field.
+ "correlation_id": f"aisoc:{case_id}",
+ "correlation_display": "AiSOC",
+ }
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.post(
+ f"{self._base_url}/api/now/table/{self._table}",
+ headers={
+ **self._auth_header(),
+ "Content-Type": "application/json",
+ },
+ json=payload,
+ )
+ if resp.status_code >= 400:
+ raise httpx.HTTPStatusError(
+ f"servicenow.push_case failed: {resp.status_code} {resp.text[:300]}",
+ request=resp.request,
+ response=resp,
+ )
+ data = (resp.json() or {}).get("result", {})
+
+ sys_id = data.get("sys_id") or ""
+ number = data.get("number")
+ return {
+ "external_id": sys_id,
+ "external_url": self._record_url(sys_id, number) if sys_id else None,
+ "vendor": self.connector_id,
+ "external_status": data.get("state") or "1",
+ }
+
+ async def push_status_change(
+ self,
+ case: dict[str, Any],
+ old_status: str,
+ new_status: str,
+ external_ref: dict[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ """Project an AiSOC status transition onto a ServiceNow incident."""
+ if external_ref is None:
+ return await self.push_case(case)
+
+ sys_id = (external_ref or {}).get("external_id")
+ if not sys_id:
+ raise ValueError("servicenow.push_status_change: external_ref missing external_id")
+
+ target_state = _STATUS_MAP_SNOW.get(new_status)
+ if not target_state:
+ logger.info(
+ "servicenow.push_status_change.no_mapping",
+ external_id=sys_id,
+ old=old_status,
+ new=new_status,
+ )
+ return {
+ "external_id": sys_id,
+ "external_url": self._record_url(sys_id),
+ "vendor": self.connector_id,
+ "external_status": (external_ref or {}).get("external_status"),
+ }
+
+ payload: dict[str, Any] = {"state": target_state}
+ # Resolved/Closed states require close_code + close_notes on
+ # most stock ServiceNow instances or the API silently ignores
+ # the state change. Send a benign default so the transition
+ # actually applies.
+ if target_state in {"6", "7"}:
+ payload["close_code"] = "Closed/Resolved by Caller"
+ payload["close_notes"] = (
+ f"Closed by AiSOC (case {case.get('case_number') or case.get('id')})"
+ )
+
+ async with httpx.AsyncClient(timeout=30.0) as client:
+ resp = await client.patch(
+ f"{self._base_url}/api/now/table/{self._table}/{sys_id}",
+ headers={
+ **self._auth_header(),
+ "Content-Type": "application/json",
+ },
+ json=payload,
+ )
+ if resp.status_code >= 400:
+ raise httpx.HTTPStatusError(
+ f"servicenow.push_status_change failed: {resp.status_code} {resp.text[:300]}",
+ request=resp.request,
+ response=resp,
+ )
+
+ return {
+ "external_id": sys_id,
+ "external_url": self._record_url(sys_id),
+ "vendor": self.connector_id,
+ "external_status": target_state,
+ }