Zero Labs
Industry News / Technology

The Air-Gapped Chronicles: The Passport Stack

Source · Towards AI By Piyoosh Rai

From the publisher’s feed, collected in the ZeroLabs newsroom.

Decoupled Logic for Geopolitical PortabilityEvery AI architect looks brilliant in Market #1. You build for your jurisdiction, hardcode the regs, ship fast. In 2026, that’s architectural debt disguised as velocity.I’ve seen teams spend 18 months on a sovereign agent for Riyadh, then discover Brazil requires a 40% rewrite. Why? They baked the Border into the Brain.If your agent code has if jurisdiction == 'SA': inside tool-calling loops, you don't have a platform. You have a Geopolitical Prison.The fix is Jurisdictional Abstraction. Decouple the agentic brain from the compliance sidecar.The Anti-Pattern That Kills Market #2Here’s the code that destroys portability:class HealthcareAgent: def process_claim(self, claim_data): # WRONG: Jurisdiction logic in agent core if claim_data['jurisdiction'] == 'SA': # Saudi-specific compliance baked in if claim_data['contains_phi']: if not self._is_in_kingdom(claim_data['location']): raise ComplianceError("SDAIA 4.7.2 violation") # Saudi retention rules self.vault.archive(claim_data, retention_days=2555) # Saudi authorization threshold decision = self.llm.decide(claim_data) if decision['confidence'] return self._require_dual_approval(decision) elif claim_data['jurisdiction'] == 'BR': # Brazil completely different if claim_data['contains_sensitive']: if not self._check_lgpd_basis(claim_data): raise ComplianceError("LGPD Article 7 violation") # Different retention self.vault.archive(claim_data, retention_days=1825) # Different threshold decision = self.llm.decide(claim_data) if decision['confidence'] return self._require_single_approval(decision) return decisionThis code is a death sentence for expansion.When UAE regulations change, you modify agent logic. When India launches DPDP enforcement, you rewrite core loops. When regulatory auditors ask “show me where SDAIA compliance happens,” you can’t — it’s scattered across 47 files.The coupling is the problem. Agent logic should know nothing about jurisdictions.Geopolitical Prison vs Passport Stack: Hardcoded compliance requires 6 months per market. Config-driven sidecars deploy new jurisdictions in 2 weeks.The Sidecar Pattern: Brain vs BorderSeparate concerns. The agent is a stateless reasoning engine. The sidecar is the passport.Architecture:Request → Sidecar (SA config) → Agent (jurisdiction-agnostic) → Sidecar → ResponseThe agent never sees jurisdiction rules. It processes intent. The sidecar enforces compliance before and after.Why a sidecar and not a library?Libraries create language lock-in and versioning hell. If your compliance layer is a separate container, you get:Heterogeneous stacks — Agent in Python, sidecar in Rust for performanceIndependent lifecycles — Update SDAIA rules without touching agent codeFailure isolation — Sidecar crash blocks PII from ever reaching agent memoryThe sidecar is middleware, not a library import.Implementation: The JurisdictionalSidecar ClassHere’s the actual implementation. Not pseudocode — production code.import yamlfrom typing import Dict, Any, Optionalfrom datetime import datetime, timedeltaimport hashlibimport reclass JurisdictionalSidecar: """ Compliance enforcement layer Agent code never changes when entering new markets """ def __init__(self, jurisdiction: str, config_path: str = "/etc/passports"): self.jurisdiction = jurisdiction self.config = self._load_config(f"{config_path}/{jurisdiction}.yaml") self.vault = self._init_vault() def _load_config(self, path: str) -> Dict: """Load jurisdiction config from YAML""" with open(path, 'r') as f: return yaml.safe_load(f) def intercept_inbound(self, request: Dict[str, Any]) -> Dict[str, Any]: """ Enforce compliance BEFORE agent sees data Returns cleaned request or raises ComplianceError """ # Step 1: Classify data sensitivity classification = self._classify_data(request) # Step 2: Validate residency requirements residency_check = self._enforce_residency(request, classification) if not residency_check['allowed']: raise ComplianceError( f"{self.jurisdiction}: {residency_check['violation']}" ) # Step 3: Mask PII according to jurisdiction rules cleaned = self._mask_pii(request, classification) # Step 4: Determine routing cleaned['_inference_location'] = self._route_inference(classification) # Step 5: Log inbound (with full PII, local vault only) self._log_inbound(request, classification) return cleaned def intercept_outbound(self, response: Dict[str, Any], original_request: Dict[str, Any]) -> Dict[str, Any]: """ Validate agent output BEFORE returning to user """ # Step 1: Check authorization requirements if response['confidence'] if self.config['authorization']['dual_approval_required']: response['status'] = 'PENDING_DUAL_APPROVAL' response['approvers_required'] = 2 else: response['status'] = 'PENDING_APPROVAL' response['approvers_required'] = 1 # Step 2: Format audit log per jurisdiction schema audit = self._format_audit_log(original_request, response) # Step 3: Archive with jurisdiction retention policy self._archive_with_retention( audit, days=self.config['retention']['audit_logs_days'] ) # Step 4: Validate no PII leakage in response self._validate_output_compliance(response) return response def _classify_data(self, request: Dict[str, Any]) -> Dict[str, str]: """ Classify data sensitivity per jurisdiction definitions Saudi: Category 1 (PHI, biometrics) vs Category 2 Brazil: Sensitive (LGPD Art 11) vs Regular """ classification = { 'level': 'UNKNOWN', 'contains_phi': False, 'contains_biometric': False, 'contains_financial': False } # Use jurisdiction-specific classifiers classifiers = self.config['data_classification']['classifiers'] for field, value in request.items(): if field in classifiers.get('phi_fields', []): classification['contains_phi'] = True if field in classifiers.get('biometric_fields', []): classification['contains_biometric'] = True # Pattern-based detection if isinstance(value, str): # National ID patterns if re.match(classifiers.get('national_id_pattern', ''), value): classification['contains_phi'] = True # Health record patterns if any(keyword in value.lower() for keyword in classifiers.get('health_keywords', [])): classification['contains_phi'] = True # Determine sensitivity level if self.jurisdiction == 'SA': if classification['contains_phi'] or classification['contains_biometric']: classification['level'] = 'CATEGORY_1' else: classification['level'] = 'CATEGORY_2' elif self.jurisdiction == 'BR': sensitive_fields = ['contains_phi', 'contains_biometric'] if any(classification[f] for f in sensitive_fields): classification['level'] = 'SENSITIVE' else: classification['level'] = 'REGULAR' return classification def _enforce_residency(self, request: Dict[str, Any], classification: Dict[str, str]) -> Dict[str, Any]: """ Check if data can be processed based on residency rules """ rules = self.config['data_residency'] current_location = request.get('_current_location', 'UNKNOWN') if self.jurisdiction == 'SA': # SDAIA 4.7.2: Category 1 must stay in-Kingdom if classification['level'] == 'CATEGORY_1': if current_location != 'SA': return { 'allowed': False, 'violation': 'SDAIA 4.7.2: Category 1 data must be processed in-Kingdom' } elif self.jurisdiction == 'BR': # LGPD Article 33: Sensitive data local processing preferred if classification['level'] == 'SENSITIVE': if rules.get('sensitive_local_required', False): if current_location not in ['BR', 'LATAM_APPROVED']: return { 'allowed': False, 'violation': 'LGPD Article 33: Sensitive data requires local processing' } return {'allowed': True} def _mask_pii(self, request: Dict[str, Any], classification: Dict[str, str]) -> Dict[str, Any]: """ Mask PII fields according to jurisdiction rules Agent sees tokenized versions, not raw data """ masked = request.copy() pii_fields = self.config['pii_masking']['fields'] for field in pii_fields: if field in masked: # Hash the value for consistent tokenization token = hashlib.sha256( f"{field}:{masked[field]}".encode() ).hexdigest()[:12] # Store mapping locally (NEVER sent to agent) self.vault.store_pii_mapping(token, masked[field]) # Replace with token masked[field] = f"TOKEN_{token}" return masked def _route_inference(self, classification: Dict[str, str]) -> str: """ Determine where inference should happen based on data sensitivity """ routing = self.config['inference_routing'] if self.jurisdiction == 'SA': if classification['level'] == 'CATEGORY_1': return routing['category_1'] # "RIYADH_LOCAL" return routing['category_2'] # "UAE_APPROVED" elif self.jurisdiction == 'BR': if classification['level'] == 'SENSITIVE': return routing['sensitive'] # "SAO_PAULO_LOCAL" return routing['regular'] # "LATAM_REGION" return routing.get('default', 'GLOBAL') def _format_audit_log(self, request: Dict[str, Any], response: Dict[str, Any]) -> Dict[str, Any]: """ Format audit entry per jurisdiction schema requirements """ base_entry = { 'timestamp': datetime.now().isoformat(), 'jurisdiction': self.jurisdiction, 'request_id': request.get('request_id'), 'decision': response.get('decision'), 'confidence': response.get('confidence'), } # Jurisdiction-specific fields schema = self.config['audit_schema'] if schema == 'SDAIA_STANDARD': base_entry.update({ 'regulation_basis': 'SDAIA_4.7.2', 'data_category': request.get('_classification', {}).get('level'), 'inference_location': response.get('_inference_location'), 'retention_until': ( datetime.now() + timedelta(days=self.config['retention']['audit_logs_days']) ).isoformat() }) elif schema == 'ANPD_FORMAT': base_entry.update({ 'legal_basis': 'LGPD_Article_7', 'treatment_purpose': request.get('purpose'), 'consent_obtained': request.get('consent', False), 'data_subject_rights': 'ANPD_RIGHTS_DISCLOSURE' }) elif schema == 'DFSA_STANDARD': base_entry.update({ 'regulation': 'DIFC_Law_5_2020', 'data_protection_officer': self.config.get('dpo_contact'), 'cross_border_transfer': response.get('_inference_location') != 'AE' }) return base_entryThe Config Files: Jurisdictions as DataEach jurisdiction is a YAML file. No code changes for new markets.SA.yaml (Saudi Arabia):jurisdiction: "SA"jurisdiction_name: "Saudi Arabia"regulations: - "SDAIA_4.7.2" - "PDPL_Article_43"data_classification: classifiers: phi_fields: ["medical_record", "diagnosis", "treatment", "prescription"] biometric_fields: ["fingerprint", "iris_scan", "voice_print", "facial_image"] national_id_pattern: '^\d{10}$' health_keywords: ["diabetes", "hypertension", "cancer", "hiv", "mental health"]data_residency: category_1_local_required: true category_2_approved_regions: ["SA", "AE", "BH"]inference_routing: category_1: "RIYADH_H100_CLUSTER" category_2: "DUBAI_APPROVED"pii_masking: fields: ["national_id", "patient_name", "dob", "phone", "email"]authorization: threshold: 0.75 dual_approval_required: trueretention: audit_logs_days: 2555 # 7 years raw_data_days: 2555audit_schema: "SDAIA_STANDARD"BR.yaml (Brazil):jurisdiction: "BR"jurisdiction_name: "Brazil"regulations: - "LGPD_Article_7" - "LGPD_Article_33" - "LGPD_Article_46"data_classification: classifiers: phi_fields: ["prontuario", "diagnostico", "tratamento"] biometric_fields: ["impressao_digital", "reconhecimento_facial"] national_id_pattern: '^\d{3}\.\d{3}\.\d{3}-\d{2}$' # CPF format health_keywords: ["diabetes", "hipertensao", "cancer", "saude mental"]data_residency: sensitive_local_required: true regular_data_regions: ["BR", "AR", "CL"]inference_routing: sensitive: "SAO_PAULO_LOCAL" regular: "LATAM_REGION"pii_masking: fields: ["cpf", "nome", "data_nascimento", "telefone", "email"]authorization: threshold: 0.80 dual_approval_required: falseretention: audit_logs_days: 1825 # 5 years raw_data_days: 1825audit_schema: "ANPD_FORMAT"AE.yaml (UAE):jurisdiction: "AE"jurisdiction_name: "United Arab Emirates"regulations: - "DIFC_Law_5_2020" - "TDRA_Guidelines"data_classification: classifiers: phi_fields: ["medical_record", "diagnosis", "treatment"] biometric_fields: ["emirates_id_biometric", "fingerprint"] national_id_pattern: '^\d{3}-\d{4}-\d{7}-\d{1}$' # Emirates ID health_keywords: ["diabetes", "hypertension", "cardiac"]data_residency: category_1_local_required: false approved_regions: ["AE", "SA", "BH", "OM", "KW", "QA"]inference_routing: category_1: "DUBAI_LOCAL" category_2: "GCC_REGION"pii_masking: fields: ["emirates_id", "patient_name", "dob", "mobile"]authorization: threshold: 0.70 dual_approval_required: trueretention: audit_logs_days: 3650 # 10 years (DFSA requirement) raw_data_days: 3650audit_schema: "DFSA_STANDARD"The Agent: Jurisdiction-Agnostic CoreWith the sidecar pattern, agent code never references jurisdictions:class HealthcareAgent: """ Pure agent logic - no compliance, no jurisdiction awareness Sidecar handles all regulatory enforcement """ def __init__(self, llm, tools): self.llm = llm self.tools = tools def process(self, cleaned_request: Dict[str, Any]) -> Dict[str, Any]: """ Process request that's already been validated by sidecar Never sees raw PII - only tokenized versions """ # Extract intent intent = self._parse_intent(cleaned_request) # Route to inference location (determined by sidecar) inference_location = cleaned_request.get('_inference_location') # Execute reasoning (location-aware but jurisdiction-agnostic) with self._inference_context(inference_location): decision = self.llm.generate( prompt=self._build_prompt(intent), tools=self.tools ) # Return decision with confidence return { 'decision': decision['output'], 'confidence': decision['confidence'], 'reasoning': decision['reasoning_trace'], '_inference_location': inference_location } def _inference_context(self, location: str): """ Route inference to appropriate infrastructure Agent doesn't know WHY - sidecar determined routing """ if location == "RIYADH_H100_CLUSTER": return self._local_inference_context("riyadh-prod") elif location == "SAO_PAULO_LOCAL": return self._local_inference_context("saopaulo-prod") elif location == "DUBAI_LOCAL": return self._local_inference_context("dubai-prod") else: return self._global_inference_context()Zero jurisdiction logic. Zero compliance checks. Pure reasoning.Same agent core, different passports: SA.yaml routes to Riyadh with 7-year retention, BR.yaml to São Paulo with 5-year retention, AE.yaml to Dubai with 10-year retention. Market expansion = YAML file swap.Deployment: Market #2 in 11 DaysDay 1–3: Legal mappingLegal team documents LGPD requirements:Sensitive data = biometrics + health records (Article 11)Local processing preferred (Article 33)5-year retention (Article 16)ANPD audit format requiredDay 4–6: Config creationDevOps creates BR.yaml:bashcp configs/SA.yaml configs/BR.yaml# Edit BR.yaml with Brazil-specific rulesvim configs/BR.yamlChanges:retention: 1825 (5 years instead of Saudi's 7)audit_schema: ANPD_FORMATinference_routing.sensitive: SAO_PAULO_LOCALauthorization.threshold: 0.80 (Brazil stricter than Saudi's 0.75)national_id_pattern to CPF formatDay 7–9: Infrastructure setupProvision São Paulo region:Llama-3 70B on H100 cluster (local inference)S3-equivalent WORM storage (5-year retention)Redis Shadow State sidecarDay 10: Deploy# Deploy sidecar with Brazil configkubectl apply -f sidecar-br.yaml# Agent code unchanged - zero deployment# Infrastructure routes to São Paulo for sensitive dataDay 11: Legal sign-offANPD compliance validated. Zero agent code changes.Total engineering effort: 40 hours Agent code modified: 0 lines New jurisdiction added: YesThe Economics: Why Portability CompoundsTraditional hardcoded approach:30 months to 5 markets. $2.4M spent.Sidecar approach:9 months to 5 markets. $640K spent.Savings: $1.76M and 21 months.By Market #5, you’re deploying new regions while competitors are still building Market #2.Handling Regulatory Updates: The SDAIA Voice Print CaseJune 2025. SDAIA updates Category 1 definition to include biometric voice prints.Without sidecar:Engineering team opens agent code. Finds all Category 1 checks. Updates logic across 23 files. Tests. Deploys. Hopes they caught every edge case.Timeline: 2–3 weeks Risk: High (logic scattered across codebase) Rollback: Painful (code entangled with other features)With sidecar:DevOps updates SA.yaml:data_classification: classifiers: biometric_fields: - "fingerprint" - "iris_scan" - "voice_print" # ADDED - "facial_image"Deploy new config. Agent code untouched.Timeline: 2 hours Risk: Low (isolated config change) Rollback: Instant (git revert)We’ve handled 6 regulatory updates across 8 jurisdictions in 12 months. Zero production incidents.Common Implementation MistakesMistake #1: Leaky abstractionAgent still has jurisdiction awareness:# WRONGdef process(self, request): result = self.agent.decide(request) if request['jurisdiction'] == 'SA': if result['confidence'] result['needs_approval'] = True return resultFix: Agent should never reference jurisdiction. Sidecar handles authorization thresholds.Mistake #2: Config in codeHardcoded config loading:# WRONGif jurisdiction == 'SA': config = SAUDI_CONFIGelif jurisdiction == 'BR': config = BRAZIL_CONFIGFix: Dynamic loading from file system. Adding new jurisdiction requires zero code changes.Mistake #3: Sidecar bloatPutting everything in the sidecar:# WRONG: Sidecar doing too muchclass Sidecar: def process(self, data): self.validate() self.route() self.call_agent() self.format() self.notify_users() self.update_analytics() self.trigger_webhooks() # 1000 more linesFix: Sidecar does ONE thing: Enforce jurisdiction compliance. Nothing else.Performance: The Latency TaxSidecar adds overhead. Measure it.Riyadh deployment (Saudi Arabia):Without sidecar: 180ms agent inferenceWith sidecar: 184ms total (4ms overhead)Overhead: 2.2%São Paulo deployment (Brazil):Without sidecar: 210ms agent inferenceWith sidecar: 215ms total (5ms overhead)Overhead: 2.4%The overhead is negligible. PII masking, classification, and routing add If sidecar overhead exceeds 10ms, you’ve built it wrong. Optimize the classification logic.The Real Moat: Portability at ScaleIn 2026, the moat isn’t the model. LLMs are commoditized. Every team has access to GPT-4, Claude, Llama.The moat is geopolitical velocity.Can you deploy in a new country in 2 weeks while competitors need 6 months?Can you handle regulatory updates in 2 hours instead of 2 weeks?Can you scale to 10 jurisdictions without 10x engineering overhead?If your compliance is code, you can’t. If your compliance is config, you can.Build the sidecar. Make expansion a YAML file.Piyoosh Rai builds AI infrastructure where geographic expansion doesn’t require rewriting your stack. From jurisdictional sidecars in Riyadh to config-driven compliance in São Paulo, he architects systems where adding a new country is a YAML file, not a 6-month rebuild.Currently helping companies escape jurisdictional lock-in at The Algorithm.Questions on geopolitical portability? Reach out at piyoosh.rai@the-algo.com.The Air-Gapped Chronicles: The Passport Stack was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.