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
Node.js + Express
GenKit
Gemini
Google Pub/Sub
BigQuery
HubSpot
Slack
Every lead moves through this path before it ever reaches a CRM record — see §6 Request lifecycle.
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.
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.
High-level architecture
← Scroll horizontally to see the full diagram →
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
Core project components
| Layer | Component | Responsibility |
|---|---|---|
| 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. |
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, androuting_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
Request lifecycle
- Lead enters through a source such as Typeform, a form, or a webhook.
- n8n normalizes values, validates consent and schema, deduplicates, and enriches the record.
- The orchestrator signs the payload with HMAC-SHA256 and includes agent identity metadata.
- The worker authenticates the request, checks scopes, applies rate limits, and executes gateway policy validation.
- Model Armor scans the payload and output, redacting or rejecting PII and malicious content.
- GenKit calls Gemini using a restricted schema-backed prompt and returns a structured result.
- n8n branches based on
routing_tierand routes into CRM, Slack, nurture, or analytics processes.
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.
x-api-key mode in production, and forward audit logs to a SIEM or centralized logging system for operational review.
API and runtime endpoints
| Endpoint | Purpose | Access |
|---|---|---|
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 |
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
- 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
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"
}
}
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.