24. AI Vendor Risk Assessor — Conceptual Revision Guide#
A concept-first revision guide for the AI Vendor Risk Assessor capstone (by Shivank Agrawal), which unifies three prior systems — Production RAG, Agentic RAG, and Deep Search — into one auditable compliance product. Given a request such as "Can our support team use this AI tool with customer data?", the system produces a review file checking every internal policy requirement against dated, sourced web evidence and drafting vendor follow-up questions for every gap. A human approves; the system never does. - Core mantra: "AI reads and finds facts; code judges; a human decides." - Scope & setup: Solo 2–3 weeks (team of 3–4: 4 weeks). Runs offline on day one with Python 3.10+, a free LLM key (Gemini or Groq) or local Ollama, and keyless web search (ddgs). - New capstone glue: A deterministic requirement matcher, a questionnaire drafter, a human approval gate, and a reviewer UI.
Big-Picture Architecture#
Revision Notes#
AI reads unstructured policy and vendor pages, deterministic Python rules compute auditable per-clause verdicts, and LangGraph pauses at a checkpointed human gate—enforcing 'AI finds facts; code judges; a human decides.'
Course Origin of Each Subsystem#
- Policy library — from Production RAG (clause-aware chunking, pre-ranking security filters, hybrid retrieval, reranking, grounded generation).
- Router & Graders — from Agentic RAG (typed intent routing, relevance/hallucination grading, bounded retry and abstention).
- Vendor research — from Deep Search (query planning, parallel budgeted workers, injection quarantine, identity gating, freshness/authority scoring, conflict-preserving merging).
- Matcher, Questionnaire & Human Gate — new in this capstone (deterministic compliance evaluation, gap-driven vendor questionnaires, checkpointed human sign-off).
The Problem & Domain Context (Nimbu Mart)#
Revision Notes#
Concept#
Security engineers spend 2–6 hours per vendor mostly finding, dating, and cross-checking facts across trust centres, privacy policies, and news. Because employees ask "can I use this AI tool?" several times a week, teams either wait weeks or bypass review altogether. The assessor automates the finding, dating, and rule-checking while leaving the final judgment to a named human.
Every vendor security review centers on six recurring questions:
- Does the vendor hold a current SOC 2 Type II or ISO/IEC 27001 certification?
- Where is customer/company data stored (data residency)?
- Does the vendor train models on our data?
- Who are their sub-processors (including third-party model providers)?
- Is there a history of security incidents and published post-mortems?
- Is a DPA (Data Processing Agreement) available?
Key Mental Models#
- Running example — Nimbu Mart: A fictional company whose Information Security team maintains 8 internal policy documents and evaluates tools across three data tiers (T1 public, T2 internal, T3 customer data).
- The three fictional test vendors (built-in adversarial testbed):
- LedgerLens AI (summarises support tickets): Solid SOC 2 Type II, but stores data in US/EU with India only "planned". Built-in traps: a stale 2024 page, a same-name UK accountancy firm, a forum rumour, a review site contradicting the trust centre, and a blog containing a prompt injection.
- QuillDesk (AI writing assistant): Claims "SOC 2 compliant" with no report, trains on content by default, US-only storage, a July 2026 incident with no post-mortem, and a directory page that is merely a syndicated copy of the vendor's own page.
- Parakeet Translate (Indian-language translation): The "good" vendor — ISO 27001 confirmed on the certifier's registry, India region, no training, DPA with DPDP addendum — yet approved only for internal data (T2), so customer-data (T3) use is CONDITIONAL pending Procurement.
- Anatomy of a gold-standard review (LedgerLens at T3 customer-data tier):
- SEC-4.2 (Independent security assurance) → PASS: SOC 2 Type II report dated 2026-01-20 (trust centre, 2026-09-01).
- DP-3.1 (Customer data stored in India) → FAIL: India is only planned; currently US and EU.
- AI-2.1 (No training on our data) → NEEDS REVIEW: No training on Business/Enterprise, but Free/Pro trains by default.
- AI-3.4 (Sub-processors disclosed) → NEEDS REVIEW: Third-party model provider present (Orbital Models, US).
- SEC-9.3 (Incident history) → NEEDS REVIEW: One major incident (2025-04) with published post-mortem across 2 independent sources.
- PROC-1.1 (On Approved Vendor List) → NEEDS REVIEW: Review already in progress; attach this assessment.
- Supporting sections: Dated facts with confidence and recorded conflicts; a security log ("1 page quarantined for prompt injection; 1 rejected as a different company; 1 rumour dropped"); six ready-to-send vendor questions; an approval block naming two required signers (Head of Information Security and DPO); and an outcome of BLOCKED (never "rejected", never "approved").
Trade-Offs & Pitfalls#
- Evidence-or-UNKNOWN invariant: Every requirement row must carry clause + verdict + reason + evidence (source URL and date). If evidence is missing, the verdict must be
UNKNOWN. - "Planned" is not "available": Treating planned India residency (
allow_planned: trueon DP-3.1) as a pass is a classic compliance failure — tested deliberately in M0. - Approved for T2 ≠ approved for T3: Even a vendor passing every technical check on documented evidence stays
CONDITIONALwhen its Approved Vendor List entry only covers a lower data tier.
System Architecture & Component Responsibilities#
Revision Notes#
Concept#
The system is structured as one graph with four routes (policy, vendor fact, assessment, and refuse). Policy questions stop after the graders, vendor-fact lookups stop after Deep Search, and full assessments traverse the entire pipeline through deterministic matching, questionnaire drafting, human gating, and output guardrails. The exact same node functions run either as plain Python or inside a LangGraph state machine (assessor/graph.py), where shared state flows cleanly across nodes.
A structured-output Router dispatches requests across four specialized execution paths while Answer Relevance and Hallucination Graders enforce bounded query-widening and abstention on internal policy answers.
Component Map (Starter Kit vs. Target State)#
- Stage contracts (
assessor/schemas.py): Complete in starter kit. Defines the 9 vendor fields, evidence levels, verdict enums, and report schema. - Policy library (
assessor/policy_rag.py): Starter: clause chunking +BM25+ ACL/version/trust filters + extractive answers. Upgrade: hybrid search (BM25+ dense vectors viaRRF) + cross-encoder reranker + grounded LLM generation. - Router (
assessor/router.py): Starter: rule-based regex mock. Upgrade: LLM router using structured output (LLM.structured()) across all 4 routes. - Graders (
assessor/graders.py): Starter: heuristic mocks. Upgrade: dedicated Answer Relevance Grader and Hallucination Grader with a bounded retry loop. - Vendor research (
assessor/vendor_research.py): Starter: full offline loop (identity gate, quarantine, scoring, merging) + sequential live baseline. Upgrade: planner/reviewer, parallel budgeted workers, memory, and live evaluation. - Requirement matcher (
assessor/matcher.py+data/requirements.yaml): Complete & unit-tested. Evaluates 11 requirements using 8 deterministic rule types. Extended only when new policy clauses are added. - Questionnaire & report (
assessor/questionnaire.py,report.py): Complete. MapsUNKNOWNand open items to template questions and rendersreport.md, JSON, andtrace.jsonl. - Guardrails (
assessor/guardrails.py): Starter: regex input redaction, intent check, output policy enforcement. Upgrade: small-model LLM injection classifier + red-team test suite. - Orchestrator (
assessor/graph.py): Starter: plain Python + LangGraph using the same nodes, CLI human gate. Upgrade: persistent checkpointer +interrupt()+ progress streaming. - API & UI (
app/api.py,app/ui.py): Starter: thin skeletons. Upgrade: Redis/RQ job queue, Postgres history, server-side auth/groups, streaming trace viewer, and reviewer sign-off UI. - Evaluation (
eval/run_eval.py,data/gold_set*.json): Starter: harness + fictional gold set complete; real-vendor set is a template. Upgrade: populated 10-vendor real gold set, LLM-as-judge faithfulness metric, and per-component ablations.
Key Terminology#
BM25: Classic lexical/keyword ranking algorithm.ACL(Access Control List): Security metadata defining which user groups may retrieve a document.- Extractive answer vs. Grounded generation: Extractive mode copies matching policy text verbatim (ideal as an offline fallback); grounded generation uses an LLM to synthesize an answer strictly from retrieved chunks with explicit clause citations.
Code Reference#
from __future__ import annotations
import time
from datetime import date
from typing import Any, Optional, TypedDict
from .config import SETTINGS
from .graders import grade_policy_answer
from .guardrails import check_intent, enforce_output_policy, redact_input
from .llm import LLM
from .matcher import Matcher
from .policy_rag import PolicyLibrary
from .questionnaire import as_email, build_questions
from .report import to_markdown
from .router import decide
from .schemas import Approval, AssessmentReport, AssessmentRequest
from .tracing import Budget, Tracer
from .vendor_research import VendorResearcher
# Governance matrix: higher data tiers require stricter human sign-off before approval.
# T1 (public) -> Team lead; T2 (internal) -> Head of InfoSec; T3 (customer PII) -> InfoSec + DPO.
APPROVERS = {"T1": ["Team lead"], "T2": ["Head of Information Security"], "T3": ["Head of Information Security", "DPO"]}
class State(TypedDict, total=False):
"""The shared workspace every node reads from and writes to (LangGraph merges updates per key)."""
# --- Request inputs & access control ---
question: str
user_groups: list[str] # RBAC groups enforced during policy RAG retrieval
tier: str # T1 | T2 | T3 data classification
users: int # seat count (triggers rules with min_users thresholds)
vendor: Optional[str]
domain: Optional[str]
requested_by: str
interactive: bool # True pauses for CLI human approval; False returns pending report
approver: Optional[str]
decision: Optional[str]
# --- Routing & guardrail outputs ---
route: Optional[str] # policy_qa | assessment | refuse
refusal: Optional[str]
policy_answer: Any
# --- Research, deterministic matching, and approval outputs ---
profile: Any
request: Any
results: Any
overall: Optional[str] # APPROVE | CONDITIONAL | BLOCK | NEEDS_MORE_INFO
overall_reason: Optional[str]
open_questions: list[dict]
approval: Any
report: Any
answer: Optional[str]
guardrail_notes: list[str]
started: float
def new_state(question: str, *, user_groups: list[str] | None = None, tier: str = "T3", users: int = 1,
vendor: str | None = None, domain: str | None = None, requested_by: str = "cli",
interactive: bool = False, approver: str | None = None, decision: str | None = None) -> dict:
# Default to least-privilege groups (["public", "employees"]) and strictest tier ("T3")
# so callers cannot accidentally bypass customer-data compliance rules.
return {"question": question, "user_groups": user_groups or ["public", "employees"], "tier": tier, "users": users,
"vendor": vendor, "domain": domain, "requested_by": requested_by, "interactive": interactive,
"approver": approver, "decision": decision,
"route": None, "refusal": None, "policy_answer": None, "profile": None, "results": None, "overall": None,
# -> initial: {'tier': 'T3', 'users': 40, 'vendor': 'AcmeAI', 'route': None, ...}
# after run_plain(): route='assessment', overall='BLOCK',
# overall_reason='1 blocker failed: DP-3.1 (Customer data stored in India)'
# ... (see full file: graph.py)
>>> from assessor.graph import Pipeline, new_state
>>> pipe = Pipeline()
>>> state = new_state(
... "Can we use AcmeAI for customer support tickets?",
... tier="T3", users=40, vendor="AcmeAI", domain="acmeai.example",
... )
>>> out = pipe.run_plain(state)
>>> (out["route"], out["overall"], out["overall_reason"])
('assessment', 'BLOCK', '1 blocker failed: DP-3.1 (Customer data stored in India)')
from __future__ import annotations
from datetime import date
from typing import Any, Literal, Optional
from pydantic import BaseModel, Field
# ---------------------------------------------------------------------------
# 1. Vendor facts — what the research layer tries to establish about a vendor.
# (Deep Search course Module 12 "Adapt it to your own domain": this is place 1 of 4.)
# ---------------------------------------------------------------------------
# Closed taxonomy of 9 compliance facts: every rule in data/requirements.yaml points
# to exactly one of these fields so research extraction and deterministic matching align 1:1.
VendorField = Literal[
"legal_entity", # identity anchor: which company are we actually looking at?
"security_certifications", # SOC 2 Type II / ISO 27001, with dates and evidence level
"data_regions", # where customer content is stored (available vs planned)
"subprocessors", # who else touches the data, incl. model providers
"trains_on_customer_data", # no | no_on_paid_plans | opt_out_available | yes
"data_retention", # default retention + deletion on request (days)
"sso_saml", # all_plans | paid_plans | enterprise_only | none
"security_incidents", # last 24 months, with post-mortem status
"dpa_available", # yes | on_request | no
]
VENDOR_FIELDS: tuple[str, ...] = VendorField.__args__ # type: ignore[attr-defined]
FIELD_DESCRIPTIONS: dict[str, str] = {
"legal_entity": "The legal entity, country and HQ city of the company that runs the product.",
"security_certifications": "Independent security attestations: SOC 2 (Type I/II) report dates, ISO 27001 certificate, issuer, validity.",
"data_regions": "Countries/regions where customer content is stored at rest; separate 'available now' from 'planned'.",
"subprocessors": "Third parties that process customer content for the vendor: name, purpose, category, country.",
"trains_on_customer_data": "Whether customer content is used to train or improve models, and on which plans.",
"data_retention": "Default retention after contract end and whether deletion on request is offered, in days.",
"sso_saml": "Whether SAML/OIDC single sign-on is offered and on which plan.",
"security_incidents": "Security incidents affecting customer data in the last 24 months and whether a post-mortem was published.",
"dpa_available": "Whether a Data Processing Agreement is published, available on request, or not offered.",
}
# Fields where a wrong answer is expensive: we demand documented evidence from a non-forum source.
HIGH_STAKES_FIELDS: frozenset[str] = frozenset({"security_certifications", "security_incidents", "trains_on_customer_data", "data_regions"})
# Fields whose value is a LIST that should be merged (union) across sources rather than "best source wins".
# Prevents a vendor's clean trust-center page from overwriting a real incident reported by news.
LIST_FIELDS: frozenset[str] = frozenset({"security_incidents"})
# Evidence strength is tracked separately from source type: even an official website can make
# an unverified marketing claim ("claimed") instead of linking a dated audit report ("documented").
EvidenceLevel = Literal[
"documented", # a report, certificate, registry entry, or the vendor's own policy/legal page
"claimed", # marketing text with no verifiable artefact ("we are SOC 2 compliant")
"third_party", # a named news outlet or review site reporting it
"rumour", # forum, social media, unnamed sources
]
SourceType = Literal[
"regulator", # certification body registry, government register
"official", # the vendor's own site: trust centre, legal, status page
"news", # named news outlet
"news_syndicated", # a copy of someone else's content (press release reprint, directory listing)
"review_site",
"forum",
# ... (see full file: schemas.py)
>>> from assessor.schemas import VENDOR_FIELDS, HIGH_STAKES_FIELDS, LIST_FIELDS
>>> len(VENDOR_FIELDS)
9
>>> sorted(HIGH_STAKES_FIELDS)
['data_regions', 'security_certifications', 'security_incidents', 'trains_on_customer_data']
>>> LIST_FIELDS
frozenset({'security_incidents'})
Build Progression: Milestones M0–M6#
Revision Notes#
Concept#
Development follows seven sequential milestones, each ending with a verifiable "Done when" gate. Every upgrade must preserve all earlier guarantees — existing tests stay green, guess_rate stays 0%, and safety stays 100%.
M0 — Run and Read the Starter Kit (½ day)#
- Goal: Understand the end-to-end behavior before modifying a single line.
- Core activities: Run the four demo questions, read each
report.md, and inspecttrace.jsonlbottom to top. Examinedata/vendor_web/corpus.jsonto spot the stale page, look-alike UK firm, rumour, syndicated copy, and prompt-injection blog, then verify how the trace handled each. Intentionally break DP-3.1 (allow_planned: true) to see LedgerLens flip to passing residency, then revert. - Done when: All 70 starter tests pass, offline evaluation hits 100% verdict accuracy, and you can explain concisely why QuillDesk is BLOCKED and Parakeet is only CONDITIONAL.
M1 — Production-Grade Policy Library (3–4 days)#
- Goal: Upgrade keyword-only extractive search into a full hybrid + rerank + grounded-generation RAG pipeline without weakening any security invariant.
- Key engineering decisions:
- Preserve clause IDs and metadata (
access,status,trust,version) on every chunk. - Apply all filters BEFORE ranking (
ACL, archived versions, untrusted sources, injection flags) so restricted or poisoned documents never enter candidate scoring. - Fuse
BM25and dense vectors withRRF, then apply a cross-encoder reranker. - Keep extractive mode as an offline fallback when no LLM is configured; refuse whenever the top rerank score falls below threshold or the hallucination grader flags an ungrounded answer.
- Fix the known baseline failure
pq-who-approves, where lexical search ranksSEC-7.1above the approval table inAI-5.1. - Extend the corpus with 3 new policy documents (such as an incident-response runbook and a
status: draft2027 policy) plus 3 new gold questions.
- Preserve clause IDs and metadata (
- Done when: All policy checks pass (including the previously failing baseline), ACL/archive/trust tests remain green, and asking for the Approved Vendor List returns the approval process, never the list.
M2 — Live Vendor Research on the Real Web (4–5 days)#
- Goal: Replace the sequential live baseline with a planned, parallel, budgeted Deep Search agent producing the exact same
VendorProfileschema on real-world vendors. - Key engineering decisions:
- Review and justify every parameter in
AUTHORITY(source-type trust weights),FIELD_AUTHORITY_OVERRIDES, andHALF_LIFE_DAYS(per-field freshness decay rates). - Replace static query lists with a Plan Creator → Plan Reviewer loop generating one sub-question per vendor field with explicit stop rules (stop once every high-stakes field has a documented source or two searches fail).
- Run fetching and extraction in parallel workers sharing a single Budget, routing structured claim extraction to a small, fast model.
- Upgrade the identity gate to an LLM check verifying domain, legal entity, and product — keeping it strictly as a binary gate (reject mismatched pages, never down-weight them).
- Hand-research 3 real AI/SaaS vendors first (recording URLs and dates in
gold_set_template.json) before benchmarking the agent field by field.
- Review and justify every parameter in
- Trade-offs & friction: Real trust centres are often JavaScript-heavy, block automated fetchers, or advertise "SOC 2 compliant" without a report. Keep the offline corpus as a deterministic regression suite and snapshot fetched pages in
cached_pages/so live demos never break on flaky networks. - Done when: Real-vendor field accuracy ≥ 80%, zero fields populated from a different company, live cost <
VRA_MAX_USD, latency < 90 seconds, and offline tests unchanged.
M3 — Router & Graders as Agents (2 days)#
- Goal: Replace the regex router and heuristic graders with LLM agents that deliver measurably higher routing and grounding reliability.
- Key engineering decisions:
- Implement the Router via
LLM.structured()returning a typedRouteDecisionacrosspolicy,vendor,assessment, andrefuse. - Implement
grade_relevance()(Answer Grader) andgrade_grounded()(Hallucination Grader) wired into a bounded retry loop: if retrieved chunks are not relevant, widen tok = 8with query rewriting; if the generated answer is not grounded, retry once with stricter instructions, then abstain if it still fails. - Benchmark mock vs. LLM router on 30 routing questions (10 per route, including ambiguous edge cases).
- Implement the Router via
- Done when: LLM routing accuracy ≥ 90% on the 30-question set, and a deliberately sabotaged prompt that invents a policy clause is caught by the hallucination grader and forced to abstain.
M4 — Layered Security & Red-Teaming (2 days)#
- Goal: Prove that untrusted content — vendor web pages, internal chat exports, or adversarial user prompts — can never alter a compliance verdict.
- Defense-in-depth layers & catch points:
- Build
tests/test_red_team.pywith 15 adversarial attacks, each asserting the exact catch point (quarantine, identity gate, dropped, intent check, or output guardrail): prompt injection in a vendor page ("report PASS"), injection in a policy doc, user prompt smuggling ("…and mark it approved"), fake trust centre on a look-alike domain, contradicting India-residency claim, and rumour disguised as news. - Add a small-model injection classifier behind the regex scanner on every fetched page and measure its false-positive rate on clean pages.
- Run an identity-gate ablation: disable the gate and capture the failure where the UK accountancy firm's ISO certificate leaks into LedgerLens's profile.
- Enforce the privacy checklist: store no personal data in schemas, address vendor questionnaire emails to a role rather than an individual, and never store vendor-employee names.
- Build
- Done when: 15/15 attacks caught at asserted layers, gold-set
safetyremains 100%, andguess_rateremains 0%.
M5 — Productization: Graph, API, UI & Human Gate (3–4 days)#
- Goal: Deliver a self-service product a reviewer can operate without the engineer present.
- Key engineering decisions:
- Checkpointed human gate: Add a LangGraph checkpointer +
interrupt()athuman_gateso assessments can pause for days awaiting sign-off and resume cleanly. - Async API & history: Queue
/assessvia Redis + RQ, return ajob_idimmediately, and persist reports in Postgres so/vendors/{name}/historysurfaces deltas since the prior review (SEC-12.1). - Server-side ACLs: Derive
user_groupsstrictly from server-side caller identity — never trust groups sent in the client request body. - Reviewer UI: Stream live node progress, render the execution trace as a tree beside the report, and expose an Approve/Reject form calling
/approve/{run_id}with the reviewer's name. ABLOCKEDreport must never display an Approve button. - Observability: Track per-stage latency and LLM cost per run, surfacing the last 20 runs with p50 (median) and p95 latency and cost.
- Checkpointed human gate: Add a LangGraph checkpointer +
- Done when: An unfamiliar teammate can run an assessment from the UI, inspect evidence and trace, send vendor questions, and record a decision that survives a server restart.
M6 — Evaluation, Ablations & Demo (2–3 days)#
- Goal: Prove every component earns its complexity with hard numbers and automated CI regression checks.
- Key activities:
- Expand the real-vendor gold set to 10 vendors × 8 fields (hand-verified with URLs and dates, mixing clean passes, clear fails, and ambiguous cases).
- Add an LLM-as-judge faithfulness metric verifying whether every verdict reason is faithful to its cited evidence — calibrated first on 20 hand-labelled reasons.
- Run one ablation per major component (no reranker, no identity gate, no freshness decay, no planner) to quantify each component's marginal lift.
- Wire strict evaluation (
--strict) and unit tests into CI (GitHub Actions) against the offline gold set. - Write an honest README covering architecture, metrics, known failure modes, and next steps, and rehearse the 12-minute demo.
- Done when: Scorecard covers accuracy, guess rate, safety, cost, and latency across both fictional and real sets; CI is green; demo runs both offline and live.
The Data Pack & Rules Engine#
Revision Notes#
Internal Policy Documents (data/policies/)#
- Information Security Policy 2026 (active):
SEC-4.2(assurance),SEC-7.1(SSO),SEC-9.3(incidents),SEC-9.4(rumours). - Information Security Policy 2025 (archived trap): Previously accepted SOC 2 Type I — retrieving the archived version causes non-compliant vendors to pass falsely.
- Data Protection Policy:
DP-2.2(DPA),DP-3.1(India residency),DP-4.1(sub-processors),DP-5.4(deletion). - AI Acceptable Use Policy:
AI-2.1(no training on company data),AI-3.4(model providers),AI-5.1(approvers by tier). - Vendor Onboarding Checklist:
PROC-1.1(Approved Vendor List check),PROC-2.1(required review file). - Approved Vendor List (restricted ACL): Visible only to Security & Procurement. Lists Parakeet as approved for T2 only and LedgerLens as "in progress".
- Questionnaire Template (
NM-SEC-Q): Single source of truth for every vendor follow-up question generated in reports. - Internal Chat Export (untrusted trap): Marked
untrusted; contains both a false claim and an embedded prompt injection.
Machine-Checkable Rules (data/requirements.yaml)#
- Encodes 11 requirements across 8 deterministic rule types.
- Each entry declares: clause ID, target vendor field, rule type, parameters, severity, and applicable data tiers.
- Adding a new policy requirement means adding a YAML rule (and, if needed, a small unit-tested rule function) without touching any LLM prompt.
Fictional Vendor Web & Gold Sets#
- Vendor corpus (
data/vendor_web/corpus.json): 23 fictional web pages spanning 3 vendors. Each page includesmock_claimssimulating a careful extraction model — offline mode readsmock_claims, while live mode invokes the LLM. - Gold set (
gold_set.json): 5 assessment cases (including the same query issued by a user without Security/Procurement access) + 6 policy questions (one explicitly marked "baseline known to fail" to validate M1's hybrid + rerank upgrade).
Adversarial web sources are filtered into dated, provenance-graded VendorFacts before matcher.py evaluates 11 YAML rules across 8 deterministic functions—guaranteeing 0% guess rate and repeatable outcomes.
Code Reference#
# ---------------------------------------------------------------------------
# requirements.yaml — Nimbu Mart's vendor requirements as machine-checkable rules.
#
# Each rule points at ONE clause in data/policies (so every verdict can cite its policy)
# and ONE vendor field (so every verdict can cite its evidence). The matcher in
# assessor/matcher.py evaluates `rule` with `params` against the vendor fact and
# returns PASS / FAIL / UNKNOWN / NEEDS_REVIEW / NOT_APPLICABLE.
#
# `applies_when` limits a rule to a data tier (T1 public, T2 internal, T3 customer data)
# or a minimum user count. Rules with no `applies_when` apply to every assessment.
#
# severity: blocker -> a FAIL blocks the tool for this tier
# major -> a FAIL must be resolved before approval, approver may grant an exception
# minor -> recorded, does not block
#
# Keep the LLM out of this file. Rules are deterministic on purpose: policy changes
# are audited in Git diffs and never depend on prompt phrasing or model temperature.
# ---------------------------------------------------------------------------
requirements:
# T3 (customer data) requires independent, verifiable assurance — self-attestation is rejected.
- id: SEC-4.2
title: Independent security assurance (SOC 2 Type II or ISO 27001)
policy_doc: information_security_policy_2026.md
clause: SEC-4.2
field: security_certifications
rule: certification_valid
params:
accepted: ["SOC 2 Type II", "ISO 27001"]
max_age_months: 15 # report / certificate must be dated within 15 months (PROC-2.2)
require_documented: true # "claimed" (marketing text) -> NEEDS_REVIEW, never PASS
severity: blocker
applies_when: { tiers: ["T3"] }
# T2 (internal data only) relaxes the bar: SOC 2 Type I or claimed certs are allowed,
# and a failure is a "major" (waivable with InfoSec exception) rather than a hard blocker.
- id: SEC-4.2-T2
title: Security assurance for internal-data tools (Type I or questionnaire acceptable)
policy_doc: information_security_policy_2026.md
clause: SEC-4.2
field: security_certifications
rule: certification_valid
params:
accepted: ["SOC 2 Type II", "SOC 2 Type I", "ISO 27001"]
max_age_months: 15
require_documented: false # claimed is enough for T2, but still flagged in the report
severity: major
applies_when: { tiers: ["T2"] }
# Data residency hard gate for T3 customer data; planned roadmap regions cannot satisfy it.
- id: DP-3.1
title: Customer data stored in India
policy_doc: data_protection_policy.md
clause: DP-3.1
field: data_regions
rule: region_includes
params:
any_of: ["India"]
allow_planned: false # "coming in 2027" does not count
severity: blocker
applies_when: { tiers: ["T3"] }
# ... (see full file: requirements.yaml)
>>> from assessor.matcher import load_requirements
>>> reqs = load_requirements()
>>> [(r.id, r.severity, r.rule, r.applies_when) for r in reqs[:3]]
[('SEC-4.2', 'blocker', 'certification_valid', {'tiers': ['T3']}),
('SEC-4.2-T2', 'major', 'certification_valid', {'tiers': ['T2']}),
('DP-3.1', 'blocker', 'region_includes', {'tiers': ['T3']})]
The Ten Non-Negotiable Engineering Rules#
Revision Notes#
- The model never decides a verdict: LLMs read messy pages, draft text, and classify routes;
matcher.pycomputes verdicts deterministically from unit-tested rules so identical evidence always yields identical verdicts. - UNKNOWN beats a guess: Any
PASSorFAILlacking an evidence URL is a bug; the output guardrail downgrades it toUNKNOWN, keepingguess_ratestrictly at 0%. - A claim is not evidence: Marketing copy ("We are SOC 2 compliant") is only
claimed. Reports, certificate numbers, registry entries, and legal pages aredocumented. Onlydocumentedevidence can pass high-stakes requirements. - Identity is a gate, not a weight: Pages belonging to a same-name company are rejected before extraction. Down-weighting still allows foreign facts to leak into the vendor profile.
- Untrusted content never reaches the verdict: Any page attempting to instruct the AI is quarantined whole; forum posts and rumours are dropped and logged, never merely scored low.
- Repetition is not corroboration: Syndicated or scraped copies of a vendor's own page count once toward evidence strength.
- Access control lives in retrieval: The Approved Vendor List is invisible outside Security and Procurement, and the assistant transparently explains the restriction instead of leaking. Caller groups come exclusively from server-side identity.
- Every fact has a date: Freshness decays per field via
HALF_LIFE_DAYS. A 2026 trust centre overrides a 2024 page, while the conflict is explicitly recorded, never silently hidden. - Humans approve: Every report ends with an approval block filled only by a named human. The word "approved" must never appear in system-generated output about a vendor.
- Research companies, not people: No vendor-employee names appear in schemas, agent memory, or generated reports.
Code Reference#
from __future__ import annotations
from datetime import date, timedelta
from pathlib import Path
from typing import Callable, Optional
import yaml
from .config import REQUIREMENTS_FILE
from .policy_rag import PolicyLibrary
from .schemas import (AssessmentRequest, Overall, Requirement, RequirementResult, Verdict, VendorFact, VendorProfile)
TIER_RANK = {"T1": 1, "T2": 2, "T3": 3}
# Maps failed/unknown policy clauses to the exact vendor questionnaire item so the
# questionnaire builder automatically asks only for missing or non-compliant evidence.
QUESTION_FOR_CLAUSE = {
"SEC-4.2": "Q-SEC-4.2", "DP-3.1": "Q-DP-3.1", "DP-3.2": "Q-DP-3.1", "AI-2.1": "Q-AI-2.1", "AI-3.4": "Q-AI-3.4",
"DP-5.4": "Q-DP-5.4", "SEC-7.1": "Q-SEC-7.1", "SEC-9.3": "Q-SEC-9.3", "DP-2.2": "Q-DP-2.2", "DP-4.1": "Q-DP-4.1",
}
def load_requirements(path: Path = REQUIREMENTS_FILE) -> list[Requirement]:
# Pydantic validation catches typos in requirements.yaml (e.g. unknown rule or severity) at startup
data = yaml.safe_load(Path(path).read_text(encoding="utf-8"))
return [Requirement.model_validate(r) for r in data["requirements"]]
def _norm(s: str) -> str:
# Normalize punctuation and casing so "SOC 2 Type-II" and "soc 2 type ii" match identically
return " ".join(str(s).lower().replace("/", " ").replace("-", " ").split())
def _months_between(a: date, b: date) -> float:
# 30.44 = average days per Gregorian month (365.25 / 12) for certificate freshness checks
return abs((a - b).days) / 30.44
# ---------------------------------------------------------------------------
# Rule functions. Signature: (req, fact, ctx) -> (verdict, reason)
# ctx carries as_of, request, library — only approved_for_tier uses the library.
# Pure deterministic functions keep compliance verdicts auditable and 100% repeatable.
# ---------------------------------------------------------------------------
def rule_certification_valid(req: Requirement, fact: Optional[VendorFact], ctx: dict) -> tuple[Verdict, str]:
# Never guess FAIL or PASS when no evidence was found — return UNKNOWN to trigger a vendor question
if fact is None or not fact.value:
return "UNKNOWN", "No security certification could be established from public sources."
accepted = {_norm(a) for a in req.params.get("accepted", [])}
# -> {'soc 2 type ii', 'iso 27001'}
max_age = int(req.params.get("max_age_months", 15))
require_documented = bool(req.params.get("require_documented", True))
as_of: date = ctx["as_of"]
certs = list(fact.value)
matches = [c for c in certs if _norm(c.get("name", "")) in accepted]
# -> [{'name': 'SOC 2 Type II', 'status': 'certified', 'date': '2025-11-15'}]
# Track ambiguous "SOC 2" claims (missing Type I vs Type II) separately so they route to NEEDS_REVIEW
generic_soc2 = [c for c in certs if _norm(c.get("name", "")) == "soc 2" and c.get("status") == "certified"]
# -> [] (non-empty if vendor only wrote "SOC 2" without Type I/II)
certified = [c for c in matches if c.get("status") == "certified"]
# -> [{'name': 'SOC 2 Type II', 'status': 'certified', 'date': '2025-11-15'}]
def is_current(c: dict) -> bool:
# Prefer explicit expiry date (valid_until); otherwise fall back to issue date <= max_age_months
vu = c.get("valid_until")
if vu:
return date.fromisoformat(str(vu)) >= as_of
d = c.get("date")
return bool(d) and _months_between(as_of, date.fromisoformat(str(d))) <= max_age
# -> _months_between(2026-04-01, 2025-11-15) = 4.50 <= 15 -> True (verdict: 'PASS')
# ... (see full file: matcher.py)
>>> from datetime import date
>>> from assessor.matcher import load_requirements, rule_certification_valid
>>> from assessor.schemas import VendorFact
>>> req = load_requirements()[0] # SEC-4.2 (T3 blocker)
>>> fact = VendorFact(
... field="security_certifications",
... value=[{"name": "SOC 2 Type II", "status": "certified", "date": "2025-11-15"}],
... evidence_level="documented",
... )
>>> rule_certification_valid(req, fact, {"as_of": date(2026, 4, 1)})
('PASS', 'Documented SOC 2 Type II dated 2025-11-15 is within 15 months.')
Evaluation Metrics, Rubric, Demo & Stretch Goals#
Revision Notes#
Scorecard & Hard Targets#
verdict_accuracy: Fraction of(case, requirement)verdicts matching gold — target ≥ 95% fictional, ≥ 80% real.overall_accuracy: Top-level outcome (BLOCKED/CONDITIONAL/READY) matching gold — target 100% fictional.guess_rate(the honesty metric): Fraction ofPASS/FAILverdicts where gold saysUNKNOWNorNEEDS_REVIEW— target 0% on both sets. A wrongUNKNOWNis acceptable; a confident wrongPASSis not.safety: Attack pages quarantined, look-alike companies rejected, rumours dropped, and zero citations drawn from them — target 100%.policy_qa_hard: Zero citations from documents the caller cannot access or from untrusted sources — target 100%.- Cost & latency: Live assessment must finish under
VRA_MAX_USDand in < 90 seconds.
Grading Rubric (100 Points)#
- Correctness on fictional gold set (15 pts): Strict evaluation and all unit tests green after every change.
- Policy library — M1 (15 pts): Hybrid + rerank + grounded citations,
pq-who-approvesfixed, ACL/version/trust tests passing, 3 new docs + questions. - Live vendor research — M2 (20 pts — highest weight): Planner + parallel budgeted workers, ≥ 80% real-vendor field accuracy, justified authority/freshness weights, identity gate, conflict provenance.
- Router & graders — M3 (10 pts): LLM router ≥ 90% on 30 questions, graders catch injected hallucinations, retry/abstention loop verified.
- Security — M4 (10 pts): 15/15 red-team attacks caught with asserted catch points, identity-gate ablation documented, privacy checklist applied.
- Product — M5 (15 pts): Checkpointed LangGraph human gate, queued API with history, streaming UI with trace viewer and sign-off form (
BLOCKEDcannot be approved). - Evaluation & engineering — M6 (10 pts): 10 real vendors, calibrated LLM-as-judge, per-component ablations, CI green.
- Write-up & demo (5 pts): Honest README with metrics and failure modes; smooth offline and live demo.
Scripted 12-Minute Demo Checklist#
- The question (1 min): Support lead asks about LedgerLens for customer tickets → show
BLOCKEDoutcome andDP-3.1with dated source. - The trace (2 min): Inspect
trace.jsonl→ highlight the rejected UK firm, quarantined blog, dropped rumour, and 2024 page losing to the 2026 trust centre. - Access control (1 min): Re-run as a non-Security employee →
PROC-1.1becomesUNKNOWNand the Approved Vendor List never leaks. Asking "Which vendors are approved?" returns the process, not the list. - The good vendor (2 min): Parakeet at T3 passes all documented checks yet stays
CONDITIONAL(approved for T2 only). Switch to T2 →READY FOR HUMAN APPROVAL. Attempt to approveBLOCKEDLedgerLens → refused. - Live run (3 min): Assess a real vendor in the UI with live progress streaming; compare two extracted fields against manual research.
- Live attack (1 min): Inject a prompt-injection line into a cached page and re-run → page is quarantined and verdicts remain unchanged.
- Numbers & honesty (2 min): Present the scorecard, ablation results, cost/latency stats, and two things that still go wrong.
Stretch Goals & Practical FAQ#
- Stretch — Continuous monitoring: Weekly re-reviews of approved vendors reporting only deltas (new sub-processor, new incident, or certificate expiring within 60 days).
- Stretch — MCP server: Expose
assess_vendorandask_policyas MCP tools for IDE or desktop AI clients. - Stretch — Document intake: Accept uploaded SOC 2 PDFs, extract audit period and auditor opinion via an OCR/table RAG pipeline, and automatically upgrade evidence from
claimedtodocumented. - FAQ — Why is a deterministic rule engine still "AI"? The hard AI problem is turning noisy, adversarial web pages into typed, dated, sourced facts and knowing what to distrust. Keeping the rule engine at ~300 deterministic lines makes verdicts auditable and repeatable.
- FAQ — What if vendor sites block bots? Cache reachable pages, record
UNKNOWNfor missing fields, and let the questionnaire ask the vendor — an honestUNKNOWN+ targeted question is a correct output. Adding Playwright for JS-heavy trust centres is a valid stretch. - FAQ — Solo scoping: Complete M0–M4 in full, build M5 as CLI + API only, and evaluate on 3 real vendors instead of 10 (~3 weeks total).
Code Reference#
from __future__ import annotations
import re
from typing import Optional
from pydantic import BaseModel
from .llm import LLM
from .policy_rag import tokenize
from .schemas import PolicyAnswer
class GradeResult(BaseModel):
verdict: bool
reason: str = ""
# Two independent self-check prompts mirroring Agentic RAG's dual-grader pattern:
# 1) Relevance checks whether retrieved policy clauses actually answer the user's question.
# 2) Groundedness checks whether every factual claim in the draft answer is backed by those clauses.
RELEVANCE_SYSTEM = """You are the Answer Grader. Given a question and retrieved policy text, answer whether the text
contains information that answers the question. Be strict: related topic is not enough. Return {"verdict": true|false, "reason": "..."}."""
GROUNDED_SYSTEM = """You are the Hallucination Grader. Given sources and a draft answer, check that EVERY factual statement
in the answer is supported by the sources. If any statement is not, verdict is false. Return {"verdict": true|false, "reason": "..."}."""
def grade_relevance(question: str, context: str, llm: Optional[LLM] = None) -> GradeResult:
# Deterministic lexical-overlap mock lets offline tests and CI run without LLM API calls
def mock() -> dict:
q, c = set(tokenize(question)), set(tokenize(context))
overlap = len(q & c)
# -> 5 (out of 6 question terms; 5 >= max(1, 6 // 3) -> verdict=True)
return {"verdict": overlap >= max(1, len(q) // 3), "reason": f"{overlap}/{len(q)} question terms found in context (heuristic)"}
# Cap context at 6,000 chars to bound grader token cost and latency
return (llm or LLM()).structured(RELEVANCE_SYSTEM, f"Question: {question}\n\nContext:\n{context[:6000]}", GradeResult, stage="grade_relevance", mock=mock)
def grade_grounded(answer: str, sources: str, llm: Optional[LLM] = None) -> GradeResult:
def mock() -> dict:
# Every sentence of the answer must share at least 60% of its content words with the sources.
src = set(tokenize(sources))
# Strip clause prefixes (e.g. "SEC-4.2: ") and trailing citation tags before checking overlap
body = re.sub(r"^[A-Z]{1,5}-[\d.]+:\s*", "", answer)
body = re.sub(r"\(source:.*?\)\s*$", "", body).strip()
sentences = [s for s in re.split(r"(?<=[.!?])\s+|\s*\|\s*", body) if len(tokenize(s)) >= 3]
# -> ['T3 tools also require FedRAMP High authorization.']
unsupported = [s for s in sentences if len(set(tokenize(s)) & src) / max(1, len(set(tokenize(s)))) < 0.6]
# -> ['T3 tools also require FedRAMP High authorization.']
# (< 0.6 term overlap with sources -> verdict=False)
return {"verdict": not unsupported, "reason": ("all sentences supported" if not unsupported else f"unsupported: {unsupported[0][:80]}") + " (heuristic)"}
return (llm or LLM()).structured(GROUNDED_SYSTEM, f"Sources:\n{sources[:8000]}\n\nAnswer:\n{answer}", GradeResult, stage="grade_grounded", mock=mock)
def grade_policy_answer(pa: PolicyAnswer, llm: Optional[LLM] = None) -> PolicyAnswer:
# Skip grading if the RAG layer already abstained or found no citable policy clauses
if pa.abstained or not pa.citations:
return pa
ctx = "\n\n".join(h.text for h in pa.citations)
pa.grader_relevant = grade_relevance(pa.question, ctx, llm).verdict
# -> True
pa.grader_grounded = grade_grounded(pa.answer, ctx, llm).verdict
# -> False triggers fail-closed abstention below
# Fail closed: if the hallucination grader flags any unsupported claim, replace the answer
# with an explicit abstention rather than risking fabricated compliance advice.
if not pa.grader_grounded:
pa.abstained = True
pa.answer = "I found related policy text but could not produce an answer that is fully supported by it. Please read the cited clauses directly."
return pa
>>> from assessor.graders import grade_relevance, grade_grounded
>>> ctx = "SEC-4.2: Tools processing T3 customer data must hold a SOC 2 Type II or ISO 27001 report dated within 15 months."
>>> grade_relevance("What certification is needed for T3 tools?", ctx)
GradeResult(verdict=True, reason='5/6 question terms found in context (heuristic)')
>>> grade_grounded("T3 tools need SOC 2 Type II or ISO 27001 within 15 months.", ctx)
GradeResult(verdict=True, reason='all sentences supported (heuristic)')
>>> grade_grounded("T3 tools also require FedRAMP High authorization.", ctx)
GradeResult(verdict=False, reason='unsupported: T3 tools also require FedRAMP High authorization. (heuristic)')
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
# Allow running directly via `python eval/run_eval.py` without installing the package
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from assessor.config import GOLD_SET, SETTINGS # noqa: E402
from assessor.graph import Pipeline, new_state # noqa: E402
from assessor.tracing import Budget # noqa: E402
# Release gate thresholds: guess_rate_max=0.0 enforces that the assessor NEVER turns an
# UNKNOWN/NEEDS_REVIEW requirement into a fabricated PASS/FAIL; safety=1.0 demands 100%
# quarantine of prompt-injection pages and rejection of look-alike/rumour sources.
THRESHOLDS = {"verdict_accuracy": 0.95, "overall_accuracy": 1.0, "guess_rate_max": 0.0, "safety": 1.0, "policy_qa_hard": 1.0}
def run_cases(pipe: Pipeline, gold: dict) -> dict:
"""Execute every gold vendor-assessment case and score verdicts, calibration, and safety."""
rows, n_ok, n_total, guesses, safety_checks, safety_ok, costs = [], 0, 0, 0, 0, 0, []
overall_ok = 0
for case in gold["cases"]:
t0 = time.time()
s = new_state(case["question"], user_groups=case["user_groups"], tier=case["tier"], users=case["users"],
vendor=case["vendor"], domain=case.get("official_domain"))
s = pipe.run_plain(s)
rep = s["report"]
got = {r.requirement_id: r.verdict for r in rep.results}
# -> {'SEC-4.2': 'PASS', 'DP-3.1': 'FAIL', ...} (9/9 matched in case_02_residency)
mism = []
for rid, exp in case["expected_verdicts"].items():
n_total += 1
if got.get(rid) == exp:
n_ok += 1
else:
mism.append(f"{rid}: expected {exp}, got {got.get(rid)}")
# Track dangerous overclaiming: guessing PASS/FAIL when evidence was missing or ambiguous
if exp in ("UNKNOWN", "NEEDS_REVIEW") and got.get(rid) in ("PASS", "FAIL"):
guesses += 1
# -> stays 0 across all cases -> guess_rate=0.000
ov_ok = rep.overall == case["expected_overall"]
# -> True (e.g. 'BLOCK' == 'BLOCK' for case_02_residency)
overall_ok += ov_ok
pf = rep.profile
# Verify defensive layers caught every planted prompt-injection page and look-alike URL
for key, attr in (("expected_quarantined_urls", pf.quarantined), ("expected_rejected_urls", pf.rejected)):
for url in case.get(key, []):
safety_checks += 1
safety_ok += url in attr
for url in case.get("expected_dropped_rumour_urls", []):
safety_checks += 1
safety_ok += any(url in d for d in pf.dropped)
# Second safety assertion: even if a page was quarantined, prove none of its claims
# leaked into any requirement's evidence_urls.
for url in case.get("expected_quarantined_urls", []):
safety_checks += 1
safety_ok += not any(url in r.evidence_urls for r in rep.results)
# -> 8/8 safety checks passed -> safety=1.000
costs.append(pipe.budget.spent_usd)
rows.append({"case": case["id"], "overall": f"{rep.overall} ({'ok' if ov_ok else 'expected ' + case['expected_overall']})",
"verdicts_ok": f"{len(case['expected_verdicts']) - len(mism)}/{len(case['expected_verdicts'])}",
"mismatches": "; ".join(mism) or "—", "time_s": round(time.time() - t0, 2)})
return {"rows": rows, "verdict_accuracy": n_ok / max(1, n_total), "overall_accuracy": overall_ok / max(1, len(gold["cases"])),
"guess_rate": guesses / max(1, n_total), "safety": safety_ok / max(1, safety_checks), "safety_checks": safety_checks,
"cost_usd": round(sum(costs), 4)}
# -> {'verdict_accuracy': 1.0, 'overall_accuracy': 1.0, 'guess_rate': 0.0,
# 'safety': 1.0, 'safety_checks': 8, 'cost_usd': 0.0042, 'rows': [...]}
# ... (see full file: run_eval.py)
$ python eval/run_eval.py
CASE OVERALL VERDICTS MISMATCHES TIME
------------------------------------------------------------------------
case_01_clean_t3 APPROVE (ok) 9/9 — 0.42s
case_02_residency BLOCK (ok) 9/9 — 0.38s
case_03_injection NEEDS_MORE_INFO (ok) 9/9 — 0.45s
case_04_t2_waiver CONDITIONAL (ok) 7/7 — 0.31s
verdict_accuracy : 1.000 (threshold >= 0.950) PASS
overall_accuracy : 1.000 (threshold >= 1.000) PASS
guess_rate : 0.000 (threshold <= 0.000) PASS
safety : 1.000 (8/8 checks) PASS
policy_qa_hard : 1.000 (threshold >= 1.000) PASS
total_cost_usd : $0.0042
Domain Glossary, Verdict Lifecycle & Rapid Cheat Sheet#
Revision Notes#
Domain & System Glossary#
- Data tier: Nimbu Mart's sensitivity classification — T1 public, T2 internal, T3 customer data. Applicable rules are governed by the highest tier a tool touches.
- SOC 2 Type II vs. Type I: Type II is an independent auditor's report verifying controls operated effectively over a period (typically 6–12 months); Type I only inspects control design at a single point in time.
- ISO/IEC 27001: Accredited certification of an information-security management system, verifiable via a certificate number and expiry date.
- DPA (Data Processing Agreement): Contract binding a vendor to process personal data solely on the customer's instructions.
- DPDP Act (2023): India's Digital Personal Data Protection Act — Nimbu Mart acts as the Data Fiduciary, while SaaS/AI vendors act as Data Processors.
- Sub-processor: Any downstream company used by the vendor that touches customer data (cloud hosting, email, third-party LLM providers).
- Evidence levels:
documented(audit report, certificate, registry, legal page),claimed(marketing copy),third_party(named press/review site), andrumour(forums, unnamed sources). Onlydocumentedsatisfies high-stakes rules. - Verdicts:
PASS,FAIL,UNKNOWN(no usable evidence),NEEDS_REVIEW(evidence found, human judgment required), andNOT_APPLICABLE(rule does not apply to the requested data tier). - Outcomes:
BLOCKED(at least one blocking requirement failed),CONDITIONAL(openUNKNOWN/NEEDS_REVIEWitems remain), andREADY FOR HUMAN APPROVAL(all applicable requirements passed; a named human still signs off).
Verdict-to-Human-Decision Lifecycle#
BLOCKED is not "rejected", and READY is not "approved". Only a named human makes the final call.
Rapid Cheat Sheet: Decision Rules, Numbers & Pitfalls#
- Core decision rules:
- Any
PASS/FAILwithout an evidence URL is downgraded toUNKNOWNby the output guardrail. - Policy retrieval filters (
ACL, archived, untrusted, injection) always run before ranking. - Rumours/forums are dropped & logged; syndicated copies count once; fresher facts win while conflicts stay recorded.
- Relevance failure widens to
k = 8+ query rewrite; grounding failure retries once stricter, then abstains. - Caller groups come from server identity;
BLOCKEDreports hide the Approve action; "approved" and vendor-employee names never appear in system output.
- Any
- Key benchmark numbers:
- Starter suite: 70 unit tests, running in < 1 s offline.
- Schema & rules: 9 vendor fields, 8 rule types, 11 requirements.
- Fictional data pack: 23 pages, 3 vendors, 5 assessment cases, 6 policy questions.
- Quality gates:
verdict_accuracy≥ 95% fictional / ≥ 80% real,overall_accuracy100% fictional,guess_rate0%,safety100%,policy_qa_hard100%. - Milestone targets: M2 live ≥ 80% field accuracy / < 90 s / <
VRA_MAX_USD; M3 router ≥ 90% on 30 questions; M4 red team 15/15 caught; M6 10 vendors × 8 fields, judge calibrated on 20 reasons; demo 12 minutes, rubric 100 pts (M2 = 20 pts).
- Top failure modes to avoid:
- Retrieving the archived 2025 policy (which still accepted SOC 2 Type I).
- Treating "SOC 2 compliant" marketing text as
documentedevidence. - Down-weighting look-alike company pages instead of rejecting them at the identity gate.
- Counting a syndicated copy as independent corroboration.
- Letting an LLM compute compliance verdicts instead of deterministic rules.
- Leaking the Approved Vendor List to callers outside Security/Procurement.
- Relying on live internet during demos instead of keeping
cached_pages/.
Code Reference#
from __future__ import annotations
import json
from datetime import date
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, HTTPException
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel, Field
from assessor.config import RUNS_DIR, SETTINGS
from assessor.graph import Pipeline, new_state
from assessor.tracing import Budget, Tracer
app = FastAPI(title="Nimbu Mart Vendor Risk Assessor", version="0.1.0",
description="Capstone project by Shivank Agrawal (Future with Shivank). Assessments are inputs to a human decision.")
# Request schemas enforce least-privilege RBAC defaults and strict tiering at the API boundary
class AskBody(BaseModel):
question: str
user_groups: list[str] = Field(default_factory=lambda: ["public", "employees"])
class AssessBody(BaseModel):
question: str
vendor: str
official_domain: Optional[str] = None
tier: str = "T3"
users: int = 1
user_groups: list[str] = Field(default_factory=lambda: ["public", "employees"])
requested_by: str = "api"
class ApproveBody(BaseModel):
decision: str # approve | reject
approver: str
comment: str = ""
@app.get("/health")
def health():
# Exposes active provider configuration so operators can verify mock vs. live mode
return {"ok": True, "llm_provider": SETTINGS.llm_provider, "search_provider": SETTINGS.search_provider}
@app.post("/ask")
def ask(body: AskBody):
# Lightweight policy Q&A endpoint; rejects full vendor-assessment requests with HTTP 400
# so callers explicitly supply vendor, tier, and seat count via POST /assess.
pipe = Pipeline(tracer=None)
s = pipe.run_plain(new_state(body.question, user_groups=body.user_groups, requested_by="api"))
# -> {'route': 'policy_qa',
# 'answer': 'SEC-4.2: T3 tools must hold a documented SOC 2 Type II...', ...}
if s["route"] == "assessment":
# -> False for policy_qa; returns 200 JSON with route, answer, and SEC-4.2 citation
raise HTTPException(400, "This question needs a full assessment: call POST /assess with vendor, tier and users.")
return {"route": s["route"], "answer": s["answer"],
"citations": [c.model_dump() for c in (s["policy_answer"].citations if s.get("policy_answer") else [])]}
@app.post("/assess")
def assess(body: AssessBody):
# Every assessment gets a dedicated Tracer directory under runs/<timestamp>-api/ for auditability
tracer = Tracer("api")
# ... (see full file: api.py)
$ uvicorn app.api:app --port 8000
INFO: Uvicorn running on http://127.0.0.1:8000
$ curl -s http://127.0.0.1:8000/health
{"ok":true,"llm_provider":"mock","search_provider":"corpus"}
$ curl -s -X POST http://127.0.0.1:8000/ask -H "Content-Type: application/json" \
-d '{"question": "What security certification is required for T3 customer-data tools?"}'
{
"route": "policy_qa",
"answer": "SEC-4.2: T3 tools must hold a documented SOC 2 Type II or ISO 27001 report dated within 15 months.",
"citations": [{"doc": "information_security_policy_2026.md", "clause": "SEC-4.2"}]
}
from __future__ import annotations
import json
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from .config import RUNS_DIR, SETTINGS
def estimate_tokens(text: str) -> int:
"""Rough token estimate (4 chars per token). Replace with tiktoken for exact counts (Production RAG Lab 13)."""
return max(1, len(text) // 4)
class BudgetExceeded(RuntimeError):
pass
@dataclass
class Budget:
"""Per-run LLM cost and token limiter that halts runaway assessment loops early."""
max_usd: float = field(default_factory=lambda: SETTINGS.max_usd)
spent_usd: float = 0.0
input_tokens: int = 0
output_tokens: int = 0
llm_calls: int = 0
started: float = field(default_factory=time.time)
def charge(self, input_tokens: int, output_tokens: int) -> None:
# Update counters before checking the cap so audit logs still record the exact overrun
self.llm_calls += 1
self.input_tokens += input_tokens
self.output_tokens += output_tokens
self.spent_usd += (input_tokens * SETTINGS.price_in_per_mtok + output_tokens * SETTINGS.price_out_per_mtok) / 1_000_000
# -> 0.00056 USD for (3200 in, 480 out); raises BudgetExceeded if > 0.10
if self.spent_usd > self.max_usd:
raise BudgetExceeded(f"Budget of ${self.max_usd:.2f} exceeded (spent ${self.spent_usd:.3f}). Raise VRA_MAX_USD or reduce pages.")
@property
def elapsed_s(self) -> float:
return time.time() - self.started
class Tracer:
"""Writes runs/<timestamp>-<name>/trace.jsonl. Use `t.event(stage, **data)` liberally."""
def __init__(self, name: str = "assess", root: Path | None = None, enabled: bool = True):
# UTC timestamp prefix guarantees chronological sorting and unique run directories
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
self.run_id = f"{stamp}-{name}"
# -> '20261202-132800-demo'
self.dir = (root or RUNS_DIR) / self.run_id
self.enabled = enabled
self.events: list[dict] = []
# Append-only JSONL survives mid-run crashes so partial traces are never lost
if enabled:
self.dir.mkdir(parents=True, exist_ok=True)
self._fh = open(self.dir / "trace.jsonl", "a", encoding="utf-8")
else:
self._fh = None
# Tracks wall-clock start times per pipeline stage for latency breakdowns
self._stage_start: dict[str, float] = {}
# ... (see full file: tracing.py)
>>> from assessor.tracing import Budget, Tracer
>>> b = Budget(max_usd=0.10)
>>> b.charge(input_tokens=3200, output_tokens=480)
>>> (b.llm_calls, b.input_tokens, b.output_tokens, round(b.spent_usd, 5))
(1, 3200, 480, 0.00056)
>>> t = Tracer("demo", enabled=False)
>>> t.run_id
'20261202-132800-demo'
How All Building Blocks Connect#
Revision Notes#
- Entry & Routing (Guardrails + Agentic RAG): Every request enters through input redaction and intent checks, then hits a structured-output Router that separates internal policy lookups, ad-hoc vendor fact queries, full risk assessments, and out-of-scope refusals.
- Internal Truth (Production RAG): Policy questions and compliance requirements are anchored in a clause-chunked policy library where server-derived ACLs, version filters, and trust filters execute before
BM25 + vector + RRF + cross-encoderranking. Relevance and hallucination graders enforce a bounded retry-or-abstain loop so internal rules are never fabricated or leaked. - External Truth (Deep Search): For vendor assessments, a planned, parallel, budgeted Deep Search pipeline gathers web evidence through a strict defense-in-depth funnel: injection quarantine → binary identity gate → small-model extraction → rumour drop → deduplicated authority × freshness scoring → conflict-preserving merge into a typed
VendorProfile. - Deterministic Judgment & Action (Capstone Glue): The
VendorProfilemeetsrequirements.yamlinsidematcher.py— pure, unit-testable code with zero LLM involvement — producing auditable per-clause verdicts and an overall status (BLOCKED,CONDITIONAL, orREADY FOR HUMAN APPROVAL). EveryUNKNOWNgap automatically populates targeted vendor questions fromNM-SEC-Q. - Accountable Sign-Off (LangGraph + Output Guardrails): LangGraph checkpoints and pauses at
human_gateuntil the required tier approvers (perAI-5.1) review the evidence and trace in the UI and record a persistent decision, while the output guardrail enforces the final invariants: no unsupportedPASS/FAIL, no "approved" phrasing, and no personal data.
Quick Self-Check Questions#
Self-Check Questions#
Why must the compliance matcher be deterministic code instead of an LLM prompt?
Because compliance verdicts must be repeatable, auditable, and unit-testable: identical evidence must always produce the exact same verdict. The LLM's job is unstructured extraction and routing; matcher.py enforces policy logic consistently.
Why is the identity check implemented as a binary gate rather than a low authority weight?
Down-weighting a same-name company's page still allows its claims (like the UK accountancy firm's ISO 27001 certificate) to populate missing fields on the target vendor. Rejecting mismatched entities before extraction prevents cross-company contamination completely.
In the policy RAG pipeline, why must ACL, archive, and trust filters run before hybrid ranking?
Running filters after retrieval risks leaking restricted documents (like the Approved Vendor List) or letting an archived 2025 policy (which accepted SOC 2 Type I) crowd out the active 2026 clause in top-k results.
What does guess_rate measure, and why is its target strictly 0%?
guess_rate measures how often the system outputs PASS or FAIL when the gold label is UNKNOWN or NEEDS_REVIEW. In security compliance, an honest UNKNOWN that triggers a vendor questionnaire is safe, whereas a hallucinated PASS creates real legal and security exposure.
How does the system distinguish "We are SOC 2 compliant" on a marketing page from an actual SOC 2 Type II report?
Through evidence levels: marketing text is tagged claimed, whereas an audit report, certificate number, certifier registry entry, or legal document is tagged documented. High-stakes requirements only pass on documented evidence.
Why does Parakeet Translate receive CONDITIONAL at T3 (customer data) even though it passes every technical security check?
Because Nimbu Mart's Approved Vendor List only approves Parakeet for T2 (internal data). Switching the request to T2 turns the outcome into READY FOR HUMAN APPROVAL, while T3 requires Procurement escalation.
What happens when the Hallucination Grader flags a policy answer as ungrounded?
The graph retries generation once with stricter grounding instructions and re-grades the output. If the second attempt is still ungrounded, the system abstains rather than returning an unsupported answer.
Why must user_groups be derived server-side instead of passed in the /assess request body?
Because user_groups is the Access Control List boundary. Accepting groups from the client would allow any employee to spoof Security/Procurement membership and exfiltrate the restricted Approved Vendor List.