AGENT

Architecture & Tools Reference

B2B Lead Scoring Agent

n8n B2B lead orchestration + GenKit scoring worker + zero-trust governance stack for lead intake, scoring, routing, and auditability.

n8n n8n Node.js + Express GenKit GenKit Google Gemini Gemini Google Pub/Sub Google Pub/Sub BigQuery BigQuery HubSpot Slack
INTAKE VALIDATE SIGN AUTHENTICATE SCORE ROUTE

Every lead moves through this path before it ever reaches a CRM record — see §6 Request lifecycle.

Section 01

Overview

Business purpose

This project captures inbound B2B leads, normalizes and validates them, scores fit and urgency using GenAI, routes the lead to the appropriate action path, and records event-level activity for auditing and downstream processing.

Primary workflow

Lead sources feed into n8n. The orchestrator validates, enriches, and signs the payload before sending it to the GenKit scoring worker. The worker applies rate limiting, identity checks, route policy enforcement, and guardrails before calling Gemini and returning a scored result.

Key outcomes

  • Lead qualification and routing
  • Zero-trust request authentication
  • PII and prompt-injection safeguards
  • Registry-based agent governance
  • Audit-ready observability

Hosting model

The backend service is deployed to Google Cloud Run, providing a stateless container runtime for the GenKit worker with autoscaling, HTTPS ingress, and secure environment-based configuration. n8n orchestrations are connected to the Cloud Run endpoint through signed HTTP calls.

Section 02

Project documentation

Documentation map

This project is documented across a root README, architecture reference files, and service-level READMEs. Together they describe the business problem, technical design, deployment approach, workflow logic, security controls, and operational responsibilities.

  • Root README: repository overview, setup guidance, lead scoring examples, expected JSON contracts, and overall operating model.
  • docs/architecture.md: deeper architecture narrative, trust boundaries, sequence flow, and design rationale.
  • genkit-scoring-worker/README.md: API behavior, scoring workflow, route security, registry endpoints, and agent governance.
  • n8n-B2B-ochestration/README.md: orchestration workflow, webhook triggers, payload normalization, and downstream actions.
  • docs/architecture.html: single-page visual architecture and project summary for executive or onboarding review.

What the project documentation covers

  • Lead acquisition and intake sources, including web-native and automation-based flows.
  • Workflow logic for validation, enrichment, deduplication, scoring, and routing decisions.
  • Service contracts and API responsibilities between n8n and the GenKit worker.
  • Security posture, including identity verification, HMAC signing, model guardrails, and registry-based access control.
  • Operational and business integration points with HubSpot, Slack, BigQuery, and external enrichment vendors.

Documentation goals

  • Provide a unified mental model for engineering, operations, and stakeholders.
  • Explain the trust model from source intake to final routed action.
  • Document platform-specific responsibilities and how automation and GenAI are intentionally separated.
  • Support onboarding, deployment planning, security review, and future feature expansion.
The documentation is intentionally layered: the README is the operational entry point, the architecture markdown explains the technical shape, and the HTML page serves as a concise one-page visual reference for review and presentations.
Section 03

High-level architecture

LEAD SOURCES Typeform Web Forms Zapier Email Parsers n8n ORCHESTRATOR agent: n8n-orchestrator v1.0.0 Webhook / Trigger Normalize Lead Validate & Classify GDPR / consent checks Idempotency Enrichment Hunter / firmographic data Sign Request HMAC-SHA256 genkit-scoring-worker agent: lead-scoring-worker v1.1.0 SECURITY & GOVERNANCE 1. Rate Limiter 60/min global · 10/min model class · 429 + Retry-After 2. Agent Identity x-agent-id, x-agent-timestamp, x-agent-signature 3. Agent Gateway Default-deny routes, per-route scopes, model allowlist 4. Model Armor Prompt-injection blocks · PII redaction · tool-poisoning detection Agent Registry Published / approved / deprecated / revoked lifecycle Registry discovery and version tracking Gateway routes are protected by identity + scope Lead Scoring Agent GenKit + structured output schema using Gemini lead_score · justification · routing_tier Google Gemini gemini-3.5-flash model allowlist enforced DOWNSTREAM HubSpot CRM Slack Alerts BigQuery

