WITH classified AS ( SELECT a.tenant_id,a.asset_id,a.agent_id,a.created_at,a.revoked_at,a.last_contact_at, a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256, a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version, a.system_usage,a.system_usage_observed_at, asset.archived_at,t.name AS customer_name, CASE WHEN a.revoked_at IS NOT NULL THEN 'revoked' WHEN asset.archived_at IS NOT NULL THEN 'archived' WHEN a.last_contact_at IS NULL THEN 'never_seen' WHEN a.last_authenticated_at IS NULL THEN 'unverified' WHEN EXISTS ( SELECT 1 FROM agent_installations newer WHERE newer.tenant_id=a.tenant_id AND newer.asset_id=a.asset_id AND newer.enrollment_generation>a.enrollment_generation AND newer.last_contact_at IS NOT NULL AND newer.last_authenticated_at IS NOT NULL AND newer.created_at<=$2 ) THEN 'replaced' ELSE 'current' END AS lifecycle, CASE WHEN a.last_contact_at IS NULL THEN 'never_seen' WHEN a.last_contact_at>$2::timestamptz-interval '90 seconds' THEN 'online' ELSE 'offline' END AS status FROM agent_installations a JOIN assets asset USING (tenant_id,asset_id) JOIN tenants t USING(tenant_id) WHERE a.tenant_id=$1 AND a.created_at<=$2 AND a.agent_id>$3 AND ($4::uuid IS NULL OR a.asset_id=$4) AND ($5::uuid IS NULL OR a.agent_id=$5) ) SELECT c.*,o.observed_at,o.received_at,o.data,o.source_id FROM classified c LEFT JOIN LATERAL ( SELECT observed_at,received_at,data,source_id FROM observations WHERE tenant_id=c.tenant_id AND agent_id=c.agent_id AND received_at<=$2 AND source_id IN ('linux.base','windows.base') ORDER BY observed_at DESC,received_at DESC,sequence DESC LIMIT 1 ) o ON true WHERE ($6::text IS NULL OR (c.lifecycle='current')=($6='current')) AND ($7::text IS NULL OR c.status=$7) AND ($8='' OR strpos(lower(o.data->>'hostname'),lower($8))>0) ORDER BY CASE WHEN $4 IS NOT NULL THEN (c.lifecycle='current') END DESC, CASE WHEN $4 IS NOT NULL THEN c.enrollment_generation END DESC, CASE WHEN $4 IS NOT NULL THEN c.created_at END DESC, c.agent_id LIMIT $9