// ../core/src/serviceIntelligence/types.ts
var SERVICE_INTELLIGENCE_REPORT_VERSION = 1;
var SERVICE_INTELLIGENCE_REPORT_KIND = "service_intelligence_report";
// ../core/src/contextLens/relationshipTaxonomy.ts
var CONNECTION_RELATIONSHIP_TYPE_REGISTRY = {
  related_to: { direction: "symmetric", riskLevel: "low" },
  knows: { direction: "symmetric", riskLevel: "low" },
  mentions: { direction: "symmetric", riskLevel: "low" },
  references: { direction: "symmetric", riskLevel: "low" },
  contradicts: { direction: "symmetric", riskLevel: "high" },
  owns: { direction: "directed", riskLevel: "medium" },
  owned_by: { direction: "directed", riskLevel: "medium" },
  depends_on: { direction: "directed", riskLevel: "medium" },
  implements: { direction: "directed", riskLevel: "medium" },
  documents: { direction: "directed", riskLevel: "medium" },
  calls: { direction: "directed", riskLevel: "medium" },
  imports: { direction: "directed", riskLevel: "medium" },
  affects: { direction: "directed", riskLevel: "medium" },
  affected_by: { direction: "directed", riskLevel: "medium" },
  uses: { direction: "directed", riskLevel: "medium" },
  uses_context: { direction: "directed", riskLevel: "medium" },
  supports: { direction: "directed", riskLevel: "medium" },
  tested_by: { direction: "directed", riskLevel: "medium" },
  covers: { direction: "directed", riskLevel: "medium" },
  verifies: { direction: "directed", riskLevel: "medium" },
  deploys: { direction: "directed", riskLevel: "medium" },
  configures: { direction: "directed", riskLevel: "medium" },
  publishes_to: { direction: "directed", riskLevel: "medium" },
  subscribes_to: { direction: "directed", riskLevel: "medium" },
  reads_from: { direction: "directed", riskLevel: "medium" },
  observes: { direction: "directed", riskLevel: "medium" },
  authenticates: { direction: "directed", riskLevel: "high" },
  authorizes: { direction: "directed", riskLevel: "high" },
  supersedes: { direction: "directed", riskLevel: "high" },
  source_of_truth_for: { direction: "directed", riskLevel: "high" },
  replaces: { direction: "directed", riskLevel: "high" },
  blocks: { direction: "directed", riskLevel: "high" },
  blocked_by: { direction: "directed", riskLevel: "high" },
  writes_to: { direction: "directed", riskLevel: "medium" },
  stores_in: { direction: "directed", riskLevel: "medium" },
  policy_for: { direction: "directed", riskLevel: "high" }
};
var CONNECTION_RELATIONSHIP_TYPES = Object.keys(CONNECTION_RELATIONSHIP_TYPE_REGISTRY);
function sanitizeConnectionRelationshipType(value) {
  if (typeof value !== "string")
    return null;
  const normalized = value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
  return normalized.length > 0 ? normalized : null;
}

// ../core/src/contextLens/serviceConnections.ts
var SERVICE_CONNECTION_OTEL_IDENTITY_KEYS = {
  serviceName: "service.name",
  serviceNamespace: "service.namespace",
  serviceVersion: "service.version",
  deploymentEnvironment: "deployment.environment.name"
};
var SERVICE_CONNECTION_IDENTITY_SCOPES = ["logical_service", "deployment_environment"];
var DEFAULT_SERVICE_CONNECTION_IDENTITY_SCOPE = "logical_service";
var SERVICE_CONNECTION_LIFECYCLE_STATES = [
  "hint",
  "candidate",
  "verified",
  "stale",
  "rejected",
  "retracted"
];
var DEFAULT_SERVICE_CONNECTION_LIFECYCLE_STATE = "hint";
var SERVICE_CONNECTION_OBSERVATION_STATUSES = [
  "present",
  "absent_in_latest_scan",
  "changed",
  "unknown"
];
var SERVICE_CONNECTION_SENSITIVITY_LEVELS = ["public", "internal", "sensitive", "secret"];
var SERVICE_CONNECTION_RELATIONSHIP_TYPES = [
  "publishes_to",
  "subscribes_to",
  "writes_to",
  "stores_in",
  "reads_from",
  "observes",
  "blocked_by"
];
var SERVICE_CONNECTION_RELATIONSHIP_SEMANTICS = {
  publishes_to: {
    relationshipType: "publishes_to",
    sourceDisplayLabel: "publishes to",
    inverseDisplayLabel: "receives publications from",
    sourceServiceMeaning: "The source service emits messages/events to the target service resource or broker surface."
  },
  subscribes_to: {
    relationshipType: "subscribes_to",
    sourceDisplayLabel: "subscribes to",
    inverseDisplayLabel: "has subscriber",
    sourceServiceMeaning: "The source service consumes messages/events from the target service resource or broker surface."
  },
  writes_to: {
    relationshipType: "writes_to",
    sourceDisplayLabel: "writes to",
    inverseDisplayLabel: "is written by",
    sourceServiceMeaning: "The source service mutates or sends write operations to the target resource."
  },
  stores_in: {
    relationshipType: "stores_in",
    sourceDisplayLabel: "stores in",
    inverseDisplayLabel: "stores data for",
    sourceServiceMeaning: "The source service persists durable data in the target storage resource."
  },
  reads_from: {
    relationshipType: "reads_from",
    sourceDisplayLabel: "reads from",
    inverseDisplayLabel: "is read by",
    sourceServiceMeaning: "The source service reads or queries data from the target resource without implying mutation."
  },
  observes: {
    relationshipType: "observes",
    sourceDisplayLabel: "observes",
    inverseDisplayLabel: "is observed by",
    sourceServiceMeaning: "The source service sends telemetry or monitoring signals to the target observability surface."
  },
  blocked_by: {
    relationshipType: "blocked_by",
    sourceDisplayLabel: "is blocked by",
    inverseDisplayLabel: "blocks",
    sourceServiceMeaning: "The source service depends on a missing, failing, policy-restricted, or sensitive target surface before progress can continue."
  }
};
var SERVICE_CONNECTION_ENDPOINT_KINDS = ["service", "resource"];
var SERVICE_CONNECTION_SURFACE_KINDS = [
  "api",
  "queue",
  "topic",
  "stream",
  "datastore",
  "cache",
  "object_store",
  "observability_sink",
  "config",
  "secret",
  "feature_flag",
  "runtime",
  "external_service",
  "unknown"
];
var SERVICE_CONNECTION_EVIDENCE_SOURCE_KINDS = [
  "code_static",
  "config_static",
  "runtime_receipt",
  "manual_report",
  "semantic_advisory"
];
var SERVICE_CONNECTION_EVIDENCE_TIERS = [
  "explicit_user_action",
  "accepted_truth_candidate",
  "deterministic_code_edge",
  "receipt_backed",
  "explicit_source_language",
  "repeated_reference",
  "llm_classification",
  "co_mention",
  "vector_similarity"
];
var SERVICE_CONNECTION_CANDIDATE_KINDS = [
  "http_api",
  "database",
  "auth_provider",
  "provider_client",
  "object_store",
  "queue_topic",
  "cache",
  "secret_config",
  "observability_sink",
  "runtime_owner",
  "test_proof",
  "doc_proof",
  "unknown_service_surface"
];
var SERVICE_CONNECTION_DIRECTION_HINTS = [
  "inbound_api",
  "outbound_provider",
  "reads_secret",
  "reads_datastore",
  "writes_datastore",
  "publishes_queue",
  "consumes_queue",
  "reads_cache",
  "writes_cache",
  "emits_telemetry",
  "owns_runtime",
  "proves_with_test",
  "documents",
  "unknown"
];
var SERVICE_CONNECTION_STATIC_EVIDENCE_TIERS = [
  "path_only",
  "import_backed",
  "call_backed",
  "env_backed",
  "schema_backed",
  "test_backed",
  "doc_backed",
  "mixed_backed"
];
var DEFAULT_SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND = "code_static";
var FALLBACK_SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND = "semantic_advisory";
var DEFAULT_SERVICE_CONNECTION_STATE = "observed";
var SERVICE_CONNECTION_EVIDENCE_SOURCE_CAPS = {
  maxSourcesPerConnection: 8,
  maxMetadataKeys: 20,
  maxSummaryLength: 240
};
var SERVICE_CONNECTION_EVIDENCE_SOURCE_DEFAULTS = {
  code_static: {
    label: "Static code evidence",
    evidenceTier: "deterministic_code_edge",
    defaultConfidence: 0.82,
    state: "high_confidence_hint"
  },
  config_static: {
    label: "Static configuration evidence",
    evidenceTier: "explicit_source_language",
    defaultConfidence: 0.75,
    state: "usable_hint"
  },
  runtime_receipt: {
    label: "Runtime receipt evidence",
    evidenceTier: "receipt_backed",
    defaultConfidence: 0.8,
    state: "high_confidence_hint"
  },
  manual_report: {
    label: "Manual report",
    evidenceTier: "explicit_user_action",
    defaultConfidence: 0.8,
    state: "review_candidate"
  },
  semantic_advisory: {
    label: "Semantic advisory",
    evidenceTier: "llm_classification",
    defaultConfidence: 0.5,
    confidenceCap: 0.84,
    state: "observed"
  }
};
var SERVICE_CONNECTION_RELATIONSHIP_TYPE_SET = new Set(SERVICE_CONNECTION_RELATIONSHIP_TYPES);
var SERVICE_CONNECTION_ENDPOINT_KIND_SET = new Set(SERVICE_CONNECTION_ENDPOINT_KINDS);
var SERVICE_CONNECTION_SURFACE_KIND_SET = new Set(SERVICE_CONNECTION_SURFACE_KINDS);
var SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND_SET = new Set(SERVICE_CONNECTION_EVIDENCE_SOURCE_KINDS);
var SERVICE_CONNECTION_EVIDENCE_TIER_SET = new Set(SERVICE_CONNECTION_EVIDENCE_TIERS);
var SERVICE_CONNECTION_CANDIDATE_KIND_SET = new Set(SERVICE_CONNECTION_CANDIDATE_KINDS);
var SERVICE_CONNECTION_DIRECTION_HINT_SET = new Set(SERVICE_CONNECTION_DIRECTION_HINTS);
var SERVICE_CONNECTION_STATIC_EVIDENCE_TIER_SET = new Set(SERVICE_CONNECTION_STATIC_EVIDENCE_TIERS);
var SERVICE_CONNECTION_IDENTITY_SCOPE_SET = new Set(SERVICE_CONNECTION_IDENTITY_SCOPES);
var SERVICE_CONNECTION_LIFECYCLE_STATE_SET = new Set(SERVICE_CONNECTION_LIFECYCLE_STATES);
var SERVICE_CONNECTION_CONNECTED_WORK_STATE_SET = new Set([
  "observed",
  "usable_hint",
  "high_confidence_hint",
  "review_candidate",
  "canonical",
  "dismissed",
  "stale",
  "conflicted",
  "invalidated"
]);
var SERVICE_CONNECTION_OBSERVATION_STATUS_SET = new Set(SERVICE_CONNECTION_OBSERVATION_STATUSES);
var SERVICE_CONNECTION_SENSITIVITY_LEVEL_SET = new Set(SERVICE_CONNECTION_SENSITIVITY_LEVELS);
var SERVICE_CONNECTION_SURFACE_KIND_ALIASES = {
  api: ["api", "http", "rest", "graphql", "route", "endpoint", "webhook", "callback"],
  queue: ["queue", "sqs", "worker", "job"],
  topic: ["topic", "pubsub", "kafka", "nats"],
  stream: ["stream", "event", "events", "kinesis", "topic"],
  datastore: ["datastore", "database", "db", "postgres", "mysql", "sqlite", "convex", "table", "sql", "neo4j", "memgraph"],
  cache: ["cache", "redis", "kv"],
  object_store: ["object", "bucket", "blob", "s3", "r2", "storage"],
  observability_sink: ["observability", "sink", "log", "logs", "metric", "metrics", "trace", "tracing", "monitor", "alert"],
  config: ["config", "configuration", "settings", "env"],
  secret: ["secret", "credential", "credentials", "token", "password", "api_key", "apikey", "private_key"],
  feature_flag: ["feature", "flag", "feature_flag", "launchdarkly", "split"],
  runtime: ["runtime", "scheduler", "schedule", "cron", "worker", "function"],
  external_service: ["external", "third-party", "third_party", "vendor", "saas"],
  unknown: ["unknown"]
};
function normalizeOptionalString(value) {
  if (typeof value !== "string")
    return;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}