← Scroll horizontally to see the full diagram →

rate limiting identity gateway + policy model armor registry model + scoring

For a complete visual representation of the overall system, its subsystems, and the security and governance controls applied to every agent-to-agent interaction, see the architecture.md file in the GitHub repository.

Request GitHub access: Gray@instantroam.com Evansansongg@gmail.com

Section 04

Core project components

LayerComponentResponsibility
Inbound orchestration n8n workflow Receives lead payloads from forms, Typeform, Zapier, or webhooks. Normalizes fields, validates consent, deduplicates, enriches, and signs calls before dispatch.
API service genkit-scoring-worker Runs an Express application with endpoints for health checks, lead scoring, registry queries, and policy introspection.
AI layer GenKit + Gemini Uses a model-backed structured generation to score the lead, justify the score, and assign a routing tier.
Security Rate limiter, identity middleware, gateway, model armor Enforces zero-trust access, scope checks, policy validation, and inline content filtering before the model ever sees the request.
Governance Agent registry Tracks approved agent identities, versioning, lifecycle state, and capability metadata.
Downstream actions CRM, Slack, BigQuery Routes scored leads to sales workflow automation, notifications, and business intelligence/audit storage.
Section 05

Project features

Lead intake & normalization

  • Unified lead contract for first name, company, industry, budget, message, and enrichment data
  • Consent validation and schema checks before scoring
  • Idempotency protection for duplicate submissions

AI scoring

  • Structured output schema with lead_score, justification, and routing_tier
  • Model allowlisting to restrict which providers and models are used
  • Business-oriented routing: High, Medium, Low

Security & guardrails

  • HMAC-based agent signature verification
  • Replay protection with timestamp windows
  • PII detection and redaction
  • Protection against prompt injection, tool poisoning, and malicious payloads

Governance & discovery

  • Registry state machine: published → approved → deprecated → revoked
  • Scoped authorization for reads, writes, route admin, and model invocation
  • Gateway policy enforcement for default-deny routing

Observability

  • Structured audit logs for policy decisions and model activity
  • Rate-limit headers and Retry-After handling
  • BigQuery integration for cold storage and operational analytics

Automation

  • CRM lead creation and task assignment
  • Slack hot-lead alerts
  • Queue-based nurture and follow-up branching
Section 06

Request lifecycle

  1. Lead enters through a source such as Typeform, a form, or a webhook.
  2. n8n normalizes values, validates consent and schema, deduplicates, and enriches the record.
  3. The orchestrator signs the payload with HMAC-SHA256 and includes agent identity metadata.
  4. The worker authenticates the request, checks scopes, applies rate limits, and executes gateway policy validation.
  5. Model Armor scans the payload and output, redacting or rejecting PII and malicious content.
  6. GenKit calls Gemini using a restricted schema-backed prompt and returns a structured result.
  7. n8n branches based on routing_tier and routes into CRM, Slack, nurture, or analytics processes.
Section 07

Security model

  • Agent Identity: every authenticated request is tied to a registered agent with least-privilege scopes and timestamp-based replay protection.
  • Agent Gateway: default-deny route table ensures requests only reach declared handlers; route access is gated by authorization and payload policy.
  • Model Armor: blocks prompt-injection and tool-poisoning attempts and redacts PII before and after model execution.
  • Rate limiting: sliding-window throttles cap abuse and noisy traffic while preserving service reliability.
  • Registry governance: only approved agents are accepted for invocation, and versioning/deprecation are part of the lifecycle.
Production guidance: keep secrets in platform secret storage, disable legacy x-api-key mode in production, and forward audit logs to a SIEM or centralized logging system for operational review.
Section 08

API and runtime endpoints

EndpointPurposeAccess
GET /health Health check for service readiness Public
GET /test Sample payload and response demonstration Public
POST /score Process a lead and return a scored output Authenticated agent, scored route
GET /registry/agents Discover approved or filtered agents registry:read
GET /registry/agents/:id Inspect a single agent and version history registry:read
POST /registry/agents Publish a new agent definition registry:write
POST /registry/agents/:id/versions Publish a new version registry:write
POST /registry/agents/:id/deprecate Deprecate or retire a current version registry:write
GET /gateway/routes Display active routing policy table gateway:admin
Section 09

