{
  "id": "fix-3755-durable-inbound-finalize",
  "title": "Trusted HubSpot inbound finalizes Lead and Contact identity atomically",
  "kind": "hubspot_sync",
  "optional": true,
  "targetedAcceptance": {
    "schemaVersion": "hubspot-targeted-acceptance/v1",
    "reason": "Approval-gated formal staging acceptance for isolated durable-identity fixtures."
  },
  "executionMode": "serial",
  "executionModeReason": "The case intentionally inspects and perturbs durable identity state on isolated run-scoped staging records.",
  "allowedTargetEnvironments": ["staging"],
  "caseTimeoutMs": 1200000,
  "linkedIssues": [3755],
  "provenance": {
    "businessScenario": "Formal staging acceptance for NexusCRM #3755. Ordinary authenticated HubSpot contact inbound must atomically commit the local owner, finalized remote link, and consumed authored evidence without an outbound attempt. The authoritative inverse resolver must still return that owner after the compatibility mirror is cleared. A pre-authored conflicting evidence fixture must fail closed and roll back the inbound local mutation and all new authority state.",
    "reportedBy": "NexusCRM #3755 formal staging contract",
    "capturedAt": "2026-07-18",
    "scope": "Staging sandbox only. No production mutation, repair, replay, or deployment. Account and Opportunity are verified as absent from the installed inbound Flow manifest rather than manufactured as inbound cases."
  },
  "steps": [
    {
      "id": "assert-installed-flow-surface",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT COALESCE(SUM(CASE WHEN DeveloperName = 'HubSpot_Contact_Lead_Upsert' AND IsDeleted = 0 AND ActiveVersionId IS NOT NULL THEN 1 ELSE 0 END), 0) AS ContactInboundActive, COALESCE(SUM(CASE WHEN DeveloperName = 'HubSpot_Company_Account_Upsert' AND IsDeleted = 0 AND ActiveVersionId IS NOT NULL THEN 1 ELSE 0 END), 0) AS AccountInboundActive, COALESCE(SUM(CASE WHEN DeveloperName = 'HubSpot_Deal_Opportunity_Upsert' AND IsDeleted = 0 AND ActiveVersionId IS NOT NULL THEN 1 ELSE 0 END), 0) AS OpportunityInboundActive FROM FlowDefinition WHERE DeveloperName IN ('HubSpot_Contact_Lead_Upsert', 'HubSpot_Company_Account_Upsert', 'HubSpot_Deal_Opportunity_Upsert')",
      "expectStatus": 200,
      "assertions": [
        { "path": "response.body.records[0].ContactInboundActive", "numericEquals": 1 },
        { "path": "response.body.records[0].AccountInboundActive", "numericEquals": 0 },
        { "path": "response.body.records[0].OpportunityInboundActive", "numericEquals": 0 }
      ]
    },
    {
      "id": "assert-installed-contact-finalizers",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT JSON_LENGTH(JSON_SEARCH(CAST(F.Metadata AS JSON), 'all', 'finalizeConnectorInboundRemoteIdentity', NULL, '$**.actionName')) AS FinalizerCount FROM FlowDefinition FD JOIN Flow F ON F.Id = FD.ActiveVersionId WHERE FD.DeveloperName = 'HubSpot_Contact_Lead_Upsert' AND FD.IsDeleted = 0 AND F.IsDeleted = 0",
      "expectStatus": 200,
      "assertions": [
        { "path": "response.body.records[0].FinalizerCount", "numericEquals": 2 }
      ]
    },
    {
      "id": "create-lead-campaign",
      "system": "nexuscrm",
      "authRole": "admin",
      "method": "POST",
      "path": "/services/data/v63.0/sobjects/Campaign",
      "body": { "Name": "IT #3755 Lead {{__runId}}", "IsActive": true },
      "expectStatusRange": [200, 299],
      "assertions": [{ "path": "response.body.id", "exists": true }]
    },
    {
      "id": "create-lead-remote-contact",
      "system": "hubspot",
      "method": "POST",
      "path": "/crm/v3/objects/contacts/batch/create",
      "generate": {
        "count": 1,
        "into": "inputs",
        "itemTemplate": {
          "properties": {
            "email": "fix3755-lead-{{__runId}}@example.com",
            "firstname": "Fix3755",
            "lastname": "Lead{{__runId}}",
            "jobtitle": "Lead inbound finalized",
            "lifecyclestage": "lead"
          }
        }
      },
      "expectStatusRange": [200, 299],
      "assertions": [{ "path": "response.body.results", "lengthAtLeast": 1 }]
    },
    {
      "id": "assert-lead-atomic-authority",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT L.SourceRecordId, L.LinkKey, L.Status, L.SourceObject, P.FirstName, P.LastName, P.Email, P.Title, P.Lifecycle_Stage__c, P.HubSpot_Id__c, (SELECT COUNT(*) FROM `_System_ConnectorRemoteLink` X WHERE X.ConnectorOwnerKey = L.ConnectorOwnerKey AND X.RemoteId = L.RemoteId AND X.SourceObject = 'Lead' AND X.Status = 'finalized') AS FinalizedLinkCount, (SELECT COUNT(*) FROM `_System_ConnectorInboundRemoteIDEvidence` E WHERE E.ConnectorOwnerKey = L.ConnectorOwnerKey AND E.SourceObject = L.SourceObject AND E.SourceRecordId = L.SourceRecordId AND E.RemoteId = L.RemoteId AND E.EvidenceStatus = 'consumed' AND E.ConsumedByLinkKey = L.LinkKey AND E.ActiveKey IS NULL) AS ConsumedEvidenceCount, (SELECT COUNT(*) FROM `_System_ConnectorPushAttempt` A WHERE A.SourceObject = L.SourceObject AND A.SourceRecordId = L.SourceRecordId) AS AttemptCount, (SELECT COUNT(*) FROM Lead X WHERE X.HubSpot_Id__c = L.RemoteId AND X.IsConverted = 0 AND X.IsDeleted = 0) AS RemoteIdActiveLeadCount, (SELECT COUNT(*) FROM Lead X WHERE X.Email = 'fix3755-lead-{{__runId}}@example.com' AND X.IsConverted = 0 AND X.IsDeleted = 0) AS SameEmailActiveLeadCount FROM `_System_ConnectorRemoteLink` L JOIN Lead P ON P.Id = L.SourceRecordId AND P.IsConverted = 0 AND P.IsDeleted = 0 WHERE L.ConnectorOwnerKey = 'pingcap-hubspot-companion' AND L.RemoteId = '{{steps.create-lead-remote-contact.response.body.results[0].id}}' AND L.SourceObject = 'Lead' AND L.Status = 'finalized'",
      "expectStatus": 200,
      "poll": { "budgetMs": 240000, "intervalMs": 6000 },
      "onTimeout": "fail",
      "assertions": [
        { "path": "response.body.records", "lengthAtLeast": 1 },
        { "path": "response.body.records[0].Status", "equals": "finalized" },
        { "path": "response.body.records[0].SourceObject", "equals": "Lead" },
        { "path": "response.body.records[0].FirstName", "equals": "Fix3755" },
        { "path": "response.body.records[0].LastName", "equals": "Lead{{__runId}}" },
        { "path": "response.body.records[0].Email", "equals": "fix3755-lead-{{__runId}}@example.com" },
        { "path": "response.body.records[0].Title", "equals": "Lead inbound finalized" },
        { "path": "response.body.records[0].Lifecycle_Stage__c", "equals": "lead" },
        { "path": "response.body.records[0].HubSpot_Id__c", "equals": "{{steps.create-lead-remote-contact.response.body.results[0].id}}" },
        { "path": "response.body.records[0].FinalizedLinkCount", "numericEquals": 1 },
        { "path": "response.body.records[0].ConsumedEvidenceCount", "numericEquals": 1 },
        { "path": "response.body.records[0].AttemptCount", "numericEquals": 0 },
        { "path": "response.body.records[0].RemoteIdActiveLeadCount", "numericEquals": 1 },
        { "path": "response.body.records[0].SameEmailActiveLeadCount", "numericEquals": 1 }
      ]
    },
    {
      "id": "clear-lead-compatibility-mirror",
      "system": "tidb",
      "method": "POST",
      "sql": "UPDATE Lead SET HubSpot_Id__c = NULL WHERE Id = '{{steps.assert-lead-atomic-authority.response.body.records[0].SourceRecordId}}'",
      "expectStatus": 200
    },
    {
      "id": "resolve-lead-through-set-campaign",
      "system": "connector_action",
      "path": "/webhooks/hubspot-crm-connector/workflow-action",
      "forEach": "steps.create-lead-remote-contact.response.body.results",
      "contactIdField": "id",
      "emailField": "properties.email",
      "campaignId": "{{steps.create-lead-campaign.response.body.id}}",
      "status": "Sent",
      "concurrency": 1,
      "assertions": [
        { "path": "response.body.failedCount", "numericEquals": 0 },
        { "path": "response.body.acceptedCount", "numericEquals": 1 }
      ]
    },
    {
      "id": "assert-lead-inverse-owner",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT COUNT(*) AS ExactMemberCount, SUM(CASE WHEN P.HubSpot_Id__c IS NULL OR P.HubSpot_Id__c = '' THEN 1 ELSE 0 END) AS BlankMirrorMemberCount FROM CampaignMember CM JOIN Lead P ON P.Id = CM.LeadId WHERE CM.CampaignId = '{{steps.create-lead-campaign.response.body.id}}' AND CM.LeadId = '{{steps.assert-lead-atomic-authority.response.body.records[0].SourceRecordId}}' AND CM.ContactId IS NULL",
      "expectStatus": 200,
      "poll": { "budgetMs": 180000, "intervalMs": 6000 },
      "onTimeout": "fail",
      "assertions": [
        { "path": "response.body.records[0].ExactMemberCount", "numericEquals": 1 },
        { "path": "response.body.records[0].BlankMirrorMemberCount", "numericEquals": 1 }
      ]
    },
    {
      "id": "create-contact-owner",
      "system": "nexuscrm",
      "authRole": "admin",
      "method": "POST",
      "path": "/services/data/v63.0/sobjects/Contact",
      "body": {
        "LastName": "Contact{{__runId}}",
        "Email": "fix3755-contact-{{__runId}}@example.com",
        "Title": "Contact before inbound",
        "HubSpot_Sync_Enabled__c": false
      },
      "expectStatusRange": [200, 299],
      "assertions": [{ "path": "response.body.id", "exists": true }]
    },
    {
      "id": "create-contact-campaign",
      "system": "nexuscrm",
      "authRole": "admin",
      "method": "POST",
      "path": "/services/data/v63.0/sobjects/Campaign",
      "body": { "Name": "IT #3755 Contact {{__runId}}", "IsActive": true },
      "expectStatusRange": [200, 299],
      "assertions": [{ "path": "response.body.id", "exists": true }]
    },
    {
      "id": "create-contact-remote-contact",
      "system": "hubspot",
      "method": "POST",
      "path": "/crm/v3/objects/contacts/batch/create",
      "generate": {
        "count": 1,
        "into": "inputs",
        "itemTemplate": {
          "properties": {
            "email": "fix3755-contact-{{__runId}}@example.com",
            "firstname": "Fix3755",
            "lastname": "Contact{{__runId}}",
            "jobtitle": "Contact inbound finalized",
            "lifecyclestage": "lead"
          }
        }
      },
      "expectStatusRange": [200, 299],
      "assertions": [{ "path": "response.body.results", "lengthAtLeast": 1 }]
    },
    {
      "id": "assert-contact-atomic-authority",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT L.SourceRecordId, L.LinkKey, L.Status, L.SourceObject, P.FirstName, P.LastName, P.Email, P.Title, P.HubSpot_Id__c, (SELECT COUNT(*) FROM `_System_ConnectorRemoteLink` X WHERE X.ConnectorOwnerKey = L.ConnectorOwnerKey AND X.RemoteId = L.RemoteId AND X.SourceObject = 'Contact' AND X.Status = 'finalized') AS FinalizedLinkCount, (SELECT COUNT(*) FROM `_System_ConnectorInboundRemoteIDEvidence` E WHERE E.ConnectorOwnerKey = L.ConnectorOwnerKey AND E.SourceObject = L.SourceObject AND E.SourceRecordId = L.SourceRecordId AND E.RemoteId = L.RemoteId AND E.EvidenceStatus = 'consumed' AND E.ConsumedByLinkKey = L.LinkKey AND E.ActiveKey IS NULL) AS ConsumedEvidenceCount, (SELECT COUNT(*) FROM `_System_ConnectorPushAttempt` A WHERE A.SourceObject = L.SourceObject AND A.SourceRecordId = L.SourceRecordId) AS AttemptCount, (SELECT COUNT(*) FROM Contact X WHERE X.HubSpot_Id__c = L.RemoteId AND X.IsDeleted = 0) AS RemoteIdActiveContactCount, (SELECT COUNT(*) FROM Contact X WHERE X.Email = 'fix3755-contact-{{__runId}}@example.com' AND X.IsDeleted = 0) AS SameEmailActiveContactCount, (SELECT COUNT(*) FROM Lead X WHERE X.Email = 'fix3755-contact-{{__runId}}@example.com' AND X.IsConverted = 0 AND X.IsDeleted = 0) AS DuplicateLeadCount FROM `_System_ConnectorRemoteLink` L JOIN Contact P ON P.Id = L.SourceRecordId AND P.IsDeleted = 0 WHERE L.ConnectorOwnerKey = 'pingcap-hubspot-companion' AND L.RemoteId = '{{steps.create-contact-remote-contact.response.body.results[0].id}}' AND L.SourceObject = 'Contact' AND L.SourceRecordId = '{{steps.create-contact-owner.response.body.id}}' AND L.Status = 'finalized'",
      "expectStatus": 200,
      "poll": { "budgetMs": 240000, "intervalMs": 6000 },
      "onTimeout": "fail",
      "assertions": [
        { "path": "response.body.records", "lengthAtLeast": 1 },
        { "path": "response.body.records[0].Status", "equals": "finalized" },
        { "path": "response.body.records[0].SourceObject", "equals": "Contact" },
        { "path": "response.body.records[0].FirstName", "equals": "Fix3755" },
        { "path": "response.body.records[0].LastName", "equals": "Contact{{__runId}}" },
        { "path": "response.body.records[0].Email", "equals": "fix3755-contact-{{__runId}}@example.com" },
        { "path": "response.body.records[0].Title", "equals": "Contact inbound finalized" },
        { "path": "response.body.records[0].HubSpot_Id__c", "equals": "{{steps.create-contact-remote-contact.response.body.results[0].id}}" },
        { "path": "response.body.records[0].FinalizedLinkCount", "numericEquals": 1 },
        { "path": "response.body.records[0].ConsumedEvidenceCount", "numericEquals": 1 },
        { "path": "response.body.records[0].AttemptCount", "numericEquals": 0 },
        { "path": "response.body.records[0].RemoteIdActiveContactCount", "numericEquals": 1 },
        { "path": "response.body.records[0].SameEmailActiveContactCount", "numericEquals": 1 },
        { "path": "response.body.records[0].DuplicateLeadCount", "numericEquals": 0 }
      ]
    },
    {
      "id": "clear-contact-compatibility-mirror",
      "system": "tidb",
      "method": "POST",
      "sql": "UPDATE Contact SET HubSpot_Id__c = NULL WHERE Id = '{{steps.create-contact-owner.response.body.id}}'",
      "expectStatus": 200
    },
    {
      "id": "resolve-contact-through-set-campaign",
      "system": "connector_action",
      "path": "/webhooks/hubspot-crm-connector/workflow-action",
      "forEach": "steps.create-contact-remote-contact.response.body.results",
      "contactIdField": "id",
      "emailField": "properties.email",
      "campaignId": "{{steps.create-contact-campaign.response.body.id}}",
      "status": "Sent",
      "concurrency": 1,
      "assertions": [
        { "path": "response.body.failedCount", "numericEquals": 0 },
        { "path": "response.body.acceptedCount", "numericEquals": 1 }
      ]
    },
    {
      "id": "assert-contact-inverse-owner",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT COUNT(*) AS ExactMemberCount, SUM(CASE WHEN P.HubSpot_Id__c IS NULL OR P.HubSpot_Id__c = '' THEN 1 ELSE 0 END) AS BlankMirrorMemberCount FROM CampaignMember CM JOIN Contact P ON P.Id = CM.ContactId WHERE CM.CampaignId = '{{steps.create-contact-campaign.response.body.id}}' AND CM.ContactId = '{{steps.create-contact-owner.response.body.id}}' AND CM.LeadId IS NULL",
      "expectStatus": 200,
      "poll": { "budgetMs": 180000, "intervalMs": 6000 },
      "onTimeout": "fail",
      "assertions": [
        { "path": "response.body.records[0].ExactMemberCount", "numericEquals": 1 },
        { "path": "response.body.records[0].BlankMirrorMemberCount", "numericEquals": 1 }
      ]
    },
    {
      "id": "create-rollback-contact-owner",
      "system": "nexuscrm",
      "authRole": "admin",
      "method": "POST",
      "path": "/services/data/v63.0/sobjects/Contact",
      "body": {
        "LastName": "Rollback{{__runId}}",
        "Email": "fix3755-rollback-{{__runId}}@example.com",
        "Title": "Rollback before inbound",
        "HubSpot_Sync_Enabled__c": false
      },
      "expectStatusRange": [200, 299],
      "assertions": [{ "path": "response.body.id", "exists": true }]
    },
    {
      "id": "snapshot-rollback-contact-owner",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT SHA2(CONCAT_WS(CHAR(31), COALESCE(P.FirstName, '<NULL>'), COALESCE(P.LastName, '<NULL>'), COALESCE(P.Email, '<NULL>'), COALESCE(P.Title, '<NULL>'), COALESCE(P.Lifecycle_Stage__c, '<NULL>'), COALESCE(P.HubSpot_Id__c, '<NULL>'), COALESCE(CAST(P.HubSpot_Sync_Enabled__c AS CHAR), '<NULL>'), COALESCE(P.HubSpot_Owner_Id__c, '<NULL>'), COALESCE(P.OwnerId, '<NULL>'), CAST(P.IsDeleted AS CHAR)), 256) AS LocalStateHash FROM Contact P WHERE P.Id = '{{steps.create-rollback-contact-owner.response.body.id}}'",
      "expectStatus": 200,
      "assertions": [{ "path": "response.body.records", "lengthAtLeast": 1 }]
    },
    {
      "id": "seed-conflicting-authored-evidence",
      "system": "tidb",
      "method": "POST",
      "sql": "INSERT INTO `_System_ConnectorInboundRemoteIDEvidence` (Id, ConnectorOwnerKey, ConnectorNamespace, SourceObject, SourceRecordId, RemoteIDField, RemoteId, EvidenceStatus, ActiveKey) VALUES ('fix3755-rollback-evidence-{{__runId}}', 'pingcap-hubspot-companion', 'hubspot-crm-connector', 'Contact', '{{steps.create-rollback-contact-owner.response.body.id}}', 'HubSpot_Id__c', 'wrong-remote-{{__runId}}', 'authored', CONCAT('cie_active_v2:', SHA2(CONCAT('pingcap-hubspot-companion', CHAR(31), 'Contact', CHAR(31), '{{steps.create-rollback-contact-owner.response.body.id}}', CHAR(31), 'HubSpot_Id__c'), 256)))",
      "expectStatus": 200
    },
    {
      "id": "create-rollback-remote-contact",
      "system": "hubspot",
      "method": "POST",
      "path": "/crm/v3/objects/contacts/batch/create",
      "generate": {
        "count": 1,
        "into": "inputs",
        "itemTemplate": {
          "properties": {
            "email": "fix3755-rollback-{{__runId}}@example.com",
            "firstname": "Fix3755",
            "lastname": "RollbackChanged{{__runId}}",
            "jobtitle": "Rollback after inbound",
            "lifecyclestage": "lead"
          }
        }
      },
      "expectStatusRange": [200, 299],
      "assertions": [{ "path": "response.body.results", "lengthAtLeast": 1 }]
    },
    {
      "id": "assert-rollback-error-observed",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT COUNT(*) AS ErrorCount FROM `_System_ConnectorEvent` WHERE Namespace = 'hubspot-crm-connector' AND SourceObjectID = '{{steps.create-rollback-remote-contact.response.body.results[0].id}}' AND Status IN ('failed', 'dead') AND COALESCE(LastError, '') LIKE '%active inbound authorship evidence does not match%'",
      "expectStatus": 200,
      "poll": { "budgetMs": 240000, "intervalMs": 6000 },
      "onTimeout": "fail",
      "assertions": [{ "path": "response.body.records[0].ErrorCount", "atLeast": 1 }]
    },
    {
      "id": "assert-forced-rollback-state",
      "system": "tidb",
      "method": "GET",
      "sql": "SELECT (SELECT COUNT(*) FROM Contact P WHERE P.Id = '{{steps.create-rollback-contact-owner.response.body.id}}') AS LocalOwnerCount, (SELECT SHA2(CONCAT_WS(CHAR(31), COALESCE(P.FirstName, '<NULL>'), COALESCE(P.LastName, '<NULL>'), COALESCE(P.Email, '<NULL>'), COALESCE(P.Title, '<NULL>'), COALESCE(P.Lifecycle_Stage__c, '<NULL>'), COALESCE(P.HubSpot_Id__c, '<NULL>'), COALESCE(CAST(P.HubSpot_Sync_Enabled__c AS CHAR), '<NULL>'), COALESCE(P.HubSpot_Owner_Id__c, '<NULL>'), COALESCE(P.OwnerId, '<NULL>'), CAST(P.IsDeleted AS CHAR)), 256) FROM Contact P WHERE P.Id = '{{steps.create-rollback-contact-owner.response.body.id}}') AS CurrentLocalStateHash, (SELECT COUNT(*) FROM Lead P WHERE P.Email = 'fix3755-rollback-{{__runId}}@example.com' AND P.IsConverted = 0 AND P.IsDeleted = 0) AS DuplicateLeadCount, (SELECT COUNT(*) FROM `_System_ConnectorRemoteLink` L WHERE L.RemoteId = '{{steps.create-rollback-remote-contact.response.body.results[0].id}}' OR (L.SourceObject = 'Contact' AND L.SourceRecordId = '{{steps.create-rollback-contact-owner.response.body.id}}')) AS NewLinkCount, (SELECT COUNT(*) FROM `_System_ConnectorInboundRemoteIDEvidence` E WHERE E.Id = 'fix3755-rollback-evidence-{{__runId}}' AND E.RemoteId = 'wrong-remote-{{__runId}}' AND E.EvidenceStatus = 'authored' AND E.ConsumedByLinkKey IS NULL AND E.ActiveKey IS NOT NULL) AS OriginalAuthoredEvidenceCount, (SELECT COUNT(*) FROM `_System_ConnectorInboundRemoteIDEvidence` E WHERE E.SourceObject = 'Contact' AND E.SourceRecordId = '{{steps.create-rollback-contact-owner.response.body.id}}' AND E.RemoteId = '{{steps.create-rollback-remote-contact.response.body.results[0].id}}') AS NewExactEvidenceCount, (SELECT COUNT(*) FROM `_System_ConnectorPushAttempt` A WHERE A.SourceObject = 'Contact' AND A.SourceRecordId = '{{steps.create-rollback-contact-owner.response.body.id}}') AS AttemptCount",
      "expectStatus": 200,
      "assertions": [
        { "path": "response.body.records[0].LocalOwnerCount", "numericEquals": 1 },
        { "path": "response.body.records[0].CurrentLocalStateHash", "equals": "{{steps.snapshot-rollback-contact-owner.response.body.records[0].LocalStateHash}}" },
        { "path": "response.body.records[0].DuplicateLeadCount", "numericEquals": 0 },
        { "path": "response.body.records[0].NewLinkCount", "numericEquals": 0 },
        { "path": "response.body.records[0].OriginalAuthoredEvidenceCount", "numericEquals": 1 },
        { "path": "response.body.records[0].NewExactEvidenceCount", "numericEquals": 0 },
        { "path": "response.body.records[0].AttemptCount", "numericEquals": 0 }
      ]
    }
  ]
}