function normalizeStringArray(value, cap = 20) {
  if (!Array.isArray(value))
    return;
  const items = value.map(normalizeOptionalString).filter((item) => Boolean(item)).slice(0, cap);
  return items.length > 0 ? items : undefined;
}
function normalizeFiniteNumber(value) {
  return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function recordFromUnknown(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
}
function normalizeIdentityScope(value) {
  if (typeof value !== "string")
    return DEFAULT_SERVICE_CONNECTION_IDENTITY_SCOPE;
  return SERVICE_CONNECTION_IDENTITY_SCOPE_SET.has(value) ? value : DEFAULT_SERVICE_CONNECTION_IDENTITY_SCOPE;
}
function normalizeServiceConnectionLifecycleState(value, fallback = DEFAULT_SERVICE_CONNECTION_LIFECYCLE_STATE) {
  if (typeof value !== "string")
    return fallback;
  return SERVICE_CONNECTION_LIFECYCLE_STATE_SET.has(value) ? value : fallback;
}
function normalizeConnectedWorkState(value) {
  return typeof value === "string" && SERVICE_CONNECTION_CONNECTED_WORK_STATE_SET.has(value) ? value : undefined;
}
function serviceConnectionLifecycleStateFromConnectedWorkState(state) {
  switch (state) {
    case "review_candidate":
      return "candidate";
    case "high_confidence_hint":
    case "canonical":
      return "verified";
    case "stale":
      return "stale";
    case "dismissed":
    case "conflicted":
    case "invalidated":
      return "rejected";
    case "observed":
    case "usable_hint":
    default:
      return "hint";
  }
}
function connectedWorkStateForServiceConnectionLifecycleState(lifecycleState) {
  switch (lifecycleState) {
    case "candidate":
      return "review_candidate";
    case "verified":
      return "high_confidence_hint";
    case "stale":
      return "stale";
    case "rejected":
    case "retracted":
      return "invalidated";
    case "hint":
    default:
      return DEFAULT_SERVICE_CONNECTION_STATE;
  }
}
function normalizeObservationStatus(value) {
  if (typeof value !== "string")
    return;
  return SERVICE_CONNECTION_OBSERVATION_STATUS_SET.has(value) ? value : undefined;
}
function normalizeCandidateKind(value) {
  return typeof value === "string" && SERVICE_CONNECTION_CANDIDATE_KIND_SET.has(value) ? value : undefined;
}
function normalizeDirectionHint(value) {
  return typeof value === "string" && SERVICE_CONNECTION_DIRECTION_HINT_SET.has(value) ? value : undefined;
}
function normalizeStaticEvidenceTier(value) {
  return typeof value === "string" && SERVICE_CONNECTION_STATIC_EVIDENCE_TIER_SET.has(value) ? value : undefined;
}
function normalizeSensitivityLevel(value) {
  if (typeof value !== "string")
    return;
  return SERVICE_CONNECTION_SENSITIVITY_LEVEL_SET.has(value) ? value : undefined;
}
function normalizeServiceConnectionIdentityMetadata(value) {
  const record = recordFromUnknown(value);
  if (!record)
    return;
  const serviceName = normalizeOptionalString(record["serviceName"] ?? record[SERVICE_CONNECTION_OTEL_IDENTITY_KEYS.serviceName]);
  const serviceNamespace = normalizeOptionalString(record["serviceNamespace"] ?? record[SERVICE_CONNECTION_OTEL_IDENTITY_KEYS.serviceNamespace]);
  const serviceVersion = normalizeOptionalString(record["serviceVersion"] ?? record[SERVICE_CONNECTION_OTEL_IDENTITY_KEYS.serviceVersion]);
  const deploymentEnvironment = normalizeOptionalString(record["deploymentEnvironment"] ?? record[SERVICE_CONNECTION_OTEL_IDENTITY_KEYS.deploymentEnvironment]);
  const canonicalLogicalServiceId = deriveCanonicalLogicalServiceId({ serviceName, serviceNamespace });
  if (!serviceName && !serviceNamespace && !serviceVersion && !deploymentEnvironment)
    return;
  return { serviceName, serviceNamespace, serviceVersion, deploymentEnvironment, canonicalLogicalServiceId };
}
function normalizeServiceConnectionScopeMetadata(value) {
  const record = recordFromUnknown(value);
  if (!record)
    return;
  const scope = {
    identityScope: normalizeIdentityScope(record["identityScope"]),
    deploymentEnvironment: normalizeOptionalString(record["deploymentEnvironment"] ?? record[SERVICE_CONNECTION_OTEL_IDENTITY_KEYS.deploymentEnvironment]),
    region: normalizeOptionalString(record["region"]),
    cluster: normalizeOptionalString(record["cluster"]),
    account: normalizeOptionalString(record["account"]),
    tenant: normalizeOptionalString(record["tenant"])
  };
  return Object.values(scope).some((item) => item !== undefined) ? scope : undefined;
}
function normalizeServiceConnectionMetadata(value) {
  const record = recordFromUnknown(value);
  if (!record)
    return;
  const entries = Object.entries(record).filter(([key]) => key.trim().length > 0).slice(0, SERVICE_CONNECTION_EVIDENCE_SOURCE_CAPS.maxMetadataKeys);
  const base = entries.length > 0 ? Object.fromEntries(entries) : {};
  const identity = normalizeServiceConnectionIdentityMetadata(record["identity"] ?? record);
  const scope = normalizeServiceConnectionScopeMetadata(record["scope"]);
  const catalogRecord = recordFromUnknown(record["catalog"]);
  const resourceRecord = recordFromUnknown(record["resource"]);
  const corroborationRecord = recordFromUnknown(record["corroboration"]);
  const observationStatusRecord = recordFromUnknown(record["observationStatus"]);
  const sensitivityRecord = recordFromUnknown(record["sensitivity"]);
  const metadata = {
    ...base,
    identity,
    scope,
    catalog: catalogRecord ? {
      catalogProvider: normalizeOptionalString(catalogRecord["catalogProvider"]),
      componentRef: normalizeOptionalString(catalogRecord["componentRef"]),
      systemRef: normalizeOptionalString(catalogRecord["systemRef"]),
      ownerRef: normalizeOptionalString(catalogRecord["ownerRef"]),
      resourceRef: normalizeOptionalString(catalogRecord["resourceRef"]),
      catalogId: normalizeOptionalString(catalogRecord["catalogId"]),
      catalogSource: normalizeOptionalString(catalogRecord["catalogSource"]),
      owner: normalizeOptionalString(catalogRecord["owner"]),
      lifecycle: normalizeOptionalString(catalogRecord["lifecycle"]),
      tags: normalizeStringArray(catalogRecord["tags"])
    } : undefined,
    resource: resourceRecord ? {
      resourceKind: normalizeServiceConnectionSurfaceKind(resourceRecord["resourceKind"]) ?? undefined,
      provider: normalizeOptionalString(resourceRecord["provider"]),
      protocol: normalizeOptionalString(resourceRecord["protocol"]),
      protocols: normalizeStringArray(resourceRecord["protocols"]),
      operation: normalizeOptionalString(resourceRecord["operation"]),
      endpoint: normalizeOptionalString(resourceRecord["endpoint"]),
      database: normalizeOptionalString(resourceRecord["database"]),
      schema: normalizeOptionalString(resourceRecord["schema"]),
      table: normalizeOptionalString(resourceRecord["table"]),
      topic: normalizeOptionalString(resourceRecord["topic"]),
      bucket: normalizeOptionalString(resourceRecord["bucket"])
    } : undefined,
    corroboration: corroborationRecord ? {
      sourceCount: normalizeFiniteNumber(corroborationRecord["sourceCount"]),
      evidenceSourceKinds: Array.isArray(corroborationRecord["evidenceSourceKinds"]) ? corroborationRecord["evidenceSourceKinds"].map(normalizeServiceConnectionEvidenceSourceKind).filter((item) => Boolean(item)) : undefined,
      evidenceTiers: Array.isArray(corroborationRecord["evidenceTiers"]) ? corroborationRecord["evidenceTiers"].map(normalizeServiceConnectionEvidenceTier).filter((item) => Boolean(item)) : undefined,
      notes: normalizeStringArray(corroborationRecord["notes"])
    } : undefined,
    observationStatus: observationStatusRecord ? {
      status: normalizeObservationStatus(observationStatusRecord["status"]),
      observedAtMs: normalizeFiniteNumber(observationStatusRecord["observedAtMs"]),
      lastSeenAtMs: normalizeFiniteNumber(observationStatusRecord["lastSeenAtMs"]),
      changedAtMs: normalizeFiniteNumber(observationStatusRecord["changedAtMs"]),
      reason: normalizeOptionalString(observationStatusRecord["reason"])
    } : undefined,
    sensitivity: sensitivityRecord ? {
      level: normalizeSensitivityLevel(sensitivityRecord["level"]),
      reason: normalizeOptionalString(sensitivityRecord["reason"]),
      containsSecret: typeof sensitivityRecord["containsSecret"] === "boolean" ? sensitivityRecord["containsSecret"] : undefined,
      redactionHint: sensitivityRecord["redactionHint"] === "none" || sensitivityRecord["redactionHint"] === "partial" || sensitivityRecord["redactionHint"] === "full" ? sensitivityRecord["redactionHint"] : undefined
    } : undefined
  };
  return Object.values(metadata).some((item) => item !== undefined) ? metadata : undefined;
}
function normalizeMetadata(value) {
  return normalizeServiceConnectionMetadata(value);
}
function normalizeConfidence(value, fallback) {
  if (typeof value !== "number" || !Number.isFinite(value))
    return fallback;
  return Math.max(0, Math.min(1, Number(value.toFixed(3))));
}
function normalizeTokenValue(value) {
  return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
}
function surfaceAliasMatches(alias, haystack, tokens) {
  const normalizedAlias = normalizeTokenValue(alias);
  if (!normalizedAlias)
    return false;
  if (normalizedAlias.length <= 3)
    return tokens.has(normalizedAlias);
  return tokens.has(normalizedAlias) || haystack.includes(normalizedAlias.replace(/_/g, " "));
}
function endpointLabel(endpoint) {
  return endpoint.label ?? endpoint.resourceId ?? endpoint.serviceId ?? endpoint.id;
}
function endpointLogicalServiceId(endpoint) {
  return endpoint.metadata?.identity?.canonicalLogicalServiceId ?? endpoint.serviceId;
}
function connectionIdentityScope(connection) {
  return normalizeIdentityScope(connection.metadata?.scope?.identityScope ?? connection.source.metadata?.scope?.identityScope);
}
function deriveServiceConnectionScopeKey(input = {}) {
  const explicitScopeKey = normalizeOptionalString(input.scopeKey);
  if (explicitScopeKey)
    return normalizeIdentityPart(explicitScopeKey);
  const metadata = normalizeMetadata(input.metadata);
  const scope = input.scope ?? metadata?.scope;
  const parts = [
    normalizeOptionalString(input.projectId) ? `project:${normalizeIdentityPart(normalizeOptionalString(input.projectId))}` : undefined,
    normalizeOptionalString(input.repoId) ? `repo:${normalizeIdentityPart(normalizeOptionalString(input.repoId))}` : undefined,
    scope?.identityScope ? `identity:${scope.identityScope}` : undefined,
    scope?.deploymentEnvironment ? `env:${normalizeIdentityPart(scope.deploymentEnvironment)}` : undefined,
    scope?.region ? `region:${normalizeIdentityPart(scope.region)}` : undefined,
    scope?.cluster ? `cluster:${normalizeIdentityPart(scope.cluster)}` : undefined,
    scope?.account ? `account:${normalizeIdentityPart(scope.account)}` : undefined,
    scope?.tenant ? `tenant:${normalizeIdentityPart(scope.tenant)}` : undefined
  ].filter((part) => Boolean(part));
  return parts.length > 0 ? parts.join("|") : `identity:${DEFAULT_SERVICE_CONNECTION_IDENTITY_SCOPE}`;
}
function deriveServiceConnectionStableKey(connection, options = {}) {
  const relationshipType = normalizeServiceConnectionRelationshipType(connection.relationshipType);
  if (!relationshipType)
    throw new Error("Invalid ServiceConnectionV1 relationshipType");
  const scopeKey = deriveServiceConnectionScopeKey({
    projectId: options.projectId ?? connection.projectId,
    repoId: options.repoId,
    scopeKey: options.scopeKey,
    metadata: connection.metadata
  });
  return [
    "service_connection:v1",
    scopeKey,
    normalizeEndpointIdentityPart(connection.source),
    relationshipType,
    normalizeEndpointIdentityPart(connection.target)
  ].join(":");
}
function connectionId(connection) {
  return connection.id ?? deriveServiceConnectionStableKey(connection);
}
function normalizeEndpointIdentityPart(endpoint) {
  return `${endpoint.kind}:${normalizeIdentityPart(endpoint.id)}`;
}
function normalizeIdentityPart(value) {
  return value.trim().toLowerCase().replace(/[^a-z0-9_@./-]+/g, "_").replace(/^_+|_+$/g, "") || "unknown";
}
function truncateSummary(value) {
  if (value.length <= SERVICE_CONNECTION_EVIDENCE_SOURCE_CAPS.maxSummaryLength)
    return value;
  return `${value.slice(0, SERVICE_CONNECTION_EVIDENCE_SOURCE_CAPS.maxSummaryLength - 1)}…`;
}
function normalizeServiceConnectionEndpointId(value) {
  if (typeof value !== "string")
    return null;
  const normalized = value.trim().toLowerCase().replace(/\s+/g, " ");
  return normalized.length > 0 ? normalized : null;
}
function deriveCanonicalLogicalServiceId(input) {
  const serviceName = normalizeServiceConnectionEndpointId(input.serviceName);
  if (!serviceName)
    return;
  const serviceNamespace = normalizeServiceConnectionEndpointId(input.serviceNamespace);
  return serviceNamespace ? `${serviceNamespace}/${serviceName}` : serviceName;
}
function deriveServiceConnectionEndpointId(input) {
  const fallbackId = normalizeServiceConnectionEndpointId(input.fallbackId) ?? undefined;
  const logicalServiceId = input.identity?.canonicalLogicalServiceId ?? deriveCanonicalLogicalServiceId({
    serviceName: input.identity?.serviceName,
    serviceNamespace: input.identity?.serviceNamespace
  });
  if (!logicalServiceId)
    return fallbackId;
  if (input.scope?.identityScope === "deployment_environment") {
    const deploymentEnvironment = normalizeServiceConnectionEndpointId(input.scope.deploymentEnvironment ?? input.identity?.deploymentEnvironment);
    return deploymentEnvironment ? `${logicalServiceId}@${deploymentEnvironment}` : logicalServiceId;
  }
  return logicalServiceId;
}
function serviceConnectionRelationshipSemantics(relationshipType) {
  return SERVICE_CONNECTION_RELATIONSHIP_SEMANTICS[relationshipType];
}
function normalizeServiceConnectionRelationshipType(value) {
  const sanitized = sanitizeConnectionRelationshipType(value);
  if (!sanitized || !SERVICE_CONNECTION_RELATIONSHIP_TYPE_SET.has(sanitized))
    return null;
  return sanitized;
}
function serviceConnectionRelationshipDirection(relationshipType) {
  return CONNECTION_RELATIONSHIP_TYPE_REGISTRY[relationshipType].direction;
}
function serviceConnectionRelationshipRiskLevel(relationshipType) {
  return CONNECTION_RELATIONSHIP_TYPE_REGISTRY[relationshipType].riskLevel;
}
function isServiceConnectionEndpointKind(value) {
  return typeof value === "string" && SERVICE_CONNECTION_ENDPOINT_KIND_SET.has(value);
}
function normalizeServiceConnectionEndpointKind(value) {
  return isServiceConnectionEndpointKind(value) ? value : null;
}
function normalizeServiceConnectionSurfaceKind(value) {
  if (typeof value !== "string")
    return null;
  const normalized = normalizeTokenValue(value);
  return SERVICE_CONNECTION_SURFACE_KIND_SET.has(normalized) ? normalized : null;
}
function inferServiceConnectionSurfaceKind(input) {
  const explicit = normalizeServiceConnectionSurfaceKind(input.kind);
  if (explicit)
    return explicit;
  const metadata = normalizeMetadata(input.metadata);
  const metadataKind = normalizeServiceConnectionSurfaceKind(metadata?.["surfaceKind"] ?? metadata?.["resourceKind"] ?? metadata?.resource?.resourceKind);
  if (metadataKind)
    return metadataKind;
  const rawHaystack = [input.label, input.id, input.uri, input.path].map((value) => typeof value === "string" ? value.toLowerCase() : "").join(" ");
  const tokens = new Set(rawHaystack.split(/[^a-z0-9]+/g).filter(Boolean));
  const haystack = rawHaystack.replace(/[^a-z0-9]+/g, " ");
  for (const kind of SERVICE_CONNECTION_SURFACE_KINDS) {
    if (kind === "unknown")
      continue;
    if (SERVICE_CONNECTION_SURFACE_KIND_ALIASES[kind].some((alias) => surfaceAliasMatches(alias, haystack, tokens)))
      return kind;
  }
  return "unknown";
}
function toServiceConnectionEndpoint(input) {
  const kind = normalizeServiceConnectionEndpointKind(input.kind);
  const inputMetadata = normalizeMetadata(input.metadata);
  const identity = normalizeServiceConnectionIdentityMetadata(input.identity ?? inputMetadata?.identity ?? input.metadata);
  const scope = normalizeServiceConnectionScopeMetadata(input.scope ?? inputMetadata?.scope);
  const id = deriveServiceConnectionEndpointId({ identity, scope, fallbackId: input.id });
  if (!kind || !id)
    return null;
  const metadata = normalizeMetadata({
    ...inputMetadata ?? {},
    identity: identity ?? inputMetadata?.identity,
    scope: scope ?? inputMetadata?.scope
  });
  const resourceKind = normalizeServiceConnectionSurfaceKind(input.resourceKind) ?? normalizeServiceConnectionSurfaceKind(metadata?.resource?.resourceKind) ?? inferServiceConnectionSurfaceKind({
    kind: input.resourceKind,
    label: input.label,
    id,
    uri: input.uri,
    path: input.path,
    metadata
  });
  return {
    schemaVersion: 1,
    kind,
    id,
    label: normalizeOptionalString(input.label),
    serviceId: normalizeServiceConnectionEndpointId(input.serviceId) ?? metadata?.identity?.canonicalLogicalServiceId,
    resourceId: normalizeServiceConnectionEndpointId(input.resourceId) ?? undefined,
    resourceKind,
    uri: normalizeOptionalString(input.uri),
    path: normalizeOptionalString(input.path),
    hash: normalizeOptionalString(input.hash),
    revision: normalizeOptionalString(input.revision),
    metadata
  };
}
function normalizeServiceConnectionEvidenceSourceKind(value) {
  if (typeof value !== "string")
    return null;
  const normalized = normalizeTokenValue(value);
  return SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND_SET.has(normalized) ? normalized : null;
}
function resolveServiceConnectionEvidenceSourceKind(value) {
  if (value === undefined || value === null || value === "")
    return DEFAULT_SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND;
  return normalizeServiceConnectionEvidenceSourceKind(value) ?? FALLBACK_SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND;
}
function normalizeServiceConnectionEvidenceTier(value) {
  if (typeof value !== "string")
    return null;
  const normalized = normalizeTokenValue(value);
  return SERVICE_CONNECTION_EVIDENCE_TIER_SET.has(normalized) ? normalized : null;
}
function serviceConnectionEvidenceSourceDefaults(kind) {
  return SERVICE_CONNECTION_EVIDENCE_SOURCE_DEFAULTS[resolveServiceConnectionEvidenceSourceKind(kind)];
}
function capServiceConnectionEvidenceConfidence(kind, confidence) {
  const defaults = serviceConnectionEvidenceSourceDefaults(kind);
  const normalized = normalizeConfidence(confidence, defaults.defaultConfidence);
  return defaults.confidenceCap === undefined ? normalized : Math.min(defaults.confidenceCap, normalized);
}
function normalizeServiceConnectionEvidenceSource(input) {
  const kind = resolveServiceConnectionEvidenceSourceKind(input.kind);
  const defaults = serviceConnectionEvidenceSourceDefaults(kind);
  const requestedTier = normalizeServiceConnectionEvidenceTier(input.evidenceTier);
  return {
    schemaVersion: 1,
    kind,
    id: normalizeOptionalString(input.id),
    label: normalizeOptionalString(input.label) ?? defaults.label,
    evidenceTier: requestedTier === defaults.evidenceTier ? requestedTier : defaults.evidenceTier,
    confidence: capServiceConnectionEvidenceConfidence(kind, input.confidence),
    uri: normalizeOptionalString(input.uri),
    path: normalizeOptionalString(input.path),
    hash: normalizeOptionalString(input.hash),
    revision: normalizeOptionalString(input.revision),
    metadata: normalizeMetadata(input.metadata)
  };
}
function defaultServiceConnectionEvidenceTier(evidenceSources) {
  return evidenceSources?.[0]?.evidenceTier ?? SERVICE_CONNECTION_EVIDENCE_SOURCE_DEFAULTS.code_static.evidenceTier;
}
function defaultServiceConnectionState(evidenceSources) {
  return evidenceSources?.[0] ? serviceConnectionEvidenceSourceDefaults(evidenceSources[0].kind).state : DEFAULT_SERVICE_CONNECTION_STATE;
}
function normalizeServiceConnectionV1(input, options = {}) {
  const relationshipType = normalizeServiceConnectionRelationshipType(input.relationshipType);
  if (!relationshipType)
    throw new Error("Invalid ServiceConnectionV1 relationshipType");
  if (input.direction !== undefined && input.direction !== "directed") {
    throw new Error("ServiceConnectionV1 only supports directed relationships");
  }
  const source = input.source ? toServiceConnectionEndpoint(input.source) : null;
  const target = input.target ? toServiceConnectionEndpoint(input.target) : null;
  if (!source || source.kind !== "service")
    throw new Error("ServiceConnectionV1 source must be a service endpoint");
  if (!target)
    throw new Error("ServiceConnectionV1 target must be a service or resource endpoint");
  const evidenceSources = Array.isArray(input.evidenceSources) ? input.evidenceSources.map((sourceInput) => normalizeServiceConnectionEvidenceSource(sourceInput)).slice(0, SERVICE_CONNECTION_EVIDENCE_SOURCE_CAPS.maxSourcesPerConnection) : undefined;
  const evidenceTier = normalizeServiceConnectionEvidenceTier(input.evidenceTier) ?? defaultServiceConnectionEvidenceTier(evidenceSources);
  const explicitState = normalizeConnectedWorkState(input.state);
  const lifecycleState = normalizeServiceConnectionLifecycleState(input.lifecycleState, serviceConnectionLifecycleStateFromConnectedWorkState(explicitState));
  const state = explicitState ?? connectedWorkStateForServiceConnectionLifecycleState(lifecycleState);
  const metadata = normalizeMetadata(input.metadata);
  const createdAtMs = normalizeFiniteNumber(input.createdAtMs) ?? options.generatedAtMs;
  const updatedAtMs = normalizeFiniteNumber(input.updatedAtMs) ?? options.generatedAtMs ?? createdAtMs;
  const normalizedWithoutId = {
    schemaVersion: 1,
    id: normalizeOptionalString(input.id),
    projectId: normalizeOptionalString(options.projectId) ?? normalizeOptionalString(input.projectId),
    relationshipType,
    direction: "directed",
    source,
    target,
    sourceSurfaceKind: normalizeServiceConnectionSurfaceKind(input.sourceSurfaceKind) ?? source.resourceKind,
    targetSurfaceKind: normalizeServiceConnectionSurfaceKind(input.targetSurfaceKind) ?? target.resourceKind,
    evidenceTier,
    state,
    lifecycleState,
    confidence: normalizeConfidence(input.confidence, evidenceSources?.[0]?.confidence ?? 0.5),
    evidenceSources,
    candidateKind: normalizeCandidateKind(input.candidateKind),
    directionHint: normalizeDirectionHint(input.directionHint),
    edgeLabel: normalizeOptionalString(input.edgeLabel),
    staticEvidenceTier: normalizeStaticEvidenceTier(input.staticEvidenceTier),
    missBuckets: normalizeStringArray(input.missBuckets),
    reportOnly: input.reportOnly === true ? true : undefined,
    advisoryOnly: input.advisoryOnly === true ? true : undefined,
    noAuthority: input.noAuthority === true ? true : undefined,
    summary: normalizeOptionalString(input.summary) ? truncateSummary(normalizeOptionalString(input.summary)) : undefined,
    createdAtMs,
    updatedAtMs,
    metadata
  };
  const id = normalizedWithoutId.id ?? deriveServiceConnectionStableKey(normalizedWithoutId, {
    projectId: normalizedWithoutId.projectId,
    repoId: options.repoId,
    scopeKey: options.scopeKey
  });
  return { ...normalizedWithoutId, id };
}
function summarizeServiceConnection(connection) {
  const sourceLabel = endpointLabel(connection.source);
  const targetLabel = endpointLabel(connection.target);
  const sourceSurfaceKind = connection.sourceSurfaceKind ?? connection.source.resourceKind ?? inferServiceConnectionSurfaceKind(connection.source);
  const targetSurfaceKind = connection.targetSurfaceKind ?? connection.target.resourceKind ?? inferServiceConnectionSurfaceKind(connection.target);
  const evidenceTier = connection.evidenceTier ?? defaultServiceConnectionEvidenceTier(connection.evidenceSources);
  const state = connection.state ?? defaultServiceConnectionState(connection.evidenceSources);
  const lifecycleState = connection.lifecycleState ?? serviceConnectionLifecycleStateFromConnectedWorkState(state);
  const semantics = serviceConnectionRelationshipSemantics(connection.relationshipType);
  const title = truncateSummary(connection.summary ?? `${sourceLabel} ${semantics.sourceDisplayLabel} ${targetLabel}`);
  return {
    schemaVersion: 1,
    id: connectionId(connection),
    title,
    subtitle: `${sourceSurfaceKind} → ${targetSurfaceKind}`,
    relationshipType: connection.relationshipType,
    direction: serviceConnectionRelationshipDirection(connection.relationshipType),
    riskLevel: serviceConnectionRelationshipRiskLevel(connection.relationshipType),
    sourceDisplayLabel: semantics.sourceDisplayLabel,
    inverseDisplayLabel: semantics.inverseDisplayLabel,
    sourceServiceMeaning: semantics.sourceServiceMeaning,
    sourceLogicalServiceId: endpointLogicalServiceId(connection.source),
    targetLogicalServiceId: endpointLogicalServiceId(connection.target),
    identityScope: connectionIdentityScope(connection),
    sourceLabel,
    targetLabel,
    sourceSurfaceKind,
    targetSurfaceKind,
    evidenceTier,
    state,
    lifecycleState,
    confidence: normalizeConfidence(connection.confidence, 0.5),
    evidenceSourceCount: connection.evidenceSources?.length ?? 0,
    updatedAtMs: connection.updatedAtMs
  };
}

// ../core/src/serviceConnectionEvidence/types.ts
var SERVICE_CONNECTION_EVIDENCE_BUNDLE_SCHEMA_VERSION = 1;
var SERVICE_CONNECTION_EVIDENCE_BUNDLE_KIND = "service_connection_evidence_bundle";
var SERVICE_CONNECTION_EVIDENCE_TOKEN_ESTIMATE_VERSION = "char-div-4-v1";

// ../core/src/serviceConnectionEvidence/builders.ts
var DEFAULT_GENERATED_AT = Date.parse("2026-05-18T00:00:00.000Z");
var DEFAULT_SOURCE = "explicit";
var PATH_ONLY_TOKEN_ESTIMATE = 24;
var PROOF_HINT_TOKEN_ESTIMATE = 18;
var FRESHNESS_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
var REQUIRED_PROOF_HINTS_BY_MISS_BUCKET = {
  candidate_without_runtime_owner: "Add runtime owner evidence: entrypoint, deployment, package, or process owner.",
  secret_without_consumer: "Link secret/config key to a source consumer.",
  datastore_without_tests: "Add targeted datastore test or migration proof.",
  route_without_handler: "Link route file to handler/controller symbol.",
  provider_client_without_secret: "Link provider client to config/env key evidence.",
  path_only_candidate_needs_review: "Add import, call, env, schema, test, or doc evidence before treating as dependency."
};
var REPORT_ONLY_GUARDRAILS = {
  reportOnly: true,
  advisoryOnly: true,
  noAuthority: true,
  noLive: true,
  noProductionWrites: true,
  noConvexWrites: true,
  noProviderCalls: true,
  noNetworkCalls: true,
  noFilesystemSourceScan: true,
  noHiddenExecution: true,
  noSecretsIncluded: true,
  redactedReferencesOnly: true,
  contextDoesNotMutateCanon: true,
  sourceContextGrantsNoAuthority: true,
  workingSetGrantsAuthority: false
};
var NO_LIVE = {
  pass: true,
  productionWrites: false,
  convexWrites: false,
  providers: false,
  network: false,
  memgraph: false,
  filesystemSourceScan: false,
  hiddenExecution: false
};
var SECRET_VALUE_PATTERN = /\b([A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|API_KEY|PRIVATE_KEY|ACCESS_KEY)[A-Z0-9_]*)\s*[:=]\s*([^\s,;]+)/gi;
var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/-]+=*/gi;
function buildServiceConnectionEvidenceBundleV1(args = {}) {
  const generatedAt = args.generatedAt ?? DEFAULT_GENERATED_AT;
  const source = args.source ?? DEFAULT_SOURCE;
  const warnings = [];
  const normalizedConnections = normalizeConnections(args, generatedAt, warnings);
  const staticEvidenceRefs = normalizeStaticEvidenceRefs(args.staticEvidenceRefs, warnings);
  const refs = normalizeEvidenceRefs(args, normalizedConnections, generatedAt, warnings, staticEvidenceRefs);
  const grouped = buildConnectionSummaries(args, normalizedConnections, refs);
  const requiredProofHints = uniqueStrings([
    ...grouped.flatMap((summary) => summary.requiredProofHints),
    ...(args.missBuckets ?? []).map((bucket) => REQUIRED_PROOF_HINTS_BY_MISS_BUCKET[bucket]).filter((hint) => Boolean(hint))
  ]).sort();
  const tokenSummary = buildTokenSummary(grouped, refs, requiredProofHints);
  if (typeof args.tokenBudget === "number" && tokenSummary.total > args.tokenBudget) {
    warnings.push("service_connection_evidence:token_budget_exceeded");
  }
  return {
    schemaVersion: SERVICE_CONNECTION_EVIDENCE_BUNDLE_SCHEMA_VERSION,
    kind: SERVICE_CONNECTION_EVIDENCE_BUNDLE_KIND,
    bundleId: args.bundleId ?? defaultBundleId(args, grouped, refs),
    generatedAt,
    source,
    connectionSummaries: grouped,
    evidenceRefs: refs,
    requiredProofHints,
    tokenSummary,
    statusSummary: buildStatusSummary(grouped, refs),
    redactionSummary: buildRedactionSummary(refs),
    warnings: uniqueStrings(warnings).sort(),
    staticEvidenceRefs,
    missBuckets: uniqueStrings(args.missBuckets ?? []).sort(),
    candidateKindCounts: args.candidateKindCounts,
    evidenceTierCounts: args.evidenceTierCounts,
    guardrails: REPORT_ONLY_GUARDRAILS,
    noLive: NO_LIVE,
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true
  };
}
function normalizeConnections(args, generatedAt, warnings) {
  const output = [];
  for (const input of args.serviceConnections ?? []) {
    try {
      const connection = isNormalizedServiceConnection(input) ? normalizeServiceConnectionV1(input, { generatedAtMs: generatedAt }) : normalizeServiceConnectionV1(input, { generatedAtMs: generatedAt });
      output.push({ connection, summary: summarizeServiceConnection(connection) });
    } catch (error) {
      warnings.push(`service_connection_evidence:invalid_connection:${error instanceof Error ? error.message : "unknown"}`);
    }
  }
  return output.sort((a, b) => a.summary.id.localeCompare(b.summary.id));
}
function normalizeEvidenceRefs(args, normalizedConnections, generatedAt, warnings, staticEvidenceRefs) {
  const inputs = [];
  inputs.push(...args.serviceConnectionRefs ?? []);
  inputs.push(...(args.serviceConnectionIds ?? []).map((serviceConnectionId) => ({ serviceConnectionId })));
  inputs.push(...(args.evidencePaths ?? []).map((evidencePath) => ({
    evidencePath,
    evidenceLabel: args.evidenceLabels?.[evidencePath]
  })));
  for (const item of normalizedConnections) {
    inputs.push(...connectionEvidenceInputs(item.connection, item.summary, generatedAt));
  }
  inputs.push(...staticEvidenceRefs.map(staticEvidenceInput));
  const deduped = new Map;
  for (const input of inputs) {
    const normalized = normalizeEvidenceRefInput({ input, defaultLifecycleState: args.defaultLifecycleState, defaultRelationshipType: args.defaultRelationshipType });
    if (!normalized) {
      warnings.push("service_connection_evidence:empty_ref_skipped");
      continue;
    }
    const existing = deduped.get(normalized.evidenceId);
    if (!existing || normalized.tokenEstimate > existing.tokenEstimate) {
      deduped.set(normalized.evidenceId, normalized);
    }
  }
  return Array.from(deduped.values()).sort(compareEvidenceRefs);
}
function normalizeStaticEvidenceRefs(refs, warnings) {
  if (!Array.isArray(refs))
    return [];
  const deduped = new Map;
  for (const ref of refs) {
    const kind = cleanString(ref.kind);
    const detail = cleanString(ref.detail);
    if (!kind || !detail) {
      warnings.push("service_connection_evidence:empty_static_ref_skipped");
      continue;
    }
    const containsSecret = kind === "env" || ref.redacted === true;
    const valueLabel = ref.valueLabel ? redactText(ref.valueLabel, containsSecret).text : undefined;
    const normalized = {
      serviceConnectionId: cleanString(ref.serviceConnectionId),
      candidateId: cleanString(ref.candidateId),
      kind: ref.kind,
      path: cleanString(ref.path),
      symbol: cleanString(ref.symbol),
      stableKey: cleanString(ref.stableKey),
      valueLabel,
      detail: redactText(detail, containsSecret).text,
      confidenceDelta: typeof ref.confidenceDelta === "number" && Number.isFinite(ref.confidenceDelta) ? Math.max(0, Math.min(1, ref.confidenceDelta)) : undefined,
      redacted: containsSecret ? true : undefined
    };
    const key = [
      normalized.kind,
      normalized.path ?? "",
      normalized.symbol ?? "",
      normalized.stableKey ?? "",
      normalized.valueLabel ?? ""
    ].join("|");
    deduped.set(key, normalized);
  }
  return Array.from(deduped.values()).sort((a, b) => {
    const left = [a.kind, a.path ?? "", a.symbol ?? "", a.stableKey ?? "", a.valueLabel ?? ""].join("|");
    const right = [b.kind, b.path ?? "", b.symbol ?? "", b.stableKey ?? "", b.valueLabel ?? ""].join("|");
    return left.localeCompare(right);
  });
}
function staticEvidenceInput(ref) {
  const serviceConnectionId = ref.serviceConnectionId ?? ref.candidateId ?? "service:static_candidate";
  return {
    serviceConnectionId,
    evidenceRef: ref.stableKey ?? ref.path ?? `${ref.kind}:${ref.detail}`,
    evidencePath: ref.path,
    evidenceLabel: ref.valueLabel ?? ref.detail,
    status: ref.kind === "miss_bucket" ? "missing_evidence" : "needs_review",
    freshness: "unknown",
    tokenEstimate: estimateTextTokens([ref.kind, ref.path, ref.symbol, ref.valueLabel, ref.detail].filter(Boolean).join(" ")),
    containsSecret: ref.redacted === true || ref.kind === "env"
  };
}
function connectionEvidenceInputs(connection, summary, generatedAt) {
  const sources = connection.evidenceSources && connection.evidenceSources.length > 0 ? connection.evidenceSources : [undefined];
  return sources.map((source, index) => ({
    serviceConnectionId: summary.id,
    serviceConnectionRef: connection.id,
    evidenceRef: evidenceRefFromSource(source, summary.id, index),
    evidencePath: source?.path ?? source?.uri,
    evidenceLabel: source?.label ?? summary.title,
    lifecycleState: summary.lifecycleState,
    relationshipType: summary.relationshipType,
    status: observationStatusFromSource(source),
    freshness: freshnessForConnection(connection, generatedAt),
    tokenEstimate: estimateTextTokens([summary.title, source?.path, source?.uri, source?.label].filter(Boolean).join(" ")),
    containsSecret: source?.metadata?.sensitivity?.containsSecret === true
  }));
}
function normalizeEvidenceRefInput(args) {
  const rawServiceConnectionId = cleanString(args.input.serviceConnectionId) ?? cleanString(args.input.serviceConnectionRef) ?? "service:unknown";
  const serviceIdRedaction = redactText(rawServiceConnectionId, args.input.containsSecret === true);
  const rawRef = cleanString(args.input.evidenceRef) ?? cleanString(args.input.evidencePath) ?? cleanString(args.input.serviceConnectionRef) ?? rawServiceConnectionId;
  const refRedaction = redactText(rawRef, args.input.containsSecret === true);
  const rawPath = cleanString(args.input.evidencePath);
  const pathRedaction = rawPath ? redactText(rawPath, args.input.containsSecret === true) : undefined;
  const rawLabel = cleanString(args.input.evidenceLabel) ?? cleanString(args.input.label) ?? cleanString(args.input.evidencePath) ?? rawServiceConnectionId;
  const labelRedaction = redactText(rawLabel, args.input.containsSecret === true);
  const evidenceRef = refRedaction.text;
  if (!evidenceRef)
    return null;
  const lifecycleState = args.input.lifecycleState ? normalizeServiceConnectionLifecycleState(args.input.lifecycleState, args.defaultLifecycleState) : args.defaultLifecycleState;
  const status = normalizeStatus(args.input.status, lifecycleState);
  const freshness = args.input.freshness ?? freshnessFromStatus(status);
  const redaction = mergeRedactions([serviceIdRedaction, refRedaction, labelRedaction, pathRedaction].filter((item) => Boolean(item)));
  const serviceConnectionId = serviceIdRedaction.text || "service:redacted";
  const stableKey = [serviceConnectionId, evidenceRef, lifecycleState ?? "", args.input.relationshipType ?? args.defaultRelationshipType ?? ""].join("|");
  const tokenEstimate = positiveInteger(args.input.tokenEstimate) ?? Math.max(PATH_ONLY_TOKEN_ESTIMATE, estimateTextTokens([serviceConnectionId, evidenceRef, pathRedaction?.text, labelRedaction.text].filter(Boolean).join(" ")));
  return {
    evidenceId: `service-evidence:${hashText(stableKey).slice(0, 16)}`,
    serviceConnectionId,
    serviceConnectionRef: cleanString(args.input.serviceConnectionRef),
    evidenceRef,
    evidencePath: pathRedaction?.text,
    evidenceLabel: labelRedaction.text || "Service connection evidence",
    relationshipType: args.input.relationshipType ?? args.defaultRelationshipType,
    lifecycleState,
    status,
    freshness,
    tokenEstimate,
    requiredProofHints: uniqueStrings(args.input.requiredProofHints ?? []).sort(),
    redaction,
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true
  };
}
function buildConnectionSummaries(args, normalizedConnections, refs) {
  const summaryById = new Map(normalizedConnections.map((item) => [item.summary.id, item.summary]));
  const connectionIds = uniqueStrings([
    ...refs.map((ref) => ref.serviceConnectionId),
    ...args.serviceConnectionIds ?? [],
    ...normalizedConnections.map((item) => item.summary.id)
  ]).sort();
  return connectionIds.map((serviceConnectionId) => {
    const matchingRefs = refs.filter((ref) => ref.serviceConnectionId === serviceConnectionId);
    const compactSummary = summaryById.get(serviceConnectionId);
    const statuses = matchingRefs.map((ref) => ref.status);
    const freshnessValues = matchingRefs.map((ref) => ref.freshness);
    const lifecycleState = compactSummary?.lifecycleState ?? firstDefined(matchingRefs.map((ref) => ref.lifecycleState));
    const status = statusForRefs(statuses, lifecycleState);
    const freshness = freshnessForRefs(freshnessValues, status);
    const requiredProofHints = uniqueStrings([
      ...matchingRefs.flatMap((ref) => ref.requiredProofHints),
      ...proofHintsFor({
        status,
        freshness,
        lifecycleState,
        relationshipType: compactSummary?.relationshipType ?? firstDefined(matchingRefs.map((ref) => ref.relationshipType)),
        evidenceRefCount: matchingRefs.length
      })
    ]).sort();
    const title = compactSummary?.title ?? serviceConnectionId;
    const label = compactSummary?.subtitle ? `${title} (${compactSummary.subtitle})` : title;
    const evidenceRefTokens = matchingRefs.reduce((total, ref) => total + ref.tokenEstimate, 0);
    const summaryTokenEstimate = estimateTextTokens([label, ...requiredProofHints].join(" "));
    return {
      serviceConnectionId,
      title,
      label,
      relationshipType: compactSummary?.relationshipType ?? firstDefined(matchingRefs.map((ref) => ref.relationshipType)),
      lifecycleState,
      status,
      freshness,
      evidenceRefs: uniqueStrings(matchingRefs.map((ref) => ref.evidenceRef)).sort(),
      evidencePaths: uniqueStrings(matchingRefs.map((ref) => ref.evidencePath).filter((path) => Boolean(path))).sort(),
      requiredProofHints,
      tokenEstimate: summaryTokenEstimate + evidenceRefTokens,
      compactSummary,
      redaction: mergeRedactions(matchingRefs.map((ref) => ref.redaction)),
      reportOnly: true,
      advisoryOnly: true,
      noAuthority: true
    };
  }).sort((a, b) => a.serviceConnectionId.localeCompare(b.serviceConnectionId));
}
function buildTokenSummary(summaries, refs, requiredProofHints) {
  const connectionSummaryTokens = summaries.reduce((total, summary) => total + estimateTextTokens([summary.title, summary.label].join(" ")), 0);
  const evidenceRefTokens = refs.reduce((total, ref) => total + ref.tokenEstimate, 0);
  const proofHintTokens = requiredProofHints.length * PROOF_HINT_TOKEN_ESTIMATE;
  return {
    estimateVersion: SERVICE_CONNECTION_EVIDENCE_TOKEN_ESTIMATE_VERSION,
    total: connectionSummaryTokens + evidenceRefTokens + proofHintTokens,
    connectionSummaryTokens,
    evidenceRefTokens,
    proofHintTokens,
    byConnection: summaries.map((summary) => ({
      serviceConnectionId: summary.serviceConnectionId,
      evidenceRefCount: summary.evidenceRefs.length,
      tokenEstimate: summary.tokenEstimate
    })),
    byEvidenceRef: refs.map((ref) => ({
      evidenceId: ref.evidenceId,
      serviceConnectionId: ref.serviceConnectionId,
      tokenEstimate: ref.tokenEstimate
    }))
  };
}
function buildStatusSummary(summaries, refs) {
  const statuses = summaries.map((summary) => summary.status);
  const freshness = summaries.reduce((counts, summary) => {
    counts[summary.freshness] += 1;
    return counts;
  }, { fresh: 0, stale: 0, unknown: 0 });
  return {
    totalConnections: summaries.length,
    totalEvidenceRefs: refs.length,
    presentCount: statuses.filter((status) => status === "present").length,
    missingEvidenceCount: statuses.filter((status) => status === "missing_evidence").length,
    needsReviewCount: statuses.filter((status) => status === "needs_review").length,
    staleCount: statuses.filter((status) => status === "stale").length,
    rejectedCount: statuses.filter((status) => status === "rejected").length,
    freshness
  };
}
function buildRedactionSummary(refs) {
  const redactedReferenceCount = refs.filter((ref) => ref.redaction.status === "redacted").length;
  const blockedSecretInputCount = refs.filter((ref) => ref.redaction.status === "secret_input_blocked").length;
  const cleanReferenceCount = refs.filter((ref) => ref.redaction.status === "clean").length;
  return {
    posture: "no_secret_values",
    noSecretValuesIncluded: true,
    redactedReferenceCount,
    blockedSecretInputCount,
    cleanReferenceCount,
    reasonCodes: uniqueStrings(refs.flatMap((ref) => ref.redaction.reasonCodes)).sort()
  };
}
function evidenceRefFromSource(source, serviceConnectionId, index) {
  return source?.id ?? source?.path ?? source?.uri ?? `${serviceConnectionId}:evidence:${index + 1}`;
}
function observationStatusFromSource(source) {
  return source?.metadata?.observationStatus?.status;
}
function freshnessForConnection(connection, generatedAt) {
  if (connection.lifecycleState === "stale")
    return "stale";
  if (!connection.updatedAtMs)
    return "unknown";
  const ageMs = Math.max(0, generatedAt - connection.updatedAtMs);
  return ageMs <= FRESHNESS_WINDOW_MS ? "fresh" : "unknown";
}
function normalizeStatus(status, lifecycleState) {
  if (status === "absent_in_latest_scan")
    return "stale";
  if (status === "changed")
    return "needs_review";
  if (status === "unknown")
    return lifecycleState === "verified" ? "present" : "needs_review";
  if (status === "present" || status === "missing_evidence" || status === "needs_review" || status === "stale" || status === "rejected")
    return status;
  if (lifecycleState === "rejected" || lifecycleState === "retracted")
    return "rejected";
  if (lifecycleState === "stale")
    return "stale";
  if (lifecycleState === "verified")
    return "present";
  return "needs_review";
}
function statusForRefs(statuses, lifecycleState) {
  if (statuses.length === 0)
    return "missing_evidence";
  if (statuses.includes("rejected"))
    return "rejected";
  if (statuses.includes("stale"))
    return "stale";
  if (statuses.includes("needs_review"))
    return lifecycleState === "verified" ? "present" : "needs_review";
  return "present";
}
function freshnessFromStatus(status) {
  if (status === "stale" || status === "rejected")
    return "stale";
  if (status === "present")
    return "fresh";
  return "unknown";
}
function freshnessForRefs(freshnessValues, status) {
  if (freshnessValues.length === 0)
    return freshnessFromStatus(status);
  if (freshnessValues.includes("stale"))
    return "stale";
  if (freshnessValues.every((freshness) => freshness === "fresh"))
    return "fresh";
  return "unknown";
}
function proofHintsFor(args) {
  const hints = ["Keep service connection evidence report-only until a governance path promotes it."];
  if (args.evidenceRefCount === 0 || args.status === "missing_evidence") {
    hints.push("Attach at least one explicit evidence ref or path before relying on this connection.");
  }
  if (!args.lifecycleState || args.lifecycleState === "hint" || args.lifecycleState === "candidate") {
    hints.push("Corroborate hint/candidate service connections with deterministic code, config, receipt, or explicit user-action evidence.");
  }
  if (args.freshness === "stale" || args.status === "stale") {
    hints.push("Refresh stale service connection evidence before using it for workflow decisions.");
  }
  if (args.relationshipType === "blocked_by") {
    hints.push("Capture the blocking condition and owner before planning dependent code-work.");
  }
  hints.push("Do not include raw credentials, tokens, passwords, or provider payloads in evidence labels or paths.");
  return uniqueStrings(hints).sort();
}
function redactText(value, blockSecretInput) {
  if (blockSecretInput) {
    return {
      text: `redacted:${hashText(value).slice(0, 12)}`,
      redaction: {
        status: "secret_input_blocked",
        containsSecret: false,
        noSecretValuesIncluded: true,
        redactionApplied: true,
        reasonCodes: ["redaction:explicit_secret_input_blocked"]
      }
    };
  }
  const redacted = value.replace(SECRET_VALUE_PATTERN, (_match, key) => `${key}=<redacted>`).replace(BEARER_PATTERN, "Bearer <redacted>");
  if (redacted !== value) {
    return {
      text: redacted,
      redaction: {
        status: "redacted",
        containsSecret: false,
        noSecretValuesIncluded: true,
        redactionApplied: true,
        reasonCodes: ["redaction:secret_value_pattern"]
      }
    };
  }
  return { text: value, redaction: cleanRedaction() };
}
function mergeRedactions(items) {
  const redactions = items.map((item) => ("redaction" in item) ? item.redaction : item);
  if (redactions.some((redaction) => redaction.status === "secret_input_blocked")) {
    return {
      status: "secret_input_blocked",
      containsSecret: false,
      noSecretValuesIncluded: true,
      redactionApplied: true,
      reasonCodes: uniqueStrings(redactions.flatMap((redaction) => redaction.reasonCodes)).sort()
    };
  }
  if (redactions.some((redaction) => redaction.status === "redacted")) {
    return {
      status: "redacted",
      containsSecret: false,
      noSecretValuesIncluded: true,
      redactionApplied: true,
      reasonCodes: uniqueStrings(redactions.flatMap((redaction) => redaction.reasonCodes)).sort()
    };
  }
  return cleanRedaction();
}
function cleanRedaction() {
  return {
    status: "clean",
    containsSecret: false,
    noSecretValuesIncluded: true,
    redactionApplied: false,
    reasonCodes: ["redaction:no_secret_values_detected"]
  };
}
function defaultBundleId(args, summaries, refs) {
  const seed = [args.source ?? DEFAULT_SOURCE, ...summaries.map((summary) => summary.serviceConnectionId), ...refs.map((ref) => ref.evidenceId)].join("|");
  return `service-connection-evidence:${hashText(seed || "empty").slice(0, 16)}`;
}
function isNormalizedServiceConnection(input) {
  return input.schemaVersion === 1;
}
function compareEvidenceRefs(a, b) {
  return a.serviceConnectionId.localeCompare(b.serviceConnectionId) || a.evidenceRef.localeCompare(b.evidenceRef) || a.evidenceId.localeCompare(b.evidenceId);
}
function cleanString(value) {
  if (typeof value !== "string")
    return;
  const text = value.trim();
  return text.length > 0 ? text : undefined;
}
function firstDefined(items) {
  return items.find((item) => item !== undefined);
}
function positiveInteger(value) {
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : undefined;
}
function estimateTextTokens(text) {
  return Math.max(1, Math.ceil(text.length / 4));
}
function uniqueStrings(values) {
  return Array.from(new Set(values.filter((value) => value.trim().length > 0)));
}
function hashText(value) {
  let hash = 2166136261;
  for (let index = 0;index < value.length; index += 1) {
    hash ^= value.charCodeAt(index);
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(16).padStart(8, "0");
}

// ../core/src/serviceIntelligence/builders.ts
var DEFAULT_GENERATED_AT2 = Date.parse("2026-05-18T00:00:00.000Z");
var DEFAULT_SOURCE2 = "explicit";
var DEFAULT_BACKEND_REFS = [
  "packages/core/src/contextLens/serviceConnections.ts",
  "packages/core/src/serviceConnectionEvidence/builders.ts",
  "packages/core/src/serviceIntelligence/builders.ts",
  "packages/mcp-server/src/codeContextTools.ts"
];
var DEFAULT_UI_REFS = [
  "apps/web/src/components/code-intelligence/ServiceImpactCard.tsx",
  "apps/web/src/components/code-workroom/ServiceIntelligencePanel.tsx",
  "apps/web/src/components/code-workroom/CodeWorkroomView.tsx"
];
var DEFAULT_TEST_REFS = ["convex-tests/codeLayer/serviceIntelligence.test.ts"];
var DEFAULT_DOC_REFS = ["docs/planning/MLP1.md", "docs/execution/CODE.md"];
function buildServiceIntelligenceReportV1(args = {}) {
  const generatedAt = args.generatedAt ?? DEFAULT_GENERATED_AT2;
  const source = args.source ?? DEFAULT_SOURCE2;
  const connections = normalizeServiceConnections(args, generatedAt);
  const evidenceBundle = args.evidenceBundle ?? buildServiceConnectionEvidenceBundleV1({
    ...args.evidence ?? {},
    generatedAt,
    source,
    serviceConnections: connections,
    missBuckets: uniqueStrings2([
      ...(args.evidence ?? {}).missBuckets ?? [],
      ...staticCandidateMissBuckets(args.staticCandidateGraph)
    ]),
    candidateKindCounts: staticCandidateKindCounts(args.staticCandidateGraph),
    evidenceTierCounts: staticEvidenceTierCounts(args.staticCandidateGraph)
  });
  const serviceMap = buildServiceMap(connections, evidenceBundle);
  const summary = buildSummary(serviceMap.nodes, serviceMap.edges, evidenceBundle);
  const status = summary.status;
  const nextImplementableSlice = buildNextSlice(args);
  const reportId = args.reportId ?? defaultReportId({
    source,
    goal: args.goal,
    connectionIds: serviceMap.edges.map((edge) => edge.id)
  });
  return {
    schemaVersion: SERVICE_INTELLIGENCE_REPORT_VERSION,
    reportKind: SERVICE_INTELLIGENCE_REPORT_KIND,
    reportId,
    generatedAt,
    source,
    goal: cleanString2(args.goal),
    status,
    summary,
    serviceMap,
    evidenceBundle,
    connectedSurfaceCoverage: args.connectedSurfaceCoverage ? connectedSurfaceSummary(args.connectedSurfaceCoverage) : undefined,
    absenceProof: buildAbsenceProof(evidenceBundle),
    productSummary: buildProductSummary({
      status,
      summary,
      nextImplementableSlice,
      uiRefs: args.uiRefs
    }),
    guardrails: serviceIntelligenceGuardrails(evidenceBundle.guardrails),
    noLive: serviceIntelligenceNoLive(evidenceBundle.noLive),
    reportOnly: true,
    advisoryOnly: true,
    noAuthority: true
  };
}
function normalizeServiceConnections(args, generatedAt) {
  const inputs = [
    ...args.serviceConnections ?? [],
    ...normalizeStaticCandidateGraph(args.staticCandidateGraph)
  ];
  return inputs.map((input) => {
    try {
      return normalizeServiceConnectionV1(input, { generatedAtMs: generatedAt });
    } catch {
      return null;
    }
  }).filter((connection) => connection !== null).sort((left, right) => summarizeServiceConnection(left).id.localeCompare(summarizeServiceConnection(right).id));
}
function normalizeStaticCandidateGraph(graph) {
  const edges = Array.isArray(graph?.edges) ? graph.edges : [];
  const nodeById = new Map((graph?.nodes ?? []).filter((node) => typeof node.nodeId === "string").map((node) => [node.nodeId, node]));
  return edges.filter((edge) => edge.sourceNodeId && edge.targetNodeId).map((edge) => {
    const sourceNode = nodeById.get(edge.sourceNodeId);
    const targetNode = nodeById.get(edge.targetNodeId);
    const relationshipType = relationshipTypeForDirection(edge.direction);
    const surfaceKind = surfaceKindForCandidate(edge.kind);
    return {
      id: edge.candidateId ?? edge.edgeId,
      relationshipType,
      direction: "directed",
      source: {
        kind: "service",
        id: edge.sourceNodeId,
        label: sourceNode?.label ?? edge.sourceNodeId,
        serviceId: edge.sourceNodeId
      },
      target: {
        kind: "resource",
        id: edge.targetNodeId,
        label: targetNode?.label ?? edge.targetNodeId,
        resourceId: edge.targetNodeId,
        resourceKind: surfaceKind
      },
      targetSurfaceKind: surfaceKind,
      lifecycleState: edge.evidenceTier === "path_only" ? "hint" : "candidate",
      state: edge.evidenceTier === "path_only" ? "usable_hint" : "review_candidate",
      confidence: edge.confidence,
      candidateKind: edge.kind,
      directionHint: edge.direction,
      edgeLabel: edge.edgeLabel,
      staticEvidenceTier: edge.evidenceTier,
      missBuckets: edge.missBuckets,
      reportOnly: true,
      advisoryOnly: true,
      noAuthority: true,
      evidenceSources: [{
        kind: "code_static",
        label: edge.edgeLabel ?? "Static service connection candidate",
        evidenceTier: "deterministic_code_edge",
        confidence: edge.confidence
      }],
      summary: edge.edgeLabel
    };
  });
}
function relationshipTypeForDirection(direction) {
  switch (direction) {
    case "publishes_queue":
      return "publishes_to";
    case "consumes_queue":
      return "subscribes_to";
    case "writes_datastore":
    case "writes_cache":
      return "writes_to";
    case "reads_datastore":
    case "reads_cache":
      return "reads_from";
    case "emits_telemetry":
      return "observes";
    case "reads_secret":
    case "outbound_provider":
    case "inbound_api":
    case "owns_runtime":
    case "proves_with_test":
    case "documents":
    default:
      return "blocked_by";
  }
}
function surfaceKindForCandidate(kind) {
  switch (kind) {
    case "http_api":
      return "api";
    case "database":
      return "datastore";
    case "object_store":
      return "object_store";
    case "queue_topic":
      return "queue";
    case "cache":
      return "cache";
    case "secret_config":
      return "secret";
    case "observability_sink":
      return "observability_sink";
    case "runtime_owner":
      return "runtime";
    case "auth_provider":
    case "provider_client":
      return "external_service";
    default:
      return "unknown";
  }
}
function staticCandidateMissBuckets(graph) {
  return uniqueStrings2([
    ...(graph?.edges ?? []).flatMap((edge) => edge.missBuckets ?? []),
    ...stringValues((graph?.missBuckets ?? []).map((bucket) => bucket.bucket))
  ]);
}
function staticCandidateKindCounts(graph) {
  const counts = countStrings(stringValues((graph?.edges ?? []).map((edge) => edge.kind)));
  return Object.keys(counts).length > 0 ? counts : undefined;
}
function staticEvidenceTierCounts(graph) {
  const counts = countStrings(stringValues((graph?.edges ?? []).map((edge) => edge.evidenceTier)));
  return Object.keys(counts).length > 0 ? counts : undefined;
}
function buildServiceMap(connections, evidenceBundle) {
  const nodeMap = new Map;
  const evidenceByConnectionId = new Map(evidenceBundle.connectionSummaries.map((summary) => [summary.serviceConnectionId, summary]));
  const edges = connections.map((connection) => {
    const summary = summarizeServiceConnection(connection);
    upsertNode(nodeMap, connection.source, summary.id);
    upsertNode(nodeMap, connection.target, summary.id);
    const evidenceSummary = evidenceByConnectionId.get(summary.id);
    return {
      id: summary.id,
      sourceNodeId: nodeId(connection.source),
      targetNodeId: nodeId(connection.target),
      title: summary.title,
      relationshipType: summary.relationshipType,
      lifecycleState: summary.lifecycleState,
      status: evidenceSummary?.status ?? statusForLifecycle(summary.lifecycleState),
      confidence: summary.confidence,
      evidenceRefCount: evidenceSummary?.evidenceRefs.length ?? 0,
      evidencePaths: evidenceSummary?.evidencePaths ?? [],
      summary,
      candidateKind: connection.candidateKind,
      directionHint: connection.directionHint,
      edgeLabel: connection.edgeLabel,
      evidenceTier: connection.staticEvidenceTier,
      missBuckets: connection.missBuckets,
      advisoryOnly: connection.advisoryOnly,
      noAuthority: connection.noAuthority
    };
  });
  return {
    schemaVersion: 1,
    nodes: Array.from(nodeMap.values()).sort((left, right) => left.id.localeCompare(right.id)),
    edges
  };
}
function upsertNode(nodeMap, endpoint, serviceConnectionId) {
  const id = nodeId(endpoint);
  const existing = nodeMap.get(id);
  if (existing) {
    existing.serviceConnectionIds = uniqueStrings2([...existing.serviceConnectionIds, serviceConnectionId]).sort();
    return;
  }
  nodeMap.set(id, {
    id,
    endpointKind: endpoint.kind,
    label: endpoint.label ?? endpoint.resourceId ?? endpoint.serviceId ?? endpoint.id,
    surfaceKind: endpoint.resourceKind ?? "unknown",
    logicalServiceId: endpoint.metadata?.identity?.canonicalLogicalServiceId ?? endpoint.serviceId,
    serviceConnectionIds: [serviceConnectionId]
  });
}
function buildSummary(nodes, edges, evidenceBundle) {
  const lifecycleStates = edges.map((edge) => edge.lifecycleState);
  const surfaceKinds = uniqueStrings2(nodes.map((node) => node.surfaceKind)).sort();
  const missingEvidenceCount = evidenceBundle.statusSummary.missingEvidenceCount;
  const needsReviewCount = evidenceBundle.statusSummary.needsReviewCount;
  const staleConnectionCount = evidenceBundle.statusSummary.staleCount + lifecycleStates.filter((state) => state === "stale").length;
  const status = serviceIntelligenceStatus({
    connectionCount: edges.length,
    missingEvidenceCount,
    needsReviewCount,
    staleConnectionCount
  });
  return {
    status,
    serviceCount: nodes.filter((node) => node.endpointKind === "service").length,
    resourceCount: nodes.filter((node) => node.endpointKind === "resource").length,
    connectionCount: edges.length,
    verifiedConnectionCount: lifecycleStates.filter((state) => state === "verified").length,
    candidateConnectionCount: lifecycleStates.filter((state) => state === "candidate" || state === "hint").length,
    staleConnectionCount,
    missingEvidenceCount,
    needsReviewCount,
    relationshipTypes: uniqueStrings2(edges.map((edge) => edge.relationshipType)).sort(),
    surfaceKinds,
    pathOnlyConnectionCount: edges.filter((edge) => edge.evidenceTier === "path_only").length,
    importBackedConnectionCount: edges.filter((edge) => edge.evidenceTier === "import_backed").length,
    callBackedConnectionCount: edges.filter((edge) => edge.evidenceTier === "call_backed").length,
    envBackedConnectionCount: edges.filter((edge) => edge.evidenceTier === "env_backed").length,
    schemaBackedConnectionCount: edges.filter((edge) => edge.evidenceTier === "schema_backed").length,
    testBackedConnectionCount: edges.filter((edge) => edge.evidenceTier === "test_backed").length,
    docBackedConnectionCount: edges.filter((edge) => edge.evidenceTier === "doc_backed").length,
    missBucketCounts: countStrings(edges.flatMap((edge) => edge.missBuckets ?? [])),
    candidateKindCounts: countStrings(stringValues(edges.map((edge) => edge.candidateKind))),
    directionCounts: countStrings(stringValues(edges.map((edge) => edge.directionHint)))
  };
}
function serviceIntelligenceStatus(args) {
  if (args.connectionCount === 0)
    return "empty";
  if (args.staleConnectionCount > 0)
    return "has_stale_edges";
  if (args.missingEvidenceCount > 0 || args.needsReviewCount > 0)
    return "needs_evidence";
  return "advisory_map";
}
function buildAbsenceProof(evidenceBundle) {
  const guardrailEvidence = [
    "guardrails.reportOnly=true",
    "guardrails.noAuthority=true",
    "guardrails.noProviderCalls=true",
    "guardrails.noNetworkCalls=true",
    "guardrails.noConvexWrites=true",
    "guardrails.contextDoesNotMutateCanon=true",
    `noLive.providers=${String(evidenceBundle.noLive.providers)}`,
    `noLive.network=${String(evidenceBundle.noLive.network)}`,
    `noLive.convexWrites=${String(evidenceBundle.noLive.convexWrites)}`,
    `noLive.filesystemSourceScan=${String(evidenceBundle.noLive.filesystemSourceScan)}`
  ];
  return [
    {
      claim: "This ServiceIntelligenceReportV1 did not ingest a live Runtime Surface Map.",
      status: "proven_for_report",
      scope: "this_report",
      evidence: guardrailEvidence,
      reasonCodes: ["absence:no_live_runtime_surface_ingest", "guardrail:no_provider_network_or_source_scan"]
    },
    {
      claim: "This report did not persist service connections, promote relationship memory, or mutate canon.",
      status: "proven_for_report",
      scope: "this_report",
      evidence: [
        "guardrails.noConvexWrites=true",
        "guardrails.contextDoesNotMutateCanon=true",
        "guardrails.workingSetGrantsAuthority=false",
        "noLive.graphWrites=false",
        "noLive.memoryPromotion=false"
      ],
      reasonCodes: ["absence:no_canon_mutation", "absence:no_memory_promotion"]
    },
    {
      claim: "Repo-wide service topology completeness is not claimed by this report.",
      status: "not_claimed",
      scope: "repo_wide",
      evidence: ["Report scope is limited to explicitly supplied ServiceConnectionV1/evidence inputs."],
      reasonCodes: ["absence:repo_wide_completeness_not_claimed"]
    }
  ];
}
function buildProductSummary(args) {
  const { summary } = args;
  return {
    backendStatus: summary.connectionCount === 0 ? "Backend status: ServiceConnectionV1/report contracts are available, but no service connections were supplied to this report." : `Backend status: ${summary.connectionCount} ServiceConnectionV1 edge(s) mapped across ${summary.serviceCount} service node(s) and ${summary.resourceCount} resource node(s).`,
    frontendStatus: args.uiRefs && args.uiRefs.length > 0 ? `Frontend status: UI refs supplied for read-only rendering (${args.uiRefs.join(", ")}).` : "Frontend status: the report is UI-ready, but no consuming UI ref was supplied by the caller.",
    absenceStatus: "Absence proof is scoped to this report: no live runtime-map ingest, provider call, network call, graph write, memory promotion, or canon mutation occurred.",
    guardrailStatus: "Report-only, advisory-only, no-authority. Service evidence can explain context but cannot execute, promote, write, or call providers.",
    actionabilityStatus: `${args.nextImplementableSlice.files.length} implementable file path(s) supplied for the next product slice.`,
    nextImplementableSlice: args.nextImplementableSlice
  };
}
function buildNextSlice(args) {
  const backendFiles = uniqueStrings2([...args.backendRefs ?? [], ...DEFAULT_BACKEND_REFS]);
  const uiFiles = uniqueStrings2([...args.uiRefs ?? [], ...DEFAULT_UI_REFS]);
  const testFiles = uniqueStrings2([...args.testRefs ?? [], ...DEFAULT_TEST_REFS]);
  const docsFiles = uniqueStrings2([...args.docsRefs ?? [], ...DEFAULT_DOC_REFS]);
  return {
    title: "Service Intelligence V1 read-only report slice",
    summary: "Wire ServiceConnectionV1 evidence into a first-class report, MCP payload, and read-only UI panel before any live runtime-map or connector-write work.",
    files: uniqueStrings2([...backendFiles, ...uiFiles, ...testFiles, ...docsFiles]),
    backendFiles,
    uiFiles,
    testFiles,
    docsFiles,
    steps: [
      "Build or pass ServiceConnectionV1 inputs with explicit evidence refs.",
      "Generate ServiceIntelligenceReportV1 and inspect its absenceProof before using it in agent context.",
      "Render the report as read-only service/resource topology and evidence status in Code Workroom.",
      "Add promotion or live-runtime-map work only as a later gated MLP2 slice."
    ],
    guardrails: [
      "Do not treat ServiceConnectionV1 as canon without Truth Gate or another explicit governance path.",
      "Do not add provider calls, network calls, source scans, connector writes, memory promotion, or graph writes to this report builder.",
      "Do not expose merge/comment/approval/write controls from the UI panel."
    ]
  };
}
function serviceIntelligenceGuardrails(guardrails) {
  return {
    ...guardrails,
    noGraphWrites: true,
    noMemoryPromotion: true,
    noConnectorWrites: true
  };
}
function serviceIntelligenceNoLive(noLive) {
  return {
    ...noLive,
    graphWrites: false,
    memoryPromotion: false,
    connectorWrites: false
  };
}
function connectedSurfaceSummary(report) {
  return {
    reportKind: report.reportKind,
    version: report.version,
    readiness: report.readiness,
    policy: report.policy,
    metrics: report.metrics,
    noLiveInvariants: report.noLiveInvariants,
    productSurfaces: report.productSurfaces
  };
}
function statusForLifecycle(lifecycleState) {
  if (lifecycleState === "verified")
    return "present";
  if (lifecycleState === "stale")
    return "stale";
  if (lifecycleState === "rejected" || lifecycleState === "retracted")
    return "rejected";
  return "needs_review";
}
function nodeId(endpoint) {
  return `${endpoint.kind}:${endpoint.id}`;
}
function defaultReportId(args) {
  const seed = [args.source, args.goal ?? "", ...args.connectionIds].join("|");
  return `service-intelligence:${hashText2(seed || "empty").slice(0, 16)}`;
}
function cleanString2(value) {
  if (typeof value !== "string")
    return;
  const text = value.trim();
  return text.length > 0 ? text : undefined;
}
function uniqueStrings2(values) {
  return Array.from(new Set(values.filter((value) => value.trim().length > 0)));
}
function stringValues(values) {
  return values.filter((value) => typeof value === "string" && value.trim().length > 0);
}
function countStrings(values) {
  return values.reduce((counts, value) => {
    counts[value] = (counts[value] ?? 0) + 1;
    return counts;
  }, {});
}
function hashText2(value) {
  let hash = 2166136261;
  for (let index = 0;index < value.length; index += 1) {
    hash ^= value.charCodeAt(index);
    hash = Math.imul(hash, 16777619);
  }
  return (hash >>> 0).toString(16).padStart(8, "0");
}
export {
  buildServiceIntelligenceReportV1,
  SERVICE_INTELLIGENCE_REPORT_VERSION,
  SERVICE_INTELLIGENCE_REPORT_KIND
};