Tools and technology stack

Backend runtime & API stack

  • Node.js 20+ as the primary server runtime
  • Express for the REST API layer and route handlers
  • JavaScript + TypeScript-friendly modular backend structure
  • dotenv for environment-based configuration and secrets
  • HTTP request handling for internal worker APIs and n8n integrations

AI / model stack

  • GenKit as the orchestration layer for model calls and structured generation
  • @genkit-ai/googleai integration for Google AI provider support
  • Google AI Studio + Gemini model family, including gemini-3.5-flash
  • Zod schemas to enforce the lead scoring response contract
  • Structured output generation for lead_score, justification, and routing_tier

Workflow orchestration

  • n8n for end-to-end workflow automation and trigger handling
  • Webhook-based intake from forms, parsing services, and external automation tools
  • HTTP Request nodes to call the backend scoring service
  • Node-based flow logic for normalization, validation, enrichment, and branching
  • CRM, Slack, and analytics actions triggered by scored routing decisions

Google Pub/Sub icon Google Pub/Sub

  • Google Pub/Sub for asynchronous lead and scoring event delivery
  • Decoupled messaging between n8n, scoring workers, and downstream systems
  • Topic and subscription patterns for durable, retryable processing

Security & governance tools

  • HMAC-SHA256 request signing for agent identity and replay protection
  • Scoped authorization and least-privilege agent permissions
  • Default-deny gateway policies and model allowlisting
  • Sliding-window rate limiting for global and model-specific traffic
  • Model Armor detection for prompt injection, tool poisoning, and PII redaction
  • Audit logging for allow/deny decisions and operational traceability

Registry & data layer

  • Custom agent registry JSON store for managed tool and model access
  • Lifecycle states for published, approved, deprecated, and revoked agents
  • BigQuery for audit/event storage and BI retention
  • Lead payload normalization and schema validation before scoring
  • Idempotency and deduplication controls to prevent duplicate processing

Third-party integrations

  • HubSpot CRM for lead creation, qualification, and sales routing
  • Slack notifications for urgent or high-value lead events
  • Hunter data enrichment for company and contact firmographic metadata
  • Google AI Studio for Gemini access and model execution
  • External form and automation sources connected through n8n and webhooks

Deployment & developer tooling

  • Google Cloud Run for the backend worker service hosting and HTTPS ingress
  • Dockerfile-based containerization for backend deployment
  • Environment secrets for API keys, model keys, and agent signing material
  • Git for source control and versioning
  • VS Code for development, documentation, and project maintenance
  • Documentation workflow spanning README, markdown architecture, and HTML overview pages

Core backend libraries used

  • express
  • genkit
  • @genkit-ai/googleai
  • zod
  • dotenv
  • node:crypto for HMAC-based signatures
  • Docker and Node.js process management for service deployment
Section 10

Data contract

The worker accepts a normalized lead payload and responds with a structured JSON object that downstream systems can route immediately.

Example request

{
  "first_name": "Jane",
  "last_name": "Roberts",
  "title_self": "VP Operations",
  "company": "Acme Corp",
  "industry_self": "SaaS",
  "consulting_type": "Process optimization",
  "budget": "$20k+",
  "message": "Scaling ops team",
  "enrichment": {
    "organization": "Acme Corp",
    "industry": "SaaS",
    "headcount": "320"
  }
}

Example response

{
  "output": {
    "lead_score": 88,
    "justification": "Strong fit based on role, company size, and budget signals.",
    "routing_tier": "High"
  }
}
Section 11

Recommended deployment posture

  • Runtime hosting: deploy the worker as a containerized service on Google Cloud Run with HTTPS ingress and autoscaling enabled.
  • Service exposure: keep the worker behind a stable hostname and expose only the required routes.
  • Secrets: use environment-managed secrets for AGENT_SECRET_N8N, AI keys, and registry secrets.
  • Access control: keep legacy authentication disabled in production and require signed agent identity headers.
  • State handling: persist the registry file or point it to a shared store when deploying multiple replicas.
  • Observability: ship audit logs to SIEM or centralized observability for investigation and compliance review.
↑ Top