import type { Express, Request, Response, NextFunction } from "express";
import { createServer, type Server, type IncomingMessage } from "http";
import { WebSocketServer, WebSocket } from "ws";
import { storage } from "./storage";
import { db, withBypassRls, ddlPool, buildAppConnectionString, withTenantRls, auditDb, appPool } from "./db";
import { withTenantDbPhase, runWithTenantContext } from "./lib/tenant-context";
import { ingestSignalSchema, computeSourceSignalHash } from "./lib/fincrime/ingestion";
import {
  requireMachineKey,
  issueMachineKey,
  revokeMachineKey,
  listMachineKeys,
  machineKeyAuthConfigured,
} from "./lib/fincrime/machine-keys";
import { machineIngestRateLimiter, machineIngestIpRateLimiter, getClientIp } from "./lib/rate-limiter";
import {
  assignCaseSchema,
  startInvestigationSchema,
  addEvidenceSchema,
  escalateMlcoSchema,
  queueSchema,
} from "./lib/fincrime/workflow";
import {
  openIncidentSchema,
  openFromAlertSchema,
  transitionSchema,
  assignIncidentSchema,
  irQueueSchema,
} from "./lib/security-ir/workflow";
import {
  rebuildBaselinesForTenant,
  tenantUserIds,
  MIN_BASELINE_SAMPLES,
  DEFAULT_BASELINE_WINDOW_DAYS,
} from "./lib/ueba/baseline";
import { runDetection, HIGH_CONFIDENCE_THRESHOLD } from "./lib/ueba/rules";
import {
  prepareStrSchema,
  finalizeStrSchema,
  StrGuardError,
} from "./lib/fincrime/str-workflow";
import {
  renderGoamlFormB,
  getGoamlDeploymentConfig,
} from "./lib/fincrime/goaml-formb";
import { serializeGoamlXml } from "./lib/fincrime/goaml-xml-serializer";
import { getKeyManagementStatus, rotateKek, selfTestKeyManagement } from "./lib/key-management/envelope";
import { sql, desc, and, eq, ne, isNull } from "drizzle-orm";
import { loginSchema, insertThreatEventSchema, insertAuditLogSchema, auditLogs, apiKeys, users, ssoConfigs, type KycCustomer, type KYCStatus, type InsertKycScreeningResult } from "@shared/schema";
import { userTenantRoles } from "@shared/schema-rbac";
import {
  isSyntheticKycCustomer,
  isSyntheticKycDecision,
  toExaminerCustomerRef,
  toExaminerDecisionDTO,
  toExaminerApprovalDTO,
} from "./lib/kyc/examiner-evidence";
import { verifyDecisionIntegrity } from "./lib/kyc/decision-integrity";
import { verifyFincrimeCaseIntegrity } from "./lib/fincrime/case-integrity";
import { toRegulatorCaseRefDTO, toRegulatorStrStatusDTO } from "./lib/fincrime/regulator-surface";
import { z } from "zod";
import { randomBytes, createHash, randomUUID } from "crypto";
import path from "path";
import fs from "fs";
import bcrypt from "bcryptjs";
import session from "express-session";
import pgSession from "connect-pg-simple";
import pg from "pg";
import helmet from "helmet";
import { AegisException, createErrorResponse } from "./lib/error-codes";
import { BUILD_INFO } from "./lib/build-info";
import { logger, authLogger, threatLogger, webhookLogger, apiLogger } from "./lib/logger";
import { requestTracer, requestLogger, globalErrorHandler, asyncHandler, notFoundHandler, redactedError } from "./lib/error-handler";
import { aiCircuitBreaker, cbsCircuitBreaker } from "./lib/circuit-breaker";
import { idempotencyMiddleware, getIdempotencyStats } from "./lib/idempotency";
import { getChainStats, validateChain } from "./lib/forensic-chain";
import { getDriftStats, initializeDriftDetection } from "./lib/drift-detection";
import { getHoneypotStats, initializeHoneypots, getGhostAccounts } from "./lib/honeypot";
import { threatIntelligence } from "./lib/threat-intelligence";
import { soarPlaybook } from "./lib/soar-playbook";
import { apiGateway } from "./lib/api-gateway";
import { complianceDashboard } from "./lib/compliance-dashboard";
import { privilegedAccess } from "./lib/privileged-access";
import { coreBankingGateway } from "./lib/core-banking-gateway";
import { demoMode } from "./lib/demo-mode";
import { sovereigntyMonitor, bouCompliance, ussdSecurity, a2aPaymentSecurity, bereaKuGuard, sovereignEdge, telcoGateway, sovereigntyLock, offlineSyncProtocol, sovereignCertification } from "./lib/uganda-compliance";
import { ASSURANCE_DISCLAIMER as UGANDA_CERT_DISCLAIMER } from "./lib/containment-notice";
// commercialSaas import removed 2026-07-03 (sovereign-per-bank: commercial-saas.ts deleted)
import { alertingThresholds, notificationPipeline, finOpsController } from "./lib/enterprise-alerting";
import { midnightMirrorSimulation } from "./lib/attack-simulation";
import { getIdentityVerificationAdapter } from "./lib/kyc/identity-verification-adapter";
import { getPepScreeningAdapter } from "./lib/kyc/pep-screening-adapter";
import { getSanctionsScreeningAdapter } from "./lib/kyc/sanctions-screening-adapter";
import { getOfacSdnStatus, OFAC_SDN_SOURCE } from "./lib/kyc/ofac-sdn-ingestion";
import { assertScreeningResultInvariant } from "./lib/kyc/screening-types";
import {
  collectFreshSignals,
  deriveRiskTier,
  decide,
  buildSignalsSnapshot,
  computeSignalsHash,
  coerceRiskTier,
  FinalizeGuardError,
  type KycSubjectForDecision,
} from "./lib/kyc/decision-engine";
import * as safetyRails from "./lib/safety-rails";
import * as hsmIntegration from "./lib/hsm-integration";
import * as regulatorGateway from "./lib/regulator-gateway";
import * as aiBom from "./lib/ai-bom";
// tenantBilling import removed 2026-07-03 (sovereign-per-bank: tenant-billing.ts deleted)
import * as sovereignReadiness from "./lib/sovereign-readiness";
import { getPQCEngine, performPQCHandshake } from "./pqcEngine";
import { getChaosEngine, getLoadTester, getSecurityAuditor } from "./chaosEngine";
import { registerChatRoutes } from "./replit_integrations/chat";
import { registerFIDO2Routes } from "./lib/fido2-passkey";
import { registerJITAccessRoutes } from "./lib/jit-access";
import { registerMachineIdentityRoutes } from "./lib/machine-identity";
import { registerServiceNowRoutes } from "./lib/servicenow";
import { registerPagerDutyRoutes } from "./lib/pagerduty";
import { registerScimRoutes, registerScimAdminRoutes } from "./lib/scim";
import { registerDsarRoutes } from "./lib/dsar-workflow";
import { registerWave5Routes } from "./lib/wave5-routes";
import { registerFinalRoutes } from "./lib/wave-final-routes";
import { registerThreatForecastRoutes } from "./lib/threat-forecast-routes";
import { buildRequireRole, resolveEffectiveRole, requirePlatformAdmin, requirePlatformRole } from "./lib/rbac-middleware";
import { registerRbacRoutes } from "./lib/rbac-routes";
import { getSyncHistory } from "./lib/threat-intel-sync";
import { getGlobalHSM, initializeGlobalHSM } from "./hsmEnclave";
import { getGlobalSLAMonitor } from "./slaMonitor";
import {
  encryptPii,
  decryptPii,
  isEncrypted,
  computeLookupHash,
  type PiiContext,
} from "./lib/pii-encryption";
import { getGlobalDPEngine } from "./differentialPrivacy";

const PgStore = pgSession(session);

// Session policy (auth-hardening tranche 3, security-first). Absolute = hard ceiling from login
// (also the cookie maxAge / session-store TTL). Idle = rolling inactivity window, SERVER-enforced
// (tracked server-side via lastActivityAt — never trust a client cookie for expiry). Both are
// env-overridable. Defaults 4h / 10min map to OWASP financial-app guidance (absolute 4-8h, tight idle).
const SESSION_ABSOLUTE_MS = Math.max(60_000, parseInt(process.env.SESSION_ABSOLUTE_TIMEOUT_MS || String(4 * 60 * 60 * 1000), 10) || 4 * 60 * 60 * 1000);
const SESSION_IDLE_MS = Math.max(60_000, parseInt(process.env.SESSION_IDLE_TIMEOUT_MS || String(10 * 60 * 1000), 10) || 10 * 60 * 1000);
// Throttle lastActivityAt writes so the session store isn't written on every request (bump at most
// once per this interval). Kept well under the idle window so an active user is never expired early.
const SESSION_IDLE_WRITE_THROTTLE_MS = 60 * 1000;

import { BCRYPT_ROUNDS } from "./lib/bcrypt-config";

async function hashPasswordAsync(password: string): Promise<string> {
  return bcrypt.hash(password, BCRYPT_ROUNDS);
}

async function verifyPassword(password: string, hash: string): Promise<{ valid: boolean; needsRehash: boolean }> {
  if (hash.length === 64 && !hash.startsWith("$2")) {
    const legacyHash = createHash("sha256").update(password).digest("hex");
    if (legacyHash === hash) {
      return { valid: true, needsRehash: true };
    }
    return { valid: false, needsRehash: false };
  }
  const valid = await bcrypt.compare(password, hash);
  return { valid, needsRehash: false };
}

function hashPassword(password: string): string {
  return bcrypt.hashSync(password, BCRYPT_ROUNDS);
}

// Generate random token
function generateToken(): string {
  return randomBytes(32).toString("hex");
}

// Get client IP address safely
// getClientIp is imported from ./lib/rate-limiter — the single trust-proxy-resolved resolver.
// The former local definition here read X-Forwarded-For directly and took the LEFTMOST entry,
// ignoring the trust-proxy boundary, so a client could set the value recorded in audit logs,
// session loginIp, and login-anomaly scoring (and evade scoring via X-Forwarded-For: 127.0.0.1).
// Removed 2026-07-24; every consumer now inherits the resolver, which honours TRUST_PROXY_HOPS.

// Resolve a seed-user password with dual-environment discipline (updated
// 2026-05-28 by FU-042 leak fix; original surface dated 2026-05-21):
//
//   1. If `${envVar}` is set and non-blank in process.env, use it.
//   2. Else if NODE_ENV === "production": THROW (fail-closed). The previous
//      "generate random + console.log the value with CAPTURE-NOW banner"
//      branch was removed because the cleartext value landed in deployment-
//      log retention indefinitely (Rule 1 leak, 2026-05-28 incident: three
//      seed-user passwords captured in prod deploy log at 13:16 UTC). The
//      diagnosis surfaces earlier at SECRET-BOOT-GUARD time — the three
//      AEGIS_*_PASSWORD env vars are now in secret-boot-guard's REQUIRED
//      list with prodOnly:true — so this throw should be unreachable in
//      practice. It exists as defensive belt-and-braces against the boot-
//      guard REQUIRED list and the seedDemoUsers caller list drifting out
//      of sync; if it ever fires, that's the bug to fix.
//   3. Else (development): fall back to the historical demo password to
//      preserve the existing dev-credentials workflow (carry-list item
//      "Dev login credentials" — operator currently relies on these for
//      the Replit dev preview). Dev never reads the env var; this is why
//      the boot-guard entries are gated prodOnly:true rather than always-on.
//
// Production deployments (Docker, bank on-prem, Replit production) require
// all three AEGIS_*_PASSWORD secrets set before first boot or the boot-guard
// refuses to start. Replit dev preview is unchanged.
function resolveSeedPassword(envVar: string, devFallback: string, label: string): string {
  const fromEnv = process.env[envVar]?.trim();
  if (fromEnv && fromEnv.length > 0) {
    return fromEnv;
  }
  // FU-042 hygiene fix (2026-05-28): the previous prod-time generate-and-log
  // branch wrote the cleartext password to stdout where deployment-log
  // retention captured it indefinitely (Rule 1 leak surface, incident
  // 2026-05-28: admin/ciso/auditor passwords logged to prod deploy log at
  // 13:16 UTC). Fix is fail-closed: in production, the env var MUST be set.
  // secret-boot-guard.ts now carries AEGIS_ADMIN_PASSWORD /
  // AEGIS_CISO_PASSWORD / AEGIS_AUDITOR_PASSWORD in its REQUIRED list so the
  // diagnosis surfaces uniformly with the other 9 secrets BEFORE this call
  // site is reached. This throw is defensive belt-and-braces — if it ever
  // fires, the boot-guard REQUIRED list and the seedDemoUsers caller list
  // have drifted out of sync and need re-alignment.
  if (process.env.NODE_ENV === "production") {
    throw new Error(
      `[SEED-USER] ${envVar} is required in production for seed user "${label}". ` +
      `secret-boot-guard should have caught this earlier; if you are seeing this ` +
      `error here, the guard's REQUIRED list is out of sync with the seedDemoUsers ` +
      `caller list. Set ${envVar} in the environment and restart.`
    );
  }
  return devFallback;
}

// Helper for seedDemoUsers: ensure a seed user exists, AND if an operator has
// explicitly set the corresponding AEGIS_<X>_PASSWORD env var and the stored
// hash does not match, refresh the hash in place.
//
// Refresh-on-mismatch policy (added 2026-05-24 to close P4.1 systemic gap):
// matches the regulator-seed.ts precedent — env var is the authoritative
// source of seed-user passwords WHEN explicitly set. We never refresh on the
// dev fallback alone, because the existing hash may be the operator's earlier
// choice (UPDATE or direct DB manipulation) that we should not overwrite
// blindly. The pattern matters because before this helper existed, a seed
// user whose env-set password was rotated externally became un-loginable:
// `seedDemoUsers` skipped them (user already exists), and the stored hash
// was stuck at whatever value the prior boot wrote.
async function ensureSeedUser(
  username: string,
  envVar: string,
  devFallback: string,
  role: "admin" | "risk_manager" | "auditor",
  fullName: string,
  department: string,
): Promise<void> {
  const password = resolveSeedPassword(envVar, devFallback, username);
  const existing = await storage.getUserByUsername(username);
  if (!existing) {
    await storage.createUser({
      username,
      password: hashPassword(password),
      role,
      fullName,
      department,
      isActive: true,
    });
    return;
  }
  // Refresh hash ONLY when env var is explicitly set and stored hash diverges.
  // Whitespace-only / empty env values are not "explicitly set" — guards
  // against an accidentally blank secret in CI/secret-manager state silently
  // rewriting the stored hash to a bcrypt of an empty string.
  const envRaw = process.env[envVar];
  const envSet = typeof envRaw === "string" && envRaw.trim().length > 0;
  if (!envSet) return;
  const matches = await bcrypt.compare(password, existing.password);
  if (!matches) {
    await storage.updateUserPassword(existing.id, hashPassword(password));
    // Audit the silent password refresh — Rule 9 architect-review finding
    // (2026-05-24 MEDIUM): privileged seed-user password rewrites triggered
    // by env-var rotation are operator-meaningful state changes and belong
    // in the audit trail. We log username + envVar name + role only; the
    // actual password value is never written (Rule 1 credential discipline).
    await storage.createAuditLog({
      action: "SEED_USER_PASSWORD_REFRESHED",
      resource: `Authentication System / seed user "${username}"`,
      details: `Boot-time seed refresh: stored hash for "${username}" (role=${role}) diverged from ${envVar} env value; hash rewritten in place.`,
      ipAddress: "system:seed",
    });
  }
}

// Seed demo users if they don't exist; refresh hash on env-var mismatch.
async function seedDemoUsers() {
  await ensureSeedUser(
    "admin",
    "AEGIS_ADMIN_PASSWORD",
    "admin123",
    "admin",
    "System Administrator",
    "IT Security",
  );
  await ensureSeedUser(
    "ciso",
    "AEGIS_CISO_PASSWORD",
    "ciso123",
    "risk_manager",
    "Chief Information Security Officer",
    "Risk Management",
  );
  await ensureSeedUser(
    "auditor",
    "AEGIS_AUDITOR_PASSWORD",
    "auditor123",
    "auditor",
    "Compliance Auditor",
    "Internal Audit",
  );
  // Demo/sandbox-prep engineer accounts (added 2026-06-10 by operator request:
  // M. Okot + Okello). Role: auditor (read-only). Originally proposed as
  // risk_manager ("operate, no admin"); the operator confirmed auditor
  // (least-privilege) on 2026-06-10 after advisor review — these engineers
  // prepare and present the demo (view-only) and do not need to operate
  // security features. auditor (ROLE_HIERARCHY level 1) is denied every
  // requireRole("admin") route AND every risk_manager-gated operational route.
  // Same env-var + prodOnly boot-guard discipline as the three RBAC personas
  // above; tenant binding (aegis-sovereign, auditor) lands via
  // SOVEREIGN_USER_ROLES in pilot-readiness-extras.ts.
  await ensureSeedUser(
    "m.okot",
    "ENGINEER_OKOT_PASSWORD",
    "okot-dev-2026",
    "auditor",
    "M. Okot",
    "Engineering",
  );
  await ensureSeedUser(
    "okello",
    "ENGINEER_OKELLO_PASSWORD",
    "okello-dev-2026",
    "auditor",
    "Okello",
    "Engineering",
  );
  // Permanent second senior — MLCO (Money Laundering Control Officer) checker
  // (added 2026-06-15 by operator request). Role: risk_manager — the
  // least-privilege role that satisfies the STR finalize guard
  // requireRole("admin", "risk_manager") WITHOUT granting full platform admin.
  // This is the genuine second senior, distinct from "admin" (the maker), that
  // two-eyes STR finalization requires: the maker prepares an STR, a DIFFERENT
  // senior (this MLCO) checks and finalizes it. Mirrors the ciso→risk_manager
  // persona above (global role + tenant binding both risk_manager). Same env-var +
  // prodOnly boot-guard discipline; the aegis-sovereign tenant binding
  // (risk_manager) lands via SOVEREIGN_USER_ROLES in pilot-readiness-extras.ts.
  await ensureSeedUser(
    "mlco",
    "MLCO_PASSWORD",
    "mlco-dev-2026-checker",
    "risk_manager",
    "Money Laundering Control Officer",
    "Financial Crime Compliance",
  );
}

// seedDemoThreats() and seedDemoAuditLogs() REMOVED 2026-06-30 (synthetic-as-real Pass #1).
// They inserted unlabeled fabricated threat_events / audit_logs rows (STAF_* maker IDs,
// 192.168.x.x IPs, canned descriptions) on every fresh boot, served as REAL on the tenant
// dashboard + audit viewer. Their call sites in registerRoutes were removed alongside this.
// seedDemoUsers() is intentionally retained — it seeds the REAL required RBAC/boot-guard
// accounts, not fabricated data. (Existing fabricated rows on the live volume are scrubbed
// separately under the posture-gated Pass #2 data scrub — see SYNTHETIC_DATA_AUDIT.md.)

// ─── T003 Option A: RLS diagnostic — concurrency lock ───────────────────────
// Module-level flag; prevents concurrent diagnostic runs. Reset in outer
// finally of the handler. Rule 9 architect PASS cycle 2 2026-06-04.
let rlsDiagnosticRunning = false;

// ─── Path A encryption probe — concurrency lock ─────────────────────────────
// Module-level flag; prevents concurrent probe runs. Reset in outer finally.
// Rule 9 architect PASS 2026-06-07 (v1.1-RATIFIED).
let encryptionProbeRunning = false;

// T004b migration endpoint removed per D-LIFECYCLE-1 (prod execution confirmed
// 2026-06-07: migrated=22, skipped=0, nullTenantSkipped=0, gate=CLEAN; idempotency
// re-run all-zeros). Route + module-level state removed in same session.

export async function registerRoutes(
  httpServer: Server,
  app: Express
): Promise<Server> {
  const isProduction = process.env.NODE_ENV === "production";

  // CRITICAL: trust-proxy hop count governs how `req.ip` (the login
  // rate-limiter's per-IP bucket) AND `req.secure` (whether express-session
  // will set a `secure: true` cookie) are resolved from X-Forwarded-For.
  // Configurable via TRUST_PROXY_HOPS (default 0 — FAIL-CLOSED, changed 2026-07-24;
  // see resolveTrustProxyHops):
  //   • hops === 0 (DEFAULT) — trust proxy OFF: req.ip = the raw socket peer and
  //     X-Forwarded-For is IGNORED, making the per-IP login limiter AND audit
  //     attribution spoof-proof. Correct for DIRECT-EXPOSURE deployments (no proxy
  //     in front). Behind a TLS terminator this is a LOUD misconfiguration, not a
  //     silent one: req.secure is false over HTTPS so the Secure session cookie is
  //     never set and every request 401s — that is the signal to declare the hops.
  //   • hops >= 1 — trust the rightmost N entries as proxies; req.ip = the address
  //     N hops in front. A proxied deployment MUST set this (1 = a single TLS
  //     terminator / the Replit Reserved-VM topology), which also restores
  //     req.secure===true over HTTPS so the Secure cookie is set; also what the
  //     dev proof-harness relies on (one X-Forwarded-For IP per synthetic actor
  //     through the trusted hop).
  // Invalid / out-of-range values fall back to the fail-closed default 0. See §3.5.
  // Must run BEFORE the session middleware below.
  const { resolveTrustProxyHops } = await import("./lib/rate-limiter");
  const trustProxyHops = resolveTrustProxyHops();
  app.set("trust proxy", trustProxyHops === 0 ? false : trustProxyHops);
  console.log(
    `[trust-proxy] hops=${trustProxyHops} — ${
      trustProxyHops === 0
        ? "proxy trust OFF: req.ip = socket peer, X-Forwarded-For IGNORED (spoof-proof, direct-exposure only)"
        : `trusting ${trustProxyHops} proxy hop(s): req.ip resolved from X-Forwarded-For`
    }`,
  );

  // Dynamic KYT configuration loader (2026-05-23). Loads config/kyt-rules.json
  // (or KYT_CONFIG_PATH override), validates against the strict Zod schema,
  // falls back to embedded defaults if absent/invalid (with a warning), and
  // starts a 30s mtime+hash poller that auto-reloads on file change and
  // emits KYT_CONFIG_RELOADED audit events. Called before any KYT analysis
  // path so the first /api/kyt/analyze call sees the file-backed config
  // (not the embedded defaults).
  try {
    const { loadKytConfig, startKytConfigPoller } = await import("./lib/kyt-config-loader");
    await loadKytConfig();
    startKytConfigPoller(30_000);
  } catch (err) {
    // Loader failure must not block server boot — KYT engine falls back to
    // embedded defaults which mirror the previously-hardcoded values.
    // eslint-disable-next-line no-console
    console.warn("[kyt-config] loader init failed; engine using embedded defaults:", (err as Error).message);
  }

  app.use(
    helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          scriptSrc: isProduction
            ? ["'self'"]
            : ["'self'", "'unsafe-inline'", "'unsafe-eval'"],
          styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
          fontSrc: ["'self'", "https://fonts.gstatic.com"],
          imgSrc: ["'self'", "data:", "blob:"],
          connectSrc: ["'self'", "ws:", "wss:"],
          frameSrc: ["'none'"],
          objectSrc: ["'none'"],
          baseUri: ["'self'"],
          formAction: ["'self'"],
          upgradeInsecureRequests: isProduction ? [] : null,
        },
      },
      crossOriginEmbedderPolicy: false,
      crossOriginResourcePolicy: { policy: "same-origin" },
      referrerPolicy: { policy: "strict-origin-when-cross-origin" },
      hsts: isProduction ? { maxAge: 31536000, includeSubDomains: true, preload: true } : false,
    })
  );

  const { createApiMetricsMiddleware } = await import("./lib/api-analytics");
  app.use(createApiMetricsMiddleware());

  const { apiRateLimiter } = await import("./lib/rate-limiter");
  app.use("/api", (req, res, next) => {
    // Machine ingestion is EXEMPTED from the shared per-IP `api` bucket so that
    // distinct machine keys behind one egress IP get genuine per-key isolation
    // (the route carries its own per-IP flood ceiling `machineIngestIpRateLimiter`
    // plus the per-key `machineIngestRateLimiter`). req.path here is relative to
    // the "/api" mount, hence "/fincrime/ingest/machine".
    if (req.method === "POST" && req.path === "/fincrime/ingest/machine") {
      return next();
    }
    return apiRateLimiter(req, res, next);
  });

  // Defence-in-depth: source-level fail-closed on missing SESSION_SECRET.
  // The boot guard (server/lib/secret-boot-guard.ts) is the primary gate and
  // refuses startup if SESSION_SECRET is absent; this throw is the secondary
  // gate so that any code path that bypasses the boot guard (test harness,
  // partial init, future refactor) still cannot fall through to a literal
  // fallback secret. Audit reference: AUDIT-CYBER-2026-05-15 FIND-H2.
  const sessionSecret = process.env.SESSION_SECRET;
  if (!sessionSecret) {
    throw new Error(
      "FATAL: SESSION_SECRET is not set. The secret-boot-guard should have refused startup before this point — investigate server/lib/secret-boot-guard.ts."
    );
  }

  // CO-016 (Carve-Outs Register v1.1, closed 2026-05-18): the session
  // middleware is extracted to a named const so the WebSocket verifyClient
  // handler (below, where WSS is created) can reuse the exact same
  // middleware instance to validate the connect.sid cookie at the HTTP
  // upgrade boundary — closing FIND-F1 (auth-at-upgrade rather than
  // auth-as-first-message). Side effect: removes the duplicate inline
  // session() block that previously lived in the WS connection handler
  // and carried a literal SESSION_SECRET fallback string (the second,
  // undisposed occurrence of FIND-H2 from AUDIT-CYBER-2026-05-15).
  // Cookie.secure resolution (2026-05-21, Phase 1 Docker packaging):
  // Default is `isProduction` — Replit prod (HTTPS via Reserved-VM proxy,
  // trust proxy=1) and any bank deployment behind an nginx/F5 TLS terminator
  // get Secure cookies as before. The COOKIE_SECURE env override exists for
  // the on-prem Docker case where the operator runs the platform on plain
  // HTTP localhost for a demo or single-machine pilot — `Secure` cookies
  // are silently dropped over HTTP and every API call comes back 401.
  // Setting COOKIE_SECURE=false in .env (only sensible for localhost-only
  // plain-HTTP deployments) makes the cookie non-Secure so the session
  // round-trips. Production deployments behind a real TLS terminator must
  // NOT set this; leave unset for default Secure behaviour.
  const cookieSecureOverride = process.env.COOKIE_SECURE?.trim().toLowerCase();
  const cookieSecure = cookieSecureOverride === "false" ? false
    : cookieSecureOverride === "true" ? true
    : isProduction;

  // Defence-in-depth boot guard (added 2026-05-22 after architect review of
  // FU-005-adjacent Phase 1 Docker packaging work): refuse to start in
  // production with a non-Secure session cookie unless the operator has
  // *also* set AEGIS_ALLOW_INSECURE_COOKIE=true. This closes the
  // template-default-drift path — a bank deployment that copies .env.template
  // and accidentally leaves COOKIE_SECURE=false uncommented (or sets it for
  // a localhost test and forgets to remove it before going live) would
  // otherwise silently run production with browser-droppable session cookies.
  // Pairs with the secret-boot-guard pattern at server/lib/secret-boot-guard.ts.
  if (isProduction && cookieSecure === false) {
    const allowInsecure = process.env.AEGIS_ALLOW_INSECURE_COOKIE?.trim().toLowerCase() === "true";
    if (!allowInsecure) {
      throw new Error(
        "FATAL: COOKIE_SECURE=false in production without AEGIS_ALLOW_INSECURE_COOKIE=true. " +
        "Non-Secure session cookies in production are a security regression and only acceptable " +
        "for plain-HTTP localhost demos. If this is a localhost demo, also set " +
        "AEGIS_ALLOW_INSECURE_COOKIE=true in .env to confirm intent. If this is a real " +
        "deployment, remove COOKIE_SECURE=false and put a TLS terminator in front of the app."
      );
    }
  }
  const sessionMiddleware = session({
    secret: sessionSecret,
    resave: false,
    saveUninitialized: false,
    store: new PgStore({
      conString: process.env.DATABASE_URL,
      tableName: "session",
      createTableIfMissing: true,
      pruneSessionInterval: 60,
    }),
    cookie: {
      secure: cookieSecure,
      httpOnly: true,
      sameSite: "lax",
      maxAge: SESSION_ABSOLUTE_MS, // cookie/store TTL = the absolute cap; idle is enforced server-side below
    },
  });
  app.use(sessionMiddleware);

  // Idle + absolute session-timeout enforcement (auth-hardening tranche 3). Runs on EVERY /api request,
  // so it is FAIL-OPEN and cheap: any error lets the request through (logged, never wrongly expiring a
  // session or blocking a request). Server-tracked (lastActivityAt / loginAt), not client-cookie.
  //   - Absolute: now - loginAt > SESSION_ABSOLUTE_MS  ⇒ expire (hard ceiling from login).
  //   - Idle:     now - lastActivityAt > SESSION_IDLE_MS ⇒ expire (rolling inactivity window).
  //   - Otherwise slide the idle window (throttled write).
  app.use("/api", (req: Request, res: Response, next: NextFunction) => {
    try {
      if (!req.session?.userId) return next();
      const now = Date.now();
      const loginAt = req.session.loginAt ?? now;
      if (now - loginAt > SESSION_ABSOLUTE_MS) {
        const uid = req.session.userId;
        return req.session.destroy(() => {
          authLogger.info("Session expired (absolute cap)", { metadata: { userId: uid, ageMs: now - loginAt } });
          res.status(401).json({ error: "session_expired_absolute", message: "Session reached its maximum lifetime. Please sign in again." });
        });
      }
      const last = req.session.lastActivityAt ?? loginAt;
      if (now - last > SESSION_IDLE_MS) {
        const uid = req.session.userId;
        return req.session.destroy(() => {
          authLogger.info("Session expired (idle timeout)", { metadata: { userId: uid, idleMs: now - last } });
          res.status(401).json({ error: "session_expired_idle", message: "Session expired due to inactivity. Please sign in again." });
        });
      }
      if (now - (req.session.lastActivityAt ?? 0) > SESSION_IDLE_WRITE_THROTTLE_MS) req.session.lastActivityAt = now;
      return next();
    } catch {
      return next(); // FAIL-OPEN: a timeout-check error must never block a request or wrongly log a user out.
    }
  });

  // FU-053 Deliverable 7 (2c): Global apiKeyAuth mount. Runs after session
  // middleware (so req.session is populated) and before tenantMiddleware (so
  // req.apiKeyAuth.tenantId is available as Source 3 for tenant resolution).
  // The aegis_ format gate inside apiKeyAuth means non-aegis_ Bearer tokens
  // skip the DB lookup and fall through cleanly to route-level auth.
  const { apiKeyAuth } = await import("./lib/api-key-auth");
  app.use("/api", apiKeyAuth);

  const { tenantMiddleware } = await import("./lib/tenant-middleware");
  app.use("/api", tenantMiddleware);

  // FU-005 amendment 3 (Task #2 — multi-server CSRF): the CSRF token is
  // now stored on the session itself (req.session.csrfToken), not in a
  // process-local Map. This works correctly across multiple app instances
  // because express-session is already pg-backed via connect-pg-simple, so
  // a token minted on server A is automatically available to server B on
  // the next request that carries the same connect.sid cookie. No new
  // schema, no new pool ops, no in-memory state. Token TTL is enforced via
  // req.session.csrfMintedAt + the same 2h window as before.
  //
  // FU-005: Named allowlist for paths that legitimately have no CSRF token at
  // request time. Two shapes:
  //   • CSRF_ALLOWLIST_EXACT — exact path match (no Express :params).
  //   • CSRF_ALLOWLIST_PREFIXES — startsWith match for routes that take params
  //     (e.g. /api/sso/callback/:configId). Order-sensitive only insofar as
  //     specificity matters; current entries are non-overlapping.
  //
  // x-api-key continues to bypass CSRF (operator CLI tools).
  // GET/HEAD/OPTIONS continue to bypass CSRF (method skip below).
  // /api/csrf-token itself is GET so it never reaches this check.
  //
  // Inclusion rule for any new entry: the endpoint must enforce its own
  // integrity (signature/HMAC, x-api-key, signed payload, rate limit) such
  // that CSRF is not its primary protection mechanism. Any addition here is a
  // security-relevant change and warrants a review.
  const CSRF_ALLOWLIST_EXACT = new Set<string>([
    "/api/auth/login",
    // Passkey (WebAuthn) login — pre-session like /api/auth/login (no ambient cookie credential yet).
    // Protected by the WebAuthn assertion (a CSRF attacker cannot forge a signed assertion) + loginRateLimiter.
    "/api/auth/passkey/login/options",
    "/api/auth/passkey/login/verify",
    // Public verifier and submission endpoints. Each enforces its own
    // integrity check (HMAC/signature) or accepts anonymous public input
    // that is rate-limited and audit-logged downstream.
    "/api/public/evidence/verify",
    "/api/public/attestation/verify",
    "/api/public/vdp/submit",
    "/api/public/ombudsman/complaint",
    "/api/pilot-readiness/verify-signature",
    "/api/regulator/verify-bundle",
    // M2M / webhook / sync surfaces. Called by telcos or remote services that
    // hold an x-api-key or sign their payloads — not browser flows.
    // (edge↔cloud /api/cloud/{heartbeat,sync} + root /heartbeat,/sync aliases were
    // REMOVED 2026-07-27 with the failover routes; their CSRF-exempt entries removed
    // here so a future /sync or /heartbeat route is not silently exempt.)
    "/api/ussd/callback",
    // Machine-API-key fincrime ingestion (AS/SOAR/2026/001). Satisfies the
    // inclusion rule above: it is NOT a browser flow and carries no ambient
    // cookie credential — it authenticates with a per-request `Authorization:
    // Bearer mk_...` machine key (requireMachineKey: sha256(salt+raw) lookup,
    // scoped, revocable, TTL'd) plus a per-key + per-IP rate limiter. A CSRF
    // attacker cannot forge the Bearer header, so CSRF is not its protection
    // mechanism. req.path here is the full path (csrfProtection is mounted
    // without a route prefix).
    "/api/fincrime/ingest/machine",
  ]);
  const CSRF_ALLOWLIST_PREFIXES: readonly string[] = [
    "/api/sso/callback/",  // IdP redirects back to us with a configId in the path
    "/api/sso/login/",     // user starts SSO before having any local session
    // Public bearer SCIM 2.0 surface (RFC 7644). NOT a browser flow: carries no
    // ambient cookie credential; authenticates solely via a per-request
    // Authorization: Bearer token (validateBearerToken) a CSRF attacker cannot
    // forge — so CSRF is not its protection mechanism, the bearer is. Mirrors the
    // /api/fincrime/ingest/machine exemption. Scoped to /scim/v2/* only; the
    // session-authed /api/integrations/scim/* admin routes keep CSRF (not matched).
    // INVARIANT: any future state-changing /scim/v2/* route MUST stay bearer-only.
    "/scim/v2/",
  ];
  const isCsrfExempt = (path: string): boolean => {
    if (CSRF_ALLOWLIST_EXACT.has(path)) return true;
    return CSRF_ALLOWLIST_PREFIXES.some((p) => path.startsWith(p));
  };

  app.get("/api/csrf-token", (req, res) => {
    const token = randomBytes(32).toString("hex");
    // FU-005 amendment 3: persist the token on the session itself. The
    // pg-backed session store guarantees this is visible to every app
    // instance reading the same connect.sid cookie. Mutating the session
    // also ensures express-session sends Set-Cookie even with
    // saveUninitialized:false, which is what makes anonymous browser flows
    // like /regulator-verify work end-to-end.
    req.session.csrfToken = token;
    req.session.csrfMintedAt = Date.now();
    res.json({ csrfToken: token });
  });

  const TOKEN_MAX_AGE_MS = 2 * 60 * 60 * 1000;

  const csrfProtection = (req: Request, res: Response, next: NextFunction) => {
    if (["GET", "HEAD", "OPTIONS"].includes(req.method)) {
      return next();
    }
    // VF-A2 fix: skip CSRF only for a *validated* API-key identity, not on raw
    // header presence. apiKeyAuth (mounted on /api before this middleware)
    // populates req.apiKeyAuth only after a successful aegis_-key validation.
    // Pre-fix this checked req.headers["x-api-key"] presence, so any junk
    // x-api-key value bypassed CSRF (and apiKeyAuth fell through unauthenticated).
    if (req.apiKeyAuth) {
      return next();
    }
    if (isCsrfExempt(req.path)) {
      return next();
    }
    const headerToken = req.headers["x-csrf-token"] as string | undefined;
    const sessionToken = req.session.csrfToken;
    const mintedAt = req.session.csrfMintedAt;
    // FU-005 fail-closed: a missing token on a state-changing, non-allowlisted
    // request is either a bug, a stale tab, or an attack. apiRequest on the
    // client always attaches x-csrf-token after first lazy-fetching one.
    if (!headerToken || !sessionToken || !mintedAt) {
      return res.status(403).json({ error: "CSRF_TOKEN_REQUIRED", message: "CSRF token required for state-changing requests" });
    }
    if (sessionToken !== headerToken) {
      return res.status(403).json({ error: "CSRF_VALIDATION_FAILED", message: "Invalid CSRF token" });
    }
    if (Date.now() - mintedAt > TOKEN_MAX_AGE_MS) {
      // Clear the expired token from the session so the next mint replaces it
      // cleanly (and so a stale token can't accidentally be re-used after the
      // window). The client's one-shot retry-on-403-CSRF will refetch.
      req.session.csrfToken = undefined;
      req.session.csrfMintedAt = undefined;
      return res.status(403).json({ error: "CSRF_TOKEN_EXPIRED", message: "CSRF token expired, please refresh" });
    }
    next();
  };

  app.use(csrfProtection);

  // CO-017 framing clarification (2026-05-23): this middleware strips ASCII
  // control characters (\x00-\x08, \x0B, \x0C, \x0E-\x1F) from string fields
  // in req.body. It is NOT HTML sanitisation — does not remove or escape
  // <script>, <img onerror=…>, javascript:-URLs, on*-attributes, or any other
  // HTML/JS payload. E1 (HTML output sanitisation) remains addressed by React's
  // default JSX escaping on the client; CO-017 carve-out remains correctly
  // dormant against the first rich-text endpoint introduction. Renamed from
  // `inputSanitizer` to make the actual scope unambiguous on a grep or
  // function-name read.
  const controlCharStripper = (req: Request, _res: Response, next: NextFunction) => {
    if (req.body && typeof req.body === "object") {
      const stripControlChars = (val: unknown): unknown => {
        if (typeof val === "string") {
          return val.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
        }
        if (Array.isArray(val)) return val.map(stripControlChars);
        if (val && typeof val === "object") {
          const stripped: Record<string, unknown> = {};
          for (const [k, v] of Object.entries(val as Record<string, unknown>)) {
            stripped[k] = stripControlChars(v);
          }
          return stripped;
        }
        return val;
      };
      req.body = stripControlChars(req.body);
    }
    next();
  };
  app.use(controlCharStripper);

  app.use(requestTracer);
  app.use(requestLogger);

  // Register AI chat routes
  registerChatRoutes(app);

  // Seed demo data
  await seedDemoUsers();

  // Boot-seed the rate-limit + geo default POLICY CATALOGS for the sovereign tenant. seedDefaults is
  // idempotent (no-ops if rows already exist) and runs under a real tenant context so the RLS
  // WITH CHECK passes. These are CONFIG CATALOGS, not live enforcement (the live API rate-limiter
  // does not read the rate-limit table; geo policies are evaluated on-demand only) — the UI labels
  // that honestly. Wrapped so a seeding failure can never block boot.
  try {
    const { runWithTenantContext } = await import("./lib/tenant-context");
    await runWithTenantContext("aegis-sovereign", async () => {
      const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
      const { geoFencing } = await import("./lib/geo-fencing");
      await rateLimitGovernance.seedDefaults("aegis-sovereign");
      await geoFencing.seedDefaults("aegis-sovereign");
    });
  } catch (e) {
    logger.warn("[boot] rate-limit/geo default policy-catalog seeding skipped", {
      metadata: { error: e instanceof Error ? e.message : String(e) },
    });
  }
  // seedDemoThreats() / seedDemoAuditLogs() REMOVED 2026-06-30 (synthetic-as-real Pass #1):
  // they inserted unlabeled fabricated threat + audit-log rows onto the tenant dashboard /
  // audit viewer on every fresh boot. A fresh deploy now starts with an HONEST EMPTY surface.
  // seedDemoUsers() is KEPT above — it seeds the REAL required RBAC / boot-guard accounts
  // (admin/ciso/auditor/m.okot/okello/mlco); removing it would break login.

  logger.info("AEGIS CYBER services initialized", {
    metadata: { version: "1.0.0", environment: process.env.NODE_ENV || "development" }
  });

  // Start SLA monitoring for demo-ready operation
  const slaLogger = logger.child('sla');
  const tierBLogger = logger.child('tier-b-scheduler');
  const slaMonitor = getGlobalSLAMonitor();
  slaMonitor.startMonitoring(5000); // 5-second intervals
  slaLogger.info('Commercial SLA monitoring started - 2026 Tier-1 thresholds active');

  // ===========================================================
  // TIER-B AUTO-DRILL SCHEDULER
  // ===========================================================
  // Runs the full Tier-A + Tier-B regulator-pilot drill suite on an interval
  // so the rolling 7-day window on /regulator/status stays populated without
  // a human remembering to click "run". Without this, the public status
  // page decays toward "no runs" and the regulator sees a less-green picture
  // than reality. Default interval: 60 minutes. Demo mode (or explicit
  // `TIER_B_AUTO_DRILL_ENABLED=false`) silences it. Each scheduled run
  // triggers a single `runAllTierBDrills` cycle plus a Tier-A cycle, both
  // tagged `triggeredBy: "scheduler"` so the receipts can be filtered out
  // of operator-attribution audits.
  const autoDrillEnabled = (process.env.TIER_B_AUTO_DRILL_ENABLED ?? 'true').toLowerCase() !== 'false';
  const autoDrillIntervalMs = Math.max(60_000, parseInt(process.env.TIER_B_AUTO_DRILL_INTERVAL_MS ?? '3600000', 10));
  if (autoDrillEnabled) {
    // In-flight guard: if a previous cycle is still running when the next
    // tick fires (e.g. someone added a slow drill, or the DB is degraded),
    // skip this tick rather than overlapping. Default cycle is ~500ms so
    // overlap is unlikely, but the guard removes a footgun for future
    // maintainers and keeps `triggeredBy:"scheduler"` receipts cleanly
    // bracketed (no concurrent inserts from the same logical run).
    let cycleInFlight = false;
    const runScheduledDrills = async () => {
      if (cycleInFlight) {
        tierBLogger.warn('previous cycle still running, skipping this tick');
        return;
      }
      cycleInFlight = true;
      try {
        const tA = await import("./lib/regulator-pilot-tier-a");
        const tB = await import("./lib/regulator-pilot-tier-b");
        const start = Date.now();
        try { await tA.runAllTierADrills({ triggeredBy: "scheduler" }); } catch (e: any) {
          tierBLogger.warn('tier-A run failed', { metadata: { error: String(e?.message || e) } });
        }
        try { await tB.runAllTierBDrills({ triggeredBy: "scheduler" }); } catch (e: any) {
          tierBLogger.warn('tier-B run failed', { metadata: { error: String(e?.message || e) } });
        }
        tierBLogger.info('cycle complete', { metadata: { durationMs: Date.now() - start } });
      } catch (e: any) {
        tierBLogger.warn('cycle aborted', { metadata: { error: String(e?.message || e) } });
      } finally {
        cycleInFlight = false;
      }
    };
    // First run after 60s (lets the server settle), then every interval.
    setTimeout(runScheduledDrills, 60_000);
    setInterval(runScheduledDrills, autoDrillIntervalMs);
    tierBLogger.info('auto-drill enabled', { metadata: { intervalMin: Math.round(autoDrillIntervalMs/60000) } });
  } else {
    // Mirror the chaos-sentinel demo-mode signals so we don't double-warn an
    // operator who has explicitly opted into demo-quiet mode.
    const isProd = process.env.NODE_ENV === 'production';
    const demoFlag = (process.env.DEMO_MODE || '').toLowerCase();
    const hasOperatorPwd = typeof process.env.REGULATOR_SEED_PASSWORD === 'string'
      && process.env.REGULATOR_SEED_PASSWORD.trim().length > 0;
    const demoMode =
      demoFlag === 'true' || demoFlag === '1' || demoFlag === 'yes' ||
      hasOperatorPwd ||
      (process.env.NODE_ENV !== 'production' &&
        (process.env.REGULATOR_DEMO_DEFAULT || '').toLowerCase() === 'true');
    if (isProd && !demoMode) {
      tierBLogger.warn(
        'WARNING: disabled in PRODUCTION without DEMO_MODE=true. The /regulator/status rolling 7-day window will decay. Re-enable by removing TIER_B_AUTO_DRILL_ENABLED=false or setting it to true.'
      );
    } else {
      tierBLogger.info('DISABLED via TIER_B_AUTO_DRILL_ENABLED=false (demo-quiet mode)');
    }
  }

  // Start Enterprise Services
  const { startReportScheduler } = await import("./lib/report-scheduler");
  startReportScheduler();
  logger.child('report-scheduler').info('Automated compliance report scheduler started');

  // G5: periodic compliance-check heartbeat — guarantees >=1 recorded run per tenant per day so the
  // control-status history becomes 30-day trend evidence, not point-in-time (see compliance-scheduler.ts).
  const { startComplianceScheduler } = await import("./lib/compliance-scheduler");
  startComplianceScheduler();

  const { startForwarder } = await import("./lib/siem-forwarder");
  startForwarder();

  const { startHealthChecks } = await import("./lib/dr-failover");
  startHealthChecks(60000);
  logger.child('dr-failover').info('Disaster recovery health checks started');

  // Auth middleware with structured error responses
  const requireAuth = (req: Request, res: Response, next: NextFunction) => {
    const traceId = (req as any).traceId;
    if (!req.session.userId) {
      authLogger.warn("Authentication required", { traceId });
      return res.status(401).json(createErrorResponse("AEGIS_ERR_004", { path: req.path }));
    }
    next();
  };

  const requireRole = buildRequireRole(requireAuth);

  // Concurrent-session cap (auth-hardening tranche 2): max simultaneous active sessions per user.
  // Env-overridable; default 3. Enforced at login (evict oldest beyond the cap).
  const MAX_CONCURRENT_SESSIONS = Math.max(1, parseInt(process.env.MAX_CONCURRENT_SESSIONS || "3", 10) || 3);

  // ============ HEALTH CHECK ============
  
  // Production-ready health endpoint for load balancers and monitoring
  app.get("/api/health", async (req, res) => {
    const startTime = Date.now();
    const checks: { component: string; status: "healthy" | "degraded" | "unhealthy"; latency?: number }[] = [];
    
    // Database health
    try {
      const dbStart = Date.now();
      await db.execute(sql`SELECT 1`);
      const dbLatency = Date.now() - dbStart;
      checks.push({ component: "database", status: dbLatency < 100 ? "healthy" : "degraded", latency: dbLatency });
    } catch (error) {
      checks.push({ component: "database", status: "unhealthy" });
    }
    
    // Session store health (in-memory store — no external dependency, so availability is a tautology)
    checks.push({ component: "session_store", status: "healthy" });

    // WebSocket: no runtime liveness probe is wired, so its health is NOT asserted here. Removed a
    // hardcoded status:"healthy" that was never measured (fabrication cleanup, Tier-3 2026-07-05).
    
    const overallStatus = checks.every(c => c.status === "healthy") 
      ? "healthy" 
      : checks.some(c => c.status === "unhealthy") 
        ? "unhealthy" 
        : "degraded";
    
    const responseTime = Date.now() - startTime;
    
    res.status(overallStatus === "unhealthy" ? 503 : 200).json({
      status: overallStatus,
      // FU-011 follow-through (2026-05-03): was hardcoded "4.0.1" — a known
      // stale string that was the original motivation for adding /api/version.
      // Now sourced from BUILD_INFO.packageVersion (real package.json value).
      // /api/version remains the canonical place to read full build metadata
      // (gitSha, gitCommittedAt, startedAt, nodeVersion, nodeEnv).
      version: BUILD_INFO.packageVersion,
      timestamp: new Date().toISOString(),
      responseTime: `${responseTime}ms`,
      checks,
      sla: {
        target: "<200ms",
        met: responseTime < 200
      }
    });
  });

  // Build / deploy version endpoint — answers "is prod on current main?" from outside.
  // Captured once at module-load by server/lib/build-info.ts; no I/O per request.
  // Added 2026-05-03 to remove the recurring readiness-check blind spot where
  // /api/health returned a hardcoded "4.0.1" with no way to size the prod-vs-main gap.
  app.get("/api/version", (_req, res) => {
    res.status(200).json(BUILD_INFO);
  });

  // Readiness probe for Kubernetes/load balancers
  app.get("/api/ready", async (req, res) => {
    try {
      await db.execute(sql`SELECT 1`);
      res.status(200).json({ ready: true });
    } catch (error) {
      res.status(503).json({ ready: false, reason: "database_unavailable" });
    }
  });

  // Liveness probe
  app.get("/api/live", (req, res) => {
    res.status(200).json({ alive: true, uptime: process.uptime() });
  });

  // ============ SECURITY FEATURES ============
  
  const { loginRateLimiter } = await import("./lib/rate-limiter");
  const { isAccountLocked, recordFailedLogin, recordSuccessfulLogin } = await import("./lib/account-lockout");
  const { validatePassword } = await import("./lib/password-policy");
  const { isTwoFactorEnabled, verifyTwoFactor } = await import("./lib/two-factor-auth");
  const { analyzeLoginAttempt, recordLogin } = await import("./lib/login-anomaly");

  // Shared session-establishment tail for ALL login factors (password, passkey). A passkey session
  // MUST be byte-for-byte identical to a password session — tenant RLS, the idle window (tranche 3),
  // and the concurrent-session cap (tranche 2) all depend on these exact fields — so both factors call
  // this one helper and can never drift. Factor-specific steps (password rehash, TOTP) stay in each
  // caller; this is only the post-verification tail: regenerate → fail-closed tenant → 6 fields → cap
  // → audit → session-manager. Returns ok, or a 403 the caller must send (no tenant assignment).
  async function establishAuthenticatedSession(
    req: Request,
    user: { id: string; role: string; username: string },
    clientIp: string,
    traceId: string,
  ): Promise<{ ok: true } | { ok: false; status: number; body: any }> {
    // Session fixation prevention: regenerate before writing any authenticated state.
    await new Promise<void>((resolve, reject) => {
      req.session.regenerate((err) => (err ? reject(err) : resolve()));
    });
    // Fail-closed primary-tenant resolution (LOGIN-UTR bypass: no session GUC yet at login time).
    const primaryTenant = await withBypassRls((bypassDb) =>
      bypassDb
        .select({ tenantId: userTenantRoles.tenantId })
        .from(userTenantRoles)
        .where(
          and(
            eq(userTenantRoles.userId, user.id),
            eq(userTenantRoles.isPrimary, true),
            eq(userTenantRoles.isActive, true),
          ),
        )
        .limit(1),
    );
    if (primaryTenant.length === 0) {
      authLogger.warn("Login rejected — no primary tenant assignment", { traceId, metadata: { username: user.username, userId: user.id } });
      await storage.createAuditLog({ userId: user.id, action: "LOGIN_REJECTED_NO_TENANT", resource: "Authentication System", details: `Login rejected: no primary tenant assignment for user ${user.username}`, ipAddress: clientIp });
      return { ok: false, status: 403, body: { error: "TENANT_ASSIGNMENT_MISSING", message: "Login rejected: account has no tenant assignment. Contact your administrator.", traceId } };
    }
    req.session.userId = user.id;
    req.session.userRole = user.role;
    req.session.tenantId = primaryTenant[0].tenantId;
    req.session.loginAt = Date.now();
    req.session.loginIp = clientIp;
    req.session.lastActivityAt = Date.now(); // idle-window anchor (tranche 3)
    // Concurrent-session cap (tranche 2) — dedicated appPool connection, fail-open.
    try {
      const capClient = await appPool.connect();
      try {
        await capClient.query(
          `DELETE FROM "session" WHERE sid IN (
             SELECT sid FROM "session" WHERE (sess->>'userId') = $1 AND sid <> $3 ORDER BY expire DESC OFFSET $2
           )`,
          [user.id, Math.max(0, MAX_CONCURRENT_SESSIONS - 1), req.sessionID],
        );
      } finally {
        capClient.release();
      }
    } catch (capErr) {
      authLogger.warn("Concurrent-session cap enforcement failed (fail-open — login proceeds)", { traceId, metadata: { userId: user.id, error: String((capErr as Error)?.message ?? capErr) } });
    }
    await storage.createAuditLog({ userId: user.id, action: "LOGIN", resource: "Authentication System", details: `User ${user.username} authenticated successfully`, ipAddress: clientIp });
    try {
      const { sessionManager } = await import("./lib/session-manager");
      await sessionManager.createSession(user.id, req);
    } catch (e) {}
    return { ok: true };
  }

  // ============ AUTH ROUTES ============

  // Login with rate limiting, account lockout, and anomaly detection
  app.post("/api/auth/login", loginRateLimiter, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    const clientIp = getClientIp(req);
    const userAgent = req.headers["user-agent"] || "unknown";

    const parsed = loginSchema.safeParse(req.body);
    if (!parsed.success) {
      authLogger.warn("Invalid login request format", { traceId });
      return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "credentials" }, traceId));
    }

    const { username, password, totpToken } = parsed.data as { username: string; password: string; totpToken?: string };
    
    // Check account lockout before proceeding
    const lockoutStatus = await isAccountLocked(username, clientIp);
    if (lockoutStatus.isLocked) {
      const remainingSeconds = Math.ceil((lockoutStatus.remainingMs || 0) / 1000);
      authLogger.warn("Login blocked - account locked", { 
        traceId, 
        metadata: { username, remainingSeconds, failedAttempts: lockoutStatus.failedAttempts } 
      });
      return res.status(423).json({
        error: "ACCOUNT_LOCKED",
        message: `Account temporarily locked. Try again in ${Math.ceil(remainingSeconds / 60)} minutes.`,
        retryAfter: remainingSeconds,
      });
    }
    
    const user = await storage.getUserByUsername(username);

    const passwordResult = user ? await verifyPassword(password, user.password) : { valid: false, needsRehash: false };
    if (!user || !passwordResult.valid) {
      const lockoutResult = await recordFailedLogin(username, clientIp);
      await recordLogin(user?.id ?? "", username, clientIp, userAgent, false);
      
      await storage.createAuditLog({
        action: "LOGIN_FAILED",
        resource: "Authentication System",
        details: `Failed login attempt for username: ${username}`,
        ipAddress: clientIp,
      });
      
      authLogger.warn("Invalid credentials", { 
        traceId, 
        metadata: { username, remainingAttempts: lockoutResult.remainingAttempts } 
      });
      
      const response: any = {
        ...createErrorResponse("AEGIS_ERR_001", undefined, traceId),
        remainingAttempts: lockoutResult.remainingAttempts,
      };
      
      if (lockoutResult.isLocked) {
        response.locked = true;
        response.lockoutDuration = lockoutResult.lockoutDuration;
      }
      
      return res.status(401).json(response);
    }

    if (!user.isActive) {
      authLogger.warn("Account disabled", { traceId, metadata: { username } });
      return res.status(403).json(createErrorResponse("AEGIS_ERR_006", undefined, traceId));
    }
    
    // Check if 2FA is enabled and verify token
    if (await isTwoFactorEnabled(user.id)) {
      if (!totpToken) {
        authLogger.info("2FA required for user", { traceId, metadata: { username } });
        return res.status(200).json({
          success: false,
          requires2FA: true,
          message: "Two-factor authentication required",
        });
      }
      
      const twoFactorResult = await verifyTwoFactor(user.id, totpToken);
      if (!twoFactorResult.success) {
        authLogger.warn("2FA verification failed", { traceId, metadata: { username } });
        return res.status(401).json({
          error: "INVALID_2FA_TOKEN",
          message: "Invalid two-factor authentication code",
        });
      }
      
      if (twoFactorResult.method === "backup" && twoFactorResult.remainingBackupCodes !== undefined) {
        authLogger.warn("Backup code used for 2FA", { 
          traceId, 
          metadata: { username, remainingBackupCodes: twoFactorResult.remainingBackupCodes } 
        });
      }
    }
    
    // Analyze login for anomalies
    const anomalyResult = await analyzeLoginAttempt(user.id, username, clientIp, userAgent);

    // M67: persist the detection HERE — before the BLOCK branch below, which returns.
    // Writing after it would silently drop every blocked attempt, i.e. the highest-risk
    // detections the platform makes and the exact rows an incident investigation needs.
    //
    // Only anomalous attempts (riskScore >= 30) are stored. Routine logins are not, so
    // this adds no blanket behavioural log of ordinary user activity — the record exists
    // because something was detected, not because someone logged in.
    //
    // Fail-open for the user, fail-loud for the record: persistLoginAnomaly never throws
    // and cannot block a legitimate login; on failure it logs at ERROR rather than
    // leaving the platform believing it holds a record it does not hold. Awaited (not
    // fire-and-forget) so the row is durable before the response is sent.
    if (anomalyResult.isAnomalous) {
      const { persistLoginAnomaly } = await import("./lib/login-anomaly-store");
      await persistLoginAnomaly(db, {
        userId: user.id,
        username,
        ipAddress: clientIp,
        userAgent,
        riskScore: anomalyResult.riskScore,
        recommendation: anomalyResult.recommendation,
        requiresVerification: anomalyResult.requiresVerification,
        factors: anomalyResult.factors,
      });
    }

    if (anomalyResult.recommendation === "BLOCK") {
      authLogger.warn("Login blocked due to high-risk anomaly", { 
        traceId, 
        metadata: { username, riskScore: anomalyResult.riskScore, factors: anomalyResult.factors.length } 
      });
      return res.status(403).json({
        error: "LOGIN_BLOCKED",
        message: "Login blocked due to suspicious activity. Please contact support.",
        riskScore: anomalyResult.riskScore,
      });
    }

    await storage.updateUserLastLogin(user.id);
    
    await recordSuccessfulLogin(username, clientIp);
    await recordLogin(user.id, username, clientIp, userAgent, true);

    if (passwordResult.needsRehash) {
      const newHash = await hashPasswordAsync(password);
      await storage.updateUserPassword(user.id, newHash);
      authLogger.info("Password rehashed from legacy SHA-256 to bcrypt", { traceId, metadata: { username } });
    }

    // Session fixation prevention + fail-closed tenant resolution + the six session fields +
    // concurrent-session cap + LOGIN audit + session-manager — all in the shared helper so a password
    // session and a passkey session are established identically. (Exhaustive scan of L918-L1035
    // confirmed zero req.session.* writes before this point. FU-053 Del-7 §7.1.)
    const established = await establishAuthenticatedSession(req, user, clientIp, traceId);
    if (!established.ok) return res.status(established.status).json(established.body);

    authLogger.info("User authenticated", { 
      traceId, 
      userId: user.id, 
      duration: Date.now() - startTime,
      metadata: { username: user.username, role: user.role }
    });

    const responseData: any = {
      success: true,
      user: {
        id: user.id,
        username: user.username,
        fullName: user.fullName,
        role: user.role,
        department: user.department,
      },
    };
    
    // Include anomaly warning if detected
    if (anomalyResult.isAnomalous && anomalyResult.recommendation === "CHALLENGE") {
      responseData.securityWarning = {
        message: "Unusual login activity detected",
        riskScore: anomalyResult.riskScore,
        factors: anomalyResult.factors.map(f => f.description),
      };
    }
    
    res.json(responseData);
  }));

  // ── Passkey (WebAuthn) login — the login factor the FIDO2 crypto lacked ──────────────────────────
  // Pre-session + rate-limited. `options` returns a WebAuthn assertion challenge for the account's
  // registered passkeys; `verify` checks the assertion and, on success, establishes a session IDENTICAL
  // to a password login via the shared establishAuthenticatedSession helper. (Anti-enumeration: `options`
  // returns the same 404 whether the account is unknown or simply has no passkey.)
  app.post("/api/auth/passkey/login/options", loginRateLimiter, asyncHandler(async (req, res) => {
    const username = String((req.body ?? {}).username ?? "");
    if (!username) return res.status(400).json({ error: "username_required" });
    const user = await storage.getUserByUsername(username);
    const { fido2Manager } = await import("./lib/fido2-passkey");
    if (!user || !(await fido2Manager.isUserEnrolled(user.id))) {
      return res.status(404).json({ error: "no_passkey", message: "No passkey is registered for this account." });
    }
    res.json(await fido2Manager.getAuthenticationOptions(user.id)); // { challengeId, options }
  }));

  app.post("/api/auth/passkey/login/verify", loginRateLimiter, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const clientIp = getClientIp(req);
    const { username, challengeId, response } = req.body ?? {};
    if (typeof username !== "string" || typeof challengeId !== "string" || !response) {
      return res.status(400).json({ error: "invalid_request" });
    }
    const user = await storage.getUserByUsername(String(username));
    if (!user) return res.status(401).json({ error: "passkey_auth_failed" });
    if ((user as any).isActive === false) return res.status(403).json({ error: "ACCOUNT_INACTIVE", message: "Account is inactive." });
    const { fido2Manager } = await import("./lib/fido2-passkey");
    const result = await fido2Manager.verifyAuthentication(String(challengeId), response, user.id);
    if (!result.success) {
      await storage.createAuditLog({ userId: user.id, action: "PASSKEY_LOGIN_FAILED", resource: "Authentication System", details: `Passkey assertion failed: ${result.error ?? "unknown"}`, ipAddress: clientIp });
      return res.status(401).json({ error: "passkey_auth_failed" });
    }
    await storage.updateUserLastLogin(user.id);
    await recordLogin(user.id, user.username, clientIp, String(req.headers["user-agent"] ?? ""), true);
    const established = await establishAuthenticatedSession(req, user, clientIp, traceId);
    if (!established.ok) return res.status(established.status).json(established.body);
    res.json({ success: true, user: { id: user.id, username: user.username, fullName: user.fullName, role: user.role, department: user.department } });
  }));

  // Logout
  app.post("/api/auth/logout", requireAuth, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const userId = req.session.userId;
    
    if (userId) {
      await storage.createAuditLog({
        userId,
        action: "LOGOUT",
        resource: "Authentication System",
        details: "User session terminated",
        ipAddress: getClientIp(req),
      });
      authLogger.info("User logged out", { traceId, userId });
    }

    req.session.destroy((err) => {
      if (err) {
        authLogger.error("Session destruction failed", { traceId, error: err as Error });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      res.json({ success: true });
    });
  }));

  // ============ STEP-UP AUTHENTICATION (auth-hardening tranche 1) ============
  // A fresh second-factor challenge (TOTP if enrolled, else password re-auth) that gates sensitive
  // actions. requireStepUp is FAIL-CLOSED: any error, an absent/stale step-up (older than the TTL), or
  // a behavioral-biometrics anomaly demand ⇒ 403 step_up_required. This turns the previously-dormant
  // `requiresStepUp` behavioral signal (which only logged) into a real enforcement gate.
  const STEP_UP_TTL_MS = 5 * 60 * 1000; // a step-up stays fresh for 5 minutes
  const stepUpFresh = (req: Request): boolean =>
    typeof req.session.steppedUpAt === "number" &&
    !req.session.stepUpDemanded &&
    Date.now() - req.session.steppedUpAt <= STEP_UP_TTL_MS;

  const requireStepUp = async (req: Request, res: Response, next: NextFunction) => {
    try {
      if (!req.session.userId) {
        return res.status(401).json(createErrorResponse("AEGIS_ERR_004", { path: req.path }));
      }
      if (stepUpFresh(req)) return next();
      const { isTwoFactorEnabled } = await import("./lib/two-factor-auth");
      const factor = (await isTwoFactorEnabled(req.session.userId)) ? "totp" : "password";
      return res.status(403).json({ error: "step_up_required", stepUpRequired: true, factor, ttlMs: STEP_UP_TTL_MS });
    } catch (err) {
      // Fail-closed: a gate that errors must DENY, never allow.
      authLogger.error("requireStepUp errored — denying (fail-closed)", { error: err as Error });
      return res.status(403).json({ error: "step_up_required", stepUpRequired: true, factor: "password", ttlMs: STEP_UP_TTL_MS });
    }
  };

  // Perform a step-up: TOTP for 2FA-enrolled users, password re-auth otherwise.
  app.post("/api/auth/step-up", requireAuth, asyncHandler(async (req, res) => {
    const userId = req.session.userId!;
    const { totpToken, password } = req.body ?? {};
    const { isTwoFactorEnabled, verifyTwoFactor } = await import("./lib/two-factor-auth");
    const twoFA = await isTwoFactorEnabled(userId);
    let ok = false;
    let method = twoFA ? "totp" : "password";
    if (twoFA) {
      if (!totpToken) return res.status(400).json({ error: "totp_required", factor: "totp" });
      const r = await verifyTwoFactor(userId, String(totpToken));
      ok = r.success;
      method = r.method ?? "totp";
    } else {
      if (!password) return res.status(400).json({ error: "password_required", factor: "password" });
      const user = await storage.getUser(userId);
      const pr = user ? await verifyPassword(String(password), user.password) : { valid: false };
      ok = !!pr.valid;
    }
    if (!ok) {
      await storage.createAuditLog({ action: "STEP_UP_AUTH_FAILED", resource: "Authentication", userId, details: `factor=${twoFA ? "totp" : "password"}`, ipAddress: getClientIp(req) });
      return res.status(401).json({ error: "step_up_failed", stepUpRequired: true, factor: twoFA ? "totp" : "password" });
    }
    req.session.steppedUpAt = Date.now();
    req.session.stepUpDemanded = false;
    // Persist the step-up to the session store BEFORE responding. The client step-up modal auto-retries
    // the original gated action immediately on this 200 (~10-15ms later); without an explicit save,
    // express-session's async write can land AFTER that retry reads the session — so the retry still
    // sees no fresh step-up and 403s (a race that only surfaces with the auto-retry, not manual re-click).
    // Awaiting save() guarantees steppedUpAt is committed before the client can retry.
    await new Promise<void>((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve())));
    await storage.createAuditLog({ action: "STEP_UP_AUTH_SUCCESS", resource: "Authentication", userId, details: `method=${method}`, ipAddress: getClientIp(req) });
    res.json({ steppedUp: true, method, ttlMs: STEP_UP_TTL_MS });
  }));

  // Current step-up status for the session.
  app.get("/api/auth/step-up/status", requireAuth, asyncHandler(async (req, res) => {
    const userId = req.session.userId!;
    const { isTwoFactorEnabled } = await import("./lib/two-factor-auth");
    res.json({
      steppedUp: stepUpFresh(req),
      steppedUpAt: req.session.steppedUpAt ?? null,
      demanded: !!req.session.stepUpDemanded,
      ttlMs: STEP_UP_TTL_MS,
      factor: (await isTwoFactorEnabled(userId)) ? "totp" : "password",
    });
  }));

  // A real sensitive read, gated by step-up — released ONLY after a fresh step-up. Demonstrates the
  // enforcement end-to-end (blocked without step-up, released with it).
  app.get("/api/auth/step-up/sensitive-account-view", requireAuth, requireStepUp, asyncHandler(async (req, res) => {
    const userId = req.session.userId!;
    const { isTwoFactorEnabled } = await import("./lib/two-factor-auth");
    res.json({
      note: "Sensitive account view — released only after a fresh step-up authentication.",
      userId,
      role: req.session.userRole,
      twoFactorEnabled: await isTwoFactorEnabled(userId),
      releasedAt: new Date().toISOString(),
    });
  }));

  // ============ ACTIVE SESSIONS (auth-hardening tranche 2 — concurrent-session cap) ============
  // List the current user's active sessions (from the pg-backed session store). Reads on a dedicated
  // appPool connection. Never returns raw session ids — only the current-flag + login metadata.
  app.get("/api/auth/sessions", requireAuth, asyncHandler(async (req, res) => {
    const userId = req.session.userId!;
    const { isGeoConfigured } = await import("./lib/geo-ip");
    const client = await appPool.connect();
    try {
      const r = await client.query(
        // expire is a tz-NAIVE column and, worse, connect-pg-simple SLIDES it to now+maxAge on each
        // save — so it is NOT the real deadline. The real per-session expiry is the EARLIER of the
        // absolute cap (loginAt + SESSION_ABSOLUTE_MS) and the idle deadline (lastActivityAt +
        // SESSION_IDLE_MS), both enforced by the /api middleware. Compute that below; fall back to the
        // store expire (as correct epoch-ms) only for legacy sessions with no loginAt.
        `SELECT sid, sess->>'loginAt' AS login_at, sess->>'loginIp' AS login_ip,
                sess->>'lastActivityAt' AS last_activity,
                (extract(epoch from expire) * 1000)::bigint AS store_expire_ms
           FROM "session" WHERE (sess->>'userId') = $1 AND expire > now()
           ORDER BY expire DESC`,
        [userId],
      );
      const sessions = r.rows.map((row: any) => {
        const loginAt = row.login_at ? Number(row.login_at) : null;
        const lastActivityAt = row.last_activity ? Number(row.last_activity) : loginAt;
        let expiresAt = row.store_expire_ms ? Number(row.store_expire_ms) : null;
        if (loginAt != null) {
          const absoluteDeadline = loginAt + SESSION_ABSOLUTE_MS;
          const idleDeadline = (lastActivityAt ?? loginAt) + SESSION_IDLE_MS;
          expiresAt = Math.min(absoluteDeadline, idleDeadline);
        }
        return {
          current: row.sid === req.sessionID,
          loginAt,
          loginIp: row.login_ip ?? null,
          expiresAt,
        };
      });
      const geoConfigured = isGeoConfigured();
      res.json({
        cap: MAX_CONCURRENT_SESSIONS,
        count: sessions.length,
        idleTimeoutMs: SESSION_IDLE_MS,
        absoluteTimeoutMs: SESSION_ABSOLUTE_MS,
        impossibleTravel: {
          geoConfigured,
          note: geoConfigured
            ? "Impossible-travel detection active — logins are geolocated and travel-speed checked."
            : "Impossible-travel detection is built and wired into login, but dormant — awaiting the MaxMind GeoLite2 database file (set MAXMIND_DB_PATH).",
        },
        sessions,
      });
    } finally {
      client.release();
    }
  }));

  // Revoke all of the current user's OTHER sessions (sign out everywhere else). A real security action.
  app.post("/api/auth/sessions/revoke-others", requireAuth, asyncHandler(async (req, res) => {
    const userId = req.session.userId!;
    const client = await appPool.connect();
    try {
      const r = await client.query(
        `DELETE FROM "session" WHERE (sess->>'userId') = $1 AND sid <> $2`,
        [userId, req.sessionID],
      );
      const revoked = r.rowCount ?? 0;
      await storage.createAuditLog({ action: "SESSIONS_REVOKED_OTHERS", resource: "Authentication", userId, details: `revoked=${revoked}`, ipAddress: getClientIp(req) });
      res.json({ revoked });
    } finally {
      client.release();
    }
  }));

  // Check session
  app.get("/api/auth/session", asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    
    if (!req.session.userId) {
      return res.json({ success: true, user: null });
    }

    const user = await storage.getUser(req.session.userId);
    if (!user) {
      authLogger.warn("Session user not found", { traceId, metadata: { userId: req.session.userId } });
      return res.json({ success: true, user: null });
    }

    res.json({
      success: true,
      user: {
        id: user.id,
        username: user.username,
        fullName: user.fullName,
        role: user.role,
        department: user.department,
      },
    });
  }));

  // ============ DASHBOARD ROUTES ============

  // Get dashboard stats
  app.get("/api/dashboard/stats", requireAuth, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    
    const stats = await storage.getThreatsStats();
    
    apiLogger.debug("Dashboard stats fetched", { traceId, duration: Date.now() - startTime });
    res.json({ success: true, ...stats });
  }));

  // ============ THREAT ROUTES ============

  // Get all threats
  app.get("/api/threats", requireAuth, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    
    const limit = parseInt(req.query.limit as string) || 50;
    const threats = await storage.getThreats(limit);
    
    threatLogger.debug("Threats fetched", { traceId, duration: Date.now() - startTime, metadata: { count: threats.length } });
    res.json(threats);
  }));

  // Threat summary stats (active / neutralized counts) — exposes the REAL getThreatsStats()
  // source already used by the export service. Previously unregistered: /system-pulse queried
  // /api/threats/stats and got a 404 -> ?? 0 frozen counts under a "Live (EDR)" label. requireAuth
  // matches the sibling GET /api/threats list route (a stats route is as protected as its list).
  app.get("/api/threats/stats", requireAuth, asyncHandler(async (req, res) => {
    res.json(await storage.getThreatsStats());
  }));

  // Neutralize a threat - with Idempotent API support
  app.post("/api/threats/:id/neutralize", requireRole("admin", "risk_manager"), idempotencyMiddleware(60000), asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    const { id } = req.params;
    const userId = req.session.userId!;

    const threat = await storage.neutralizeThreat(String(id), String(userId));
    if (!threat) {
      threatLogger.warn("Threat not found for neutralization", { traceId, metadata: { threatId: id } });
      return res.status(404).json(createErrorResponse("AEGIS_ERR_301", { threatId: id }, traceId));
    }

    await storage.createAuditLog({
      userId,
      action: "THREAT_NEUTRALIZED",
      resource: `Threat ID: ${id}`,
      details: `Threat neutralized by user`,
      ipAddress: getClientIp(req),
    });

    threatLogger.info("Threat neutralized", { 
      traceId, 
      userId, 
      duration: Date.now() - startTime,
      metadata: { threatId: id, riskLevel: threat.riskLevel }
    });
    
    res.json({ success: true, threat });
  }));

  // ============ FINCRIME / AEGIS SOAR (AS/SOAR/2026/001) ============

  // M1 Gate 2 — source-agnostic ingestion seam. A SIGNAL → one OPEN case.
  // Auth: session-only, Admin / Risk Manager (machine API-key ingestion is a
  // deferred, separately-scoped item). Tenant comes from the authenticated
  // actor (req.tenantId, session-derived by tenantMiddleware), NEVER the request
  // payload — the strict DTO rejects a tenant_id key outright. The durable write
  // runs inside a BOUNDED tenant transaction (withTenantDbPhase) that COMMITS
  // before this handler responds, so a 201 is never returned for an uncommitted
  // case (no respond-before-commit false-green). Scope fence: creates OPEN and
  // stops — no investigation / disposition / STR (those are M2/M3).
  app.post(
    "/api/fincrime/ingest",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const userRole = req.session.userRole!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        // tenantMiddleware must resolve a tenant for an authenticated actor;
        // its absence is a server-side invariant break, not a client error.
        apiLogger.error("Fincrime ingest: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const parsed = ingestSignalSchema.safeParse(req.body);
      if (!parsed.success) {
        apiLogger.warn("Fincrime ingest rejected — invalid signal", {
          traceId,
          metadata: { issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), code: i.code })) },
        });
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_signal" }, traceId));
      }

      const signal = parsed.data;
      const sourceSignalHash = computeSourceSignalHash(signal);

      // Bounded tenant tx — commits before we respond.
      const result = await withTenantDbPhase(req, () =>
        storage.ingestFincrimeSignal({
          tenantId,
          actorUserId: userId,
          actorRole: userRole,
          sourceType: signal.sourceType,
          sourceRef: signal.sourceRef ?? null,
          subjectRef: signal.subjectRef,
          subjectRefKind: signal.subjectRefKind,
          sourceSignalHash,
          signal: signal.signal,
        }),
      );

      apiLogger.info("Fincrime signal ingested", {
        traceId,
        userId,
        metadata: { caseId: result.case.id, created: result.created, sourceType: signal.sourceType },
      });

      return res.status(result.created ? 201 : 200).json({
        caseId: result.case.id,
        state: result.case.state,
        created: result.created,
      });
    }),
  );

  // ============ AEGIS SOAR M1 — MACHINE-API-KEY INGESTION (AS/SOAR/2026/001) =======
  //
  // Same durable ingestion seam as POST /api/fincrime/ingest, but authenticated by
  // a scoped MACHINE KEY (Authorization: Bearer mk_...) instead of an operator
  // session — for automated source pipelines (KYT / sanctions / adverse-media feeds).
  // Identical defences: tenant is BOUND TO THE KEY (never the payload), the
  // OPAQUE_SUBJECT_REF guard in ingestSignalSchema rejects raw PII / kyc: subjects,
  // and the write runs in a bounded withTenantDbPhase that COMMITS before we respond.
  // Scope-fenced to "ingest:fincrime"; rate-limited per key id. FAIL-CLOSED DORMANT:
  // when MACHINE_KEY_SALT is unset the middleware answers 503 and this route is
  // unusable — the session path above is unaffected.
  app.post(
    "/api/fincrime/ingest/machine",
    // Pre-auth per-IP flood ceiling (600/min/IP) — caps how fast one source IP can
    // force the bearer-hash DB lookup, independent of any valid key. Runs BEFORE
    // requireMachineKey so it keys on IP. The per-key limiter below runs AFTER auth.
    machineIngestIpRateLimiter,
    requireMachineKey("ingest:fincrime"),
    machineIngestRateLimiter,
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const mk = (req as any).machineKey as { keyId: string; tenantId: string } | undefined;
      const tenantId = mk?.tenantId;
      if (!tenantId) {
        apiLogger.error("Machine fincrime ingest: no tenant bound to key", { traceId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const parsed = ingestSignalSchema.safeParse(req.body);
      if (!parsed.success) {
        apiLogger.warn("Machine fincrime ingest rejected — invalid signal", {
          traceId,
          metadata: { issues: parsed.error.issues.map((i) => ({ path: i.path.join("."), code: i.code })) },
        });
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_signal" }, traceId));
      }

      const signal = parsed.data;
      const sourceSignalHash = computeSourceSignalHash(signal);

      // Bounded tenant tx (tenant GUC from the key) — commits before we respond.
      const result = await withTenantDbPhase(req, () =>
        storage.ingestFincrimeSignal({
          tenantId,
          actorUserId: `machine:${mk!.keyId}`,
          actorRole: "machine_ingest",
          sourceType: signal.sourceType,
          sourceRef: signal.sourceRef ?? null,
          subjectRef: signal.subjectRef,
          subjectRefKind: signal.subjectRefKind,
          sourceSignalHash,
          signal: signal.signal,
        }),
      );

      apiLogger.info("Fincrime signal ingested (machine)", {
        traceId,
        metadata: { caseId: result.case.id, created: result.created, sourceType: signal.sourceType, keyId: mk!.keyId },
      });

      return res.status(result.created ? 201 : 200).json({
        caseId: result.case.id,
        state: result.case.state,
        created: result.created,
      });
    }),
  );

  // Admin management of machine ingestion keys (mint / list / revoke). Minting
  // returns the raw key ONCE; only its SHA-256 hash is stored. requireRole("admin").
  app.post(
    "/api/fincrime/machine-keys",
    requirePlatformAdmin,
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const issuedBy = (req.session as any)?.username || String(req.session.userId ?? "system");
      const { label, scopes, tenantId, ttlHours } = req.body || {};
      if (!label || typeof label !== "string") return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { field: "label" }, traceId));
      if (!Array.isArray(scopes) || scopes.length === 0) return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { field: "scopes" }, traceId));
      if (!tenantId || typeof tenantId !== "string") return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { field: "tenantId" }, traceId));
      if (!machineKeyAuthConfigured()) return res.status(503).json({ error: "machine-key-auth-not-configured" });
      const ttl = typeof ttlHours === "number" && ttlHours > 0 ? ttlHours : 24 * 90;
      // Bounded tenant tx so the mint COMMITS before we return the raw key (no
      // respond-before-commit false-green — same discipline as the revoke path).
      // fincrime_ingest_keys is not RLS-scoped, so the phase GUC does not gate the
      // insert; the wrap is purely for commit-before-respond durability.
      const minted = await withTenantDbPhase(req, () =>
        issueMachineKey({ label, scopes, tenantId, ttlHours: ttl, issuedBy }),
      );
      apiLogger.info("Machine ingest key minted (admin)", { traceId, metadata: { keyId: minted.id, tenantId, scopes } });
      return res.status(201).json(minted);
    }),
  );

  app.get(
    "/api/fincrime/machine-keys",
    requirePlatformAdmin,
    asyncHandler(async (_req, res) => {
      return res.json(await listMachineKeys());
    }),
  );

  app.delete(
    "/api/fincrime/machine-keys/:id",
    requirePlatformAdmin,
    asyncHandler(async (req, res) => {
      const revokedBy = (req.session as any)?.username || String(req.session.userId ?? "system");
      // Bounded tenant tx so the revocation COMMITS before we respond (no
      // revocation-race false-green — same discipline as the examiner-token revoke).
      const revoked = await withTenantDbPhase(req, () => revokeMachineKey(req.params.id, revokedBy));
      if (!revoked) return res.status(404).json({ error: "not-found" });
      return res.json(revoked);
    }),
  );

  // ============ AEGIS SOAR M2 — INVESTIGATION ROUTES (AS/SOAR/2026/001) ============
  //
  // M2 takes an OPEN fincrime case through investigation to PENDING_MLCO_REVIEW.
  // The transition surface is exactly three edges — assign / start ⇒
  // UNDER_INVESTIGATION; escalate-mlco ⇒ PENDING_MLCO_REVIEW — plus evidence-add
  // (no state change) and a read route. There is DELIBERATELY no route that
  // disposes a case or writes any disposition column: DISPOSITIONED is an M3
  // concern (the M3 fence). The target state is derived server-side from the
  // action (assertM2Transition in the storage layer); a client can never name a
  // target state — the strict DTOs reject state / disposition / dispositioned_at /
  // str_filed / tenant_id / id outright.
  //
  // Every mutation: requireRole(admin/risk_manager) + session-derived tenant
  // (never the payload) + the EFFECTIVE (tenant-scoped) actor role + a bounded
  // tenant tx (withTenantDbPhase) that COMMITS before we respond (no
  // respond-before-commit false-green). The durable transition is compare-and-set
  // on (tenant_id, id, state); a 0-row match is a 409 (someone moved it / wrong
  // precondition), never a silent no-op. Reads include auditor (read-only).

  // List cases for a queue (read-only; auditor included). Tenant-scoped; the queue
  // selector is a closed enum — an unknown queue is a 400.
  app.get(
    "/api/fincrime/cases",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime cases list: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const parsedQueue = queueSchema.safeParse(req.query.queue);
      if (!parsedQueue.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_queue" }, traceId));
      }

      const cases = await withTenantDbPhase(req, () =>
        storage.listFincrimeCasesForQueue({
          tenantId,
          actorUserId: userId,
          queue: parsedQueue.data,
        }),
      );

      // The case spine carries no raw PII (subjectRef is opaque, sourceSignalHash a
      // digest). We still project an explicit non-sensitive field set rather than
      // leaking the whole row shape; disposition columns are deliberately omitted
      // (all NULL at M2, and not this gate's concern).
      return res.status(200).json({
        queue: parsedQueue.data,
        cases: cases.map((c) => ({
          id: c.id,
          state: c.state,
          sourceType: c.sourceType,
          sourceRef: c.sourceRef,
          subjectRef: c.subjectRef,
          subjectRefKind: c.subjectRefKind,
          assignedInvestigatorId: c.assignedInvestigatorId,
          openedAt: c.openedAt,
          updatedAt: c.updatedAt,
        })),
      });
    }),
  );

  // Assign a case to an investigator (OPEN → UNDER_INVESTIGATION, set assignee).
  app.post(
    "/api/fincrime/cases/:id/assign",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime assign: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id;

      const parsed = assignCaseSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_assign" }, traceId));
      }

      // Assignee eligibility — SINGLE generic failure (no existence / role oracle).
      // The assignee must be an active user whose EFFECTIVE role in THIS tenant is
      // admin or risk_manager. A non-existent user, an inactive user, a user bound
      // to another tenant, and a wrong-role user ALL produce the identical 400, so
      // the response cannot be used to probe who exists or what role they hold.
      const assignee = await storage.getUser(parsed.data.assigneeUserId);
      const assigneeRole = assignee && assignee.isActive
        ? await resolveEffectiveRole(assignee.id, assignee.role, tenantId)
        : "none";
      if (!assignee || !assignee.isActive || (assigneeRole !== "admin" && assigneeRole !== "risk_manager")) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_assignee" }, traceId));
      }

      const result = await withTenantDbPhase(req, () =>
        storage.assignFincrimeCase({
          tenantId,
          actorUserId: userId,
          actorRole,
          caseId,
          assigneeUserId: parsed.data.assigneeUserId,
        }),
      );

      if (!result.ok) {
        // CAS matched no row — case absent in this tenant OR not in the expected
        // state. Both collapse to a 409 state-precondition (assign is CAS-only).
        return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: "state_precondition" }, traceId));
      }

      apiLogger.info("Fincrime case assigned", { traceId, userId, metadata: { caseId, state: result.case?.state } });
      return res.status(200).json({ caseId, state: result.case?.state });
    }),
  );

  // Start investigation (OPEN → UNDER_INVESTIGATION). An optional note is persisted
  // as an encrypted INVESTIGATION_NOTE evidence row (never stored raw).
  app.post(
    "/api/fincrime/cases/:id/start",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime start: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id;

      const parsed = startInvestigationSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_start" }, traceId));
      }

      const result = await withTenantDbPhase(req, () =>
        storage.startFincrimeInvestigation({
          tenantId,
          actorUserId: userId,
          actorRole,
          caseId,
          note: parsed.data.note ?? null,
        }),
      );

      if (!result.ok) {
        return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: "state_precondition" }, traceId));
      }

      apiLogger.info("Fincrime investigation started", { traceId, userId, metadata: { caseId, state: result.case?.state } });
      return res.status(200).json({ caseId, state: result.case?.state, evidenceId: result.evidenceId });
    }),
  );

  // Add evidence to a case (no state change). Eligible only while the case is OPEN
  // or UNDER_INVESTIGATION. Free-text notes are encrypted at rest; opaque pointers
  // stay opaque. A note never reaches the audit / event payload (payload_hash only).
  app.post(
    "/api/fincrime/cases/:id/evidence",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime evidence: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id;

      const parsed = addEvidenceSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_evidence" }, traceId));
      }

      const result = await withTenantDbPhase(req, () =>
        storage.addFincrimeCaseEvidence({
          tenantId,
          actorUserId: userId,
          actorRole,
          caseId,
          evidenceType: parsed.data.evidenceType,
          opaqueRef: parsed.data.opaqueRef ?? null,
          note: parsed.data.note ?? null,
        }),
      );

      if (result.notFound) {
        return res.status(404).json(createErrorResponse("AEGIS_ERR_103", { reason: "case_not_found" }, traceId));
      }
      if (result.stateNotAllowed) {
        return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: "state_not_eligible" }, traceId));
      }

      apiLogger.info("Fincrime evidence added", { traceId, userId, metadata: { caseId, evidenceId: result.evidenceId } });
      return res.status(201).json({ caseId, evidenceId: result.evidenceId });
    }),
  );

  // Escalate to MLCO review (UNDER_INVESTIGATION → PENDING_MLCO_REVIEW). The required
  // summary is persisted as an encrypted INVESTIGATION_NOTE evidence row so the MLCO
  // can read the rationale later; it is never stored raw and never enters the audit
  // payload. This is the terminal M2 edge — it does NOT dispose (M3 fence).
  app.post(
    "/api/fincrime/cases/:id/escalate-mlco",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime escalate: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id;

      const parsed = escalateMlcoSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_escalate" }, traceId));
      }

      const result = await withTenantDbPhase(req, () =>
        storage.escalateFincrimeCaseToMlcoReview({
          tenantId,
          actorUserId: userId,
          actorRole,
          caseId,
          summary: parsed.data.summary,
        }),
      );

      if (!result.ok) {
        return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: "state_precondition" }, traceId));
      }

      apiLogger.info("Fincrime case escalated to MLCO review", { traceId, userId, metadata: { caseId, state: result.case?.state } });
      return res.status(200).json({ caseId, state: result.case?.state, evidenceId: result.evidenceId });
    }),
  );

  // ── AEGIS SOAR M3 CHUNK 2 — LOCKED-DOOR STR FINALIZER (3 routes) ──────────
  // The routes are thin: resolve actor + tenant from the SESSION (never the
  // payload), validate the strict DTO, run the storage method inside the request
  // tenant tx, and map StrGuardError → 404/409. StrWorkflowError (an invariant the
  // route guard should have stopped) propagates to the global handler (500).

  // R1 (maker): prepare an STR for a case in PENDING_MLCO_REVIEW. The free-text
  // narrative is encrypted at rest; only narrative_hash leaves storage in the clear.
  // The STR is created PREPARED with NULL FIA-ack fields — nothing here ever
  // fabricates an acknowledgement (criterion 1). Senior roles only.
  app.post(
    "/api/fincrime/cases/:id/str",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime STR prepare: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id;

      const parsed = prepareStrSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_str_prepare" }, traceId));
      }

      try {
        const result = await withTenantDbPhase(req, () =>
          storage.prepareStr({
            tenantId,
            actorUserId: userId,
            actorRole,
            caseId,
            narrative: parsed.data.narrative,
          }),
        );
        apiLogger.info("Fincrime STR prepared", { traceId, userId, metadata: { caseId, strReportId: result.strReportId } });
        return res.status(201).json({ caseId, strReportId: result.strReportId, status: result.status, narrativeHash: result.narrativeHash });
      } catch (err) {
        if (err instanceof StrGuardError) {
          if (err.code === "NOT_FOUND") {
            return res.status(404).json(createErrorResponse("AEGIS_ERR_103", { reason: "case_not_found" }, traceId));
          }
          return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: err.code.toLowerCase() }, traceId));
        }
        throw err; // StrWorkflowError + anything else → global handler (500)
      }
    }),
  );

  // R2 (checker): THE LOCKED DOOR. Approve the prepared STR (two-eyes) AND dispose
  // the case PENDING_MLCO_REVIEW → DISPOSITIONED in one tx. The disposition is
  // HARD-DERIVED (STR_RECOMMENDED) — the payload carries ONLY the reviewed-narrative
  // hash (anti-stale) + a rationale (encrypted at rest). Self-approval is rejected
  // (criterion 2). Senior roles only.
  app.post(
    "/api/fincrime/cases/:id/finalize",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime STR finalize: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id;

      const parsed = finalizeStrSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "fincrime_str_finalize" }, traceId));
      }

      try {
        const result = await withTenantDbPhase(req, () =>
          storage.finalizeStr({
            tenantId,
            actorUserId: userId,
            actorRole,
            caseId,
            reportHash: parsed.data.reportHash,
            reason: parsed.data.reason,
          }),
        );
        apiLogger.info("Fincrime case finalized (STR recommended)", { traceId, userId, metadata: { caseId, state: result.state, strReportId: result.strReportId, approvalId: result.approvalId } });
        return res.status(200).json({ caseId, state: result.state, disposition: result.disposition, strReportId: result.strReportId, approvalId: result.approvalId });
      } catch (err) {
        if (err instanceof StrGuardError) {
          if (err.code === "NOT_FOUND") {
            return res.status(404).json(createErrorResponse("AEGIS_ERR_103", { reason: "case_not_found" }, traceId));
          }
          return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: err.code.toLowerCase() }, traceId));
        }
        throw err; // StrWorkflowError + anything else → global handler (500)
      }
    }),
  );

  // R3 (scoped read): return the case's STR with the narrative decrypted, for senior
  // staff or a scoped auditor only — never a subject-facing role (criterion 3,
  // tipping-off). Tenant-scoped (RLS); a sibling tenant reads null → 404.
  app.get(
    "/api/fincrime/cases/:id/str",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime STR read: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id;

      const result = await withTenantDbPhase(req, () =>
        storage.getStrForCase({ tenantId, caseId }),
      );
      if (!result) {
        return res.status(404).json(createErrorResponse("AEGIS_ERR_103", { reason: "str_not_found" }, traceId));
      }
      apiLogger.info("Fincrime STR read", { traceId, userId, metadata: { caseId, strReportId: result.id } });
      return res.status(200).json(result);
    }),
  );

  // ── AEGIS SOAR M3 CHUNK 3 — goAML Form-B EXPORT (read-only render) ───────────
  // Projects the stored STR facts (disposed case + PREPARED STR + MLCO approval) into
  // the FIA's goAML Form-B payload. READ-ONLY: no state transition, no disposing edge,
  // no mutation — it adds NO write surface (the M3-fence holds). Same senior/auditor
  // roles as GET /str (the payload is a SUBSET of what /str already exposes — narrative
  // + opaque ref + metadata — so no broader exposure). Tenant-scoped (RLS); a sibling
  // tenant reads null → 404 (no cross-tenant oracle). Submits nothing; the live goAML
  // connector + registered MLCO/goAML account stay per-deployment wiring.
  app.get(
    "/api/fincrime/cases/:id/formb",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime goAML Form-B export: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id as string;

      const source = await withTenantDbPhase(req, () =>
        storage.getFincrimeFormBSource({ tenantId, caseId }),
      );
      if (!source) {
        return res.status(404).json(createErrorResponse("AEGIS_ERR_103", { reason: "formb_not_renderable" }, traceId));
      }
      const payload = renderGoamlFormB(source, getGoamlDeploymentConfig());
      // A regulator disclosure must not be cached by any intermediary.
      res.setHeader("Cache-Control", "no-store");
      // Log only IDs/metadata — never the payload or the decrypted narrative.
      apiLogger.info("Fincrime goAML Form-B exported", { traceId, userId, metadata: { caseId, strReportId: source.strReportId } });
      return res.status(200).json(payload);
    }),
  );

  // ── goAML XML EXPORT (read-only serialize) ──────────────────────────────────
  // Same STR facts as /formb, but serialized into Uganda FIA goAML XML. Wires the
  // real, previously test-only serializeGoamlXml. READ-ONLY: renders the Form-B
  // then serializes — no state transition, no write surface. Same senior/auditor
  // roles + tenant scope (RLS) as /formb. Returns the XML plus an HONEST verdict:
  // `submittable` is false while the subject's civil identity is a separately-gated
  // DEFERRED step (never fabricated), `gaps` lists the specific blockers, and
  // `xsdValidation` stays PENDING_ACTUAL_UGANDA_XSD (the FIA XSD is portal-gated).
  // In-platform XSD validation and automated submission (GOAML_ENDPOINT_URL) remain
  // documented seams — this route generates the artifact; the bank uploads it to the
  // FIA goAML portal, which validates on submission.
  app.get(
    "/api/fincrime/cases/:id/goaml-xml",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Fincrime goAML XML export: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const caseId = req.params.id as string;

      const source = await withTenantDbPhase(req, () =>
        storage.getFincrimeFormBSource({ tenantId, caseId }),
      );
      if (!source) {
        return res.status(404).json(createErrorResponse("AEGIS_ERR_103", { reason: "goaml_xml_not_renderable" }, traceId));
      }
      const formB = renderGoamlFormB(source, getGoamlDeploymentConfig());
      const result = serializeGoamlXml(formB);
      // A regulator disclosure must not be cached by any intermediary.
      res.setHeader("Cache-Control", "no-store");
      // Log only IDs/metadata + the submittability verdict — never the XML or the decrypted narrative.
      apiLogger.info("Fincrime goAML XML exported", { traceId, userId, metadata: { caseId, strReportId: source.strReportId, submittable: result.submittable, gapCount: result.gaps.length } });
      return res.status(200).json(result);
    }),
  );

  // ── ENVELOPE KEY-MANAGEMENT (KEY_MANAGEMENT_SCOPE.md, Layer 1/2) ─────────────
  // Surfaces the real envelope-encryption mechanism: DEK-wrapped-by-KEK with
  // versioned KEK rotation that re-wraps data keys WITHOUT bulk re-encryption
  // (the operation the disabled rotateEncryptionKey could not do). Status is
  // read-only (admin/auditor). Rotate is a sensitive crypto op — admin + STEP-UP
  // (re-auth), reusing the step-up control. HONEST: the env-derived KEK is the
  // dev/sandbox default (cloud KMS/HSM is the pluggable, not-wired seam), and the
  // live PII column estate is NOT yet migrated onto this mechanism (staged T2).
  app.get(
    "/api/key-management/status",
    requireRole("admin", "auditor"),
    asyncHandler(async (_req, res) => {
      const status = await getKeyManagementStatus();
      res.setHeader("Cache-Control", "no-store");
      return res.status(200).json(status);
    }),
  );
  app.post(
    "/api/key-management/rotate-kek",
    requireRole("admin"),
    requireStepUp,
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const result = await rotateKek(userId);
      apiLogger.info("KEK rotation performed", { traceId, userId, metadata: result });
      res.setHeader("Cache-Control", "no-store");
      return res.status(200).json(result);
    }),
  );
  // Live self-test — exercises the mechanism end-to-end (encrypt → rotate → decrypt pre-rotation
  // data) on the running stack. Admin-only diagnostic; performs a real KEK rotation.
  app.post(
    "/api/key-management/self-test",
    requireRole("admin"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const result = await selfTestKeyManagement(userId);
      apiLogger.info("Key-management self-test run", { traceId, userId, metadata: { ok: result.ok, kekAfter: result.kekAfter, rewrapped: result.rewrapped } });
      res.setHeader("Cache-Control", "no-store");
      return res.status(200).json(result);
    }),
  );

  // ── User directory (admin) ──────────────────────────────────────────────────
  // Read-only list of platform users with their DECRYPTED full names (platform-key
  // PII via the async decryptPii read path) + role/status. Never returns password
  // hashes. Admin-only.
  app.get(
    "/api/users",
    requireRole("admin"),
    asyncHandler(async (_req, res) => {
      const list = await storage.listUsers();
      res.setHeader("Cache-Control", "no-store");
      return res.status(200).json(list);
    }),
  );

  // ============ AEGIS SECURITY IR (SECURITY_IR_WORKFLOW_SCOPE.md) ============
  //
  // A durable, tenant-isolated, audit-chained SECURITY-incident lifecycle (Layer 1
  // + the Layer-2 alert-in seam). Modelled on the fincrime case routes above: every
  // mutation is requireRole(admin/risk_manager) + session-derived tenant (NEVER the
  // payload) + the EFFECTIVE tenant-scoped actor role + a bounded tenant tx
  // (withTenantDbPhase) that COMMITS before we respond. The transition target state
  // is derived server-side from the route-path ACTION (assertIrTransition in the
  // storage layer) — a client can never name a target state; the strict DTOs reject
  // status / state / tenant_id / id outright. The durable transition is compare-and-
  // set on (tenant_id, id, status); a 0-row match is a 409, never a silent no-op.
  //
  // Reads include auditor (read-only). NOT in this increment (Layer 3 / next layer):
  // containment effectors, ServiceNow/PagerDuty push-out, auto-containment, UI.

  // The five lifecycle transition actions, keyed by the route-path segment. A path
  // segment NOT in this map is a 400 (the storage chokepoint also rejects unknown
  // actions defensively).
  const IR_PATH_ACTIONS: Record<string, string> = {
    triage: "TRIAGE",
    contain: "CONTAIN",
    eradicate: "ERADICATE",
    recover: "RECOVER",
    close: "CLOSE",
  };

  // List incidents for a queue (read-only; auditor included). Tenant-scoped; the
  // queue selector is a closed enum — an unknown queue is a 400.
  app.get(
    "/api/security-incidents",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Security IR list: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const parsedQueue = irQueueSchema.safeParse(req.query.queue);
      if (!parsedQueue.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "security_ir_queue" }, traceId));
      }

      const incidents = await withTenantDbPhase(req, () =>
        storage.listSecurityIncidentsForQueue({
          tenantId,
          actorUserId: userId,
          queue: parsedQueue.data,
        }),
      );

      return res.status(200).json({
        queue: parsedQueue.data,
        incidents: incidents.map((i) => ({
          id: i.id,
          title: i.title,
          severity: i.severity,
          status: i.status,
          assignedTo: i.assignedTo,
          originatingAlertRef: i.originatingAlertRef,
          originatingAlertSource: i.originatingAlertSource,
          slaTargetMinutes: i.slaTargetMinutes,
          acknowledgedAt: i.acknowledgedAt,
          resolvedAt: i.resolvedAt,
          breached: i.breached,
          openedAt: i.openedAt,
          updatedAt: i.updatedAt,
          closedAt: i.closedAt,
        })),
      });
    }),
  );

  // Get a single incident (read-only; auditor included). Tenant-scoped (RLS); a
  // sibling tenant reads undefined → 404 (no cross-tenant oracle).
  app.get(
    "/api/security-incidents/:id",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Security IR get: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const incidentId = req.params.id;

      // Enrich the detail with the audit-chained event TIMELINE + containment ACTIONS so the
      // case-detail UI can render the real history and label SIMULATED actions honestly. All
      // tenant-scoped in one DB phase; a sibling tenant reads nothing → 404 (no cross-tenant oracle).
      const detail = await withTenantDbPhase(req, async () => {
        const inc = await storage.getSecurityIncident({ tenantId, incidentId });
        if (!inc) return { incident: undefined, events: [], actions: [] };
        const [events, actions] = await Promise.all([
          storage.listSecurityIncidentEvents({ tenantId, incidentId }),
          storage.listSecurityIncidentActions({ tenantId, incidentId }),
        ]);
        return { incident: inc, events, actions };
      });
      if (!detail.incident) {
        return res.status(404).json(createErrorResponse("AEGIS_ERR_103", { reason: "incident_not_found" }, traceId));
      }
      return res.status(200).json(detail);
    }),
  );

  // Open an incident MANUALLY (no originating alert). Severity drives the folded
  // SLA target. Returns the new incident id + state.
  app.post(
    "/api/security-incidents",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Security IR open: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const parsed = openIncidentSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "security_ir_open" }, traceId));
      }

      const incident = await withTenantDbPhase(req, () =>
        storage.openSecurityIncident({
          tenantId,
          actorUserId: userId,
          actorRole,
          title: parsed.data.title,
          severity: parsed.data.severity,
          note: parsed.data.note ?? null,
        }),
      );

      apiLogger.info("Security incident opened (manual)", { traceId, userId, metadata: { incidentId: incident.id, severity: incident.severity } });
      return res.status(201).json({ incidentId: incident.id, status: incident.status });
    }),
  );

  // Open an incident FROM AN ALERT (Layer-2 seam). HONEST EDGE: the alert DATA is
  // synthetic until the APT-make-real effort lands; this route wires the real
  // INTERFACE (alertId + source on the request body, stored as the originating
  // reference on the case) so NOTHING here changes when the feed becomes real. We do
  // NOT claim "detection-driven IR" — the feeding alert is not yet real. The alert
  // reference is stored so triage can trace back to the originating observation.
  app.post(
    "/api/security-incidents/from-alert",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Security IR open-from-alert: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const parsed = openFromAlertSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "security_ir_from_alert" }, traceId));
      }

      const incident = await withTenantDbPhase(req, () =>
        storage.openSecurityIncident({
          tenantId,
          actorUserId: userId,
          actorRole,
          title: parsed.data.title,
          severity: parsed.data.severity,
          note: parsed.data.note ?? null,
          originatingAlertRef: parsed.data.alertId,
          originatingAlertSource: parsed.data.source,
        }),
      );

      apiLogger.info("Security incident opened from alert", { traceId, userId, metadata: { incidentId: incident.id, severity: incident.severity, alertSource: parsed.data.source } });
      return res.status(201).json({ incidentId: incident.id, status: incident.status });
    }),
  );

  // Advance an incident through the lifecycle. The action comes from the ROUTE PATH
  // (triage/contain/eradicate/recover/close), never the body — the strict DTO body
  // carries only an optional note and cannot name a target state. CAS miss → 409.
  app.post(
    "/api/security-incidents/:id/transition/:action",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Security IR transition: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const incidentId = req.params.id;

      const action = IR_PATH_ACTIONS[String(req.params.action)];
      if (!action) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "security_ir_action" }, traceId));
      }

      const parsed = transitionSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "security_ir_transition" }, traceId));
      }

      const result = await withTenantDbPhase(req, () =>
        storage.transitionSecurityIncident({
          tenantId,
          actorUserId: userId,
          actorRole,
          incidentId,
          action,
          note: parsed.data.note ?? null,
        }),
      );

      if (!result.ok) {
        return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: "state_precondition" }, traceId));
      }

      apiLogger.info("Security incident transitioned", { traceId, userId, metadata: { incidentId, action, status: result.incident?.status } });
      return res.status(200).json({ incidentId, status: result.incident?.status });
    }),
  );

  // Assign an incident to a responder (no state change). Single generic 400 on an
  // ineligible assignee (no existence / role oracle), mirroring the fincrime assign.
  app.post(
    "/api/security-incidents/:id/assign",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("Security IR assign: no tenant context on authenticated request", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }
      const incidentId = req.params.id;

      const parsed = assignIncidentSchema.safeParse(req.body);
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "security_ir_assign" }, traceId));
      }

      // Assignee eligibility — SINGLE generic failure (no existence / role oracle).
      // The assignee must be an active user whose EFFECTIVE role in THIS tenant is
      // admin or risk_manager. A non-existent / inactive / wrong-tenant / wrong-role
      // user ALL produce the identical 400.
      const assignee = await storage.getUser(parsed.data.assigneeUserId);
      const assigneeRole = assignee && assignee.isActive
        ? await resolveEffectiveRole(assignee.id, assignee.role, tenantId)
        : "none";
      if (!assignee || !assignee.isActive || (assigneeRole !== "admin" && assigneeRole !== "risk_manager")) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "security_ir_assignee" }, traceId));
      }

      const result = await withTenantDbPhase(req, () =>
        storage.assignSecurityIncident({
          tenantId,
          actorUserId: userId,
          actorRole,
          incidentId,
          assigneeUserId: parsed.data.assigneeUserId,
        }),
      );

      if (!result.ok) {
        return res.status(409).json(createErrorResponse("AEGIS_ERR_104", { reason: "state_precondition" }, traceId));
      }

      apiLogger.info("Security incident assigned", { traceId, userId, metadata: { incidentId, status: result.incident?.status } });
      return res.status(200).json({ incidentId, status: result.incident?.status });
    }),
  );

  // ============ AEGIS UEBA ROUTES (UEBA_PRIVILEGED_SCOPE.md) ============
  //
  // Insider-threat detection on PRIVILEGED users, computed from the REAL, tamper-
  // evident audit stream (audit_logs). admin / risk_manager only + tenant-scoped +
  // CSRF (app.use(csrfProtection) is global). PRIVACY: this watches the bank's OWN
  // staff — viewing is itself privileged — so every baseline rebuild, detection run,
  // anomaly creation, and anomaly LIST is audit-chained via storage.createAuditLog
  // (which hash-chains through chainAuditLog). No UI in this increment.

  // Rebuild behavioral baselines for the tenant's users (or a single user). Each
  // baseline is computed from that user's REAL audit_logs rows — never synthesized.
  app.post(
    "/api/ueba/baselines/rebuild",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("UEBA baseline rebuild: no tenant context", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      // Strict DTO: optional targetUserId + optional windowDays. Unknown keys rejected.
      const parsed = z
        .object({
          targetUserId: z.string().min(1).max(256).optional(),
          windowDays: z.number().int().positive().max(365).optional(),
        })
        .strict()
        .safeParse(req.body ?? {});
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "ueba_rebuild" }, traceId));
      }

      const results = await withTenantDbPhase(req, () =>
        rebuildBaselinesForTenant(tenantId, {
          userId: parsed.data.targetUserId,
          windowDays: parsed.data.windowDays ?? DEFAULT_BASELINE_WINDOW_DAYS,
        }),
      );

      // PRIVACY audit-chain: record WHO rebuilt baselines over WHOSE behavior. Non-PII
      // structural detail only (counts, target scope) — never raw audit content.
      await storage.createAuditLog({
        userId,
        action: "UEBA_BASELINE_REBUILT",
        resource: parsed.data.targetUserId ? `ueba_baseline:${parsed.data.targetUserId}` : "ueba_baselines:tenant",
        details: JSON.stringify({
          tenantId,
          targetUserId: parsed.data.targetUserId ?? "ALL",
          usersRebuilt: results.length,
          coldStart: results.filter((r) => !r.trustworthy).length,
        }),
        ipAddress: getClientIp(req),
      });

      apiLogger.info("UEBA baselines rebuilt", { traceId, userId, metadata: { usersRebuilt: results.length } });
      return res.status(200).json({
        usersRebuilt: results.length,
        minSamples: MIN_BASELINE_SAMPLES,
        results: results.map((r) => ({
          userId: r.userId,
          sampleCount: r.sampleCount,
          // Honest cold-start surfacing — NOT trustworthy below the floor.
          status: r.trustworthy ? "ready" : `baseline building (${r.sampleCount}/${MIN_BASELINE_SAMPLES})`,
        })),
      });
    }),
  );

  // List the tenant's persisted baselines (audit-chained: viewing staff baselines is
  // itself privileged).
  app.get(
    "/api/ueba/baselines",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("UEBA baselines list: no tenant context", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const baselines = await withTenantDbPhase(req, () => storage.listUebaBaselines(tenantId));

      await storage.createAuditLog({
        userId,
        action: "UEBA_BASELINES_VIEWED",
        resource: "ueba_baselines:tenant",
        details: JSON.stringify({ tenantId, count: baselines.length }),
        ipAddress: getClientIp(req),
      });

      return res.status(200).json({
        count: baselines.length,
        minSamples: MIN_BASELINE_SAMPLES,
        baselines: baselines.map((b) => ({
          userId: b.userId,
          sampleCount: b.sampleCount,
          windowDays: b.windowDays,
          avgExportsPerDay: b.avgExportsPerDay,
          lastRebuiltAt: b.lastRebuiltAt,
          trustworthy: b.sampleCount >= MIN_BASELINE_SAMPLES,
          status: b.sampleCount >= MIN_BASELINE_SAMPLES ? "ready" : `baseline building (${b.sampleCount}/${MIN_BASELINE_SAMPLES})`,
        })),
      });
    }),
  );

  // Run the two detection rules over recent REAL audit rows. Each anomaly cites the
  // triggering audit_logs id(s) and is persisted; a high-confidence anomaly opens a
  // security_incident via the EXISTING IR seam (storage.openSecurityIncident) and the
  // opened incident id is stamped back on the anomaly (Layer 3).
  app.post(
    "/api/ueba/detect/run",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const actorRole = (req as any).effectiveRole as string;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("UEBA detect run: no tenant context", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const parsed = z
        .object({ windowHours: z.number().int().positive().max(720).optional() })
        .strict()
        .safeParse(req.body ?? {});
      if (!parsed.success) {
        return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "ueba_detect" }, traceId));
      }

      const outcome = await withTenantDbPhase(req, async () => {
        const userIds = await tenantUserIds(tenantId);
        const detection = await runDetection(tenantId, userIds, parsed.data.windowHours);

        const persisted: Array<{ anomalyId: string; rule: string; confidence: number; openedIncidentId: string | null }> = [];
        for (const a of detection.anomalies) {
          // Persist the anomaly (DB CHECK requires it to cite a real audit row).
          const stored = await storage.insertUebaAnomaly({
            tenantId,
            userId: a.userId,
            rule: a.rule,
            observed: a.observed,
            expected: a.expected,
            confidence: a.confidence,
            triggeringAuditIds: a.triggeringAuditIds,
          });

          // Layer 3: high-confidence anomaly → open a real security_incident via the
          // EXISTING seam, then stamp the incident id back on the anomaly.
          let openedIncidentId: string | null = null;
          if (a.confidence >= HIGH_CONFIDENCE_THRESHOLD) {
            const incident = await storage.openSecurityIncident({
              tenantId,
              actorUserId: userId,
              actorRole,
              title: `UEBA: ${a.rule} on user ${a.userId}`,
              // P2 for a high-confidence insider-threat anomaly (resolution SLA derived).
              severity: "P2",
              originatingAlertRef: stored.id,
              originatingAlertSource: "UEBA",
            });
            openedIncidentId = incident.id;
            await storage.setUebaAnomalyIncident(tenantId, stored.id, incident.id);
          }

          persisted.push({ anomalyId: stored.id, rule: a.rule, confidence: a.confidence, openedIncidentId });
        }

        return { detection, persisted };
      });

      // PRIVACY audit-chain: a detection run inspected staff behavior — record it.
      await storage.createAuditLog({
        userId,
        action: "UEBA_DETECTION_RUN",
        resource: "ueba_anomalies:tenant",
        details: JSON.stringify({
          tenantId,
          usersEvaluated: outcome.detection.usersEvaluated,
          anomalies: outcome.persisted.length,
          incidentsOpened: outcome.persisted.filter((p) => p.openedIncidentId).length,
          coldStartSkipped: outcome.detection.skippedColdStart.length,
        }),
        ipAddress: getClientIp(req),
      });

      apiLogger.info("UEBA detection run", { traceId, userId, metadata: { anomalies: outcome.persisted.length } });
      return res.status(200).json({
        usersEvaluated: outcome.detection.usersEvaluated,
        anomaliesDetected: outcome.persisted.length,
        incidentsOpened: outcome.persisted.filter((p) => p.openedIncidentId).length,
        // Honest cold-start disclosure: these users were NOT evaluated (no false clear).
        coldStartSkipped: outcome.detection.skippedColdStart,
        anomalies: outcome.persisted,
      });
    }),
  );

  // List persisted anomalies (audit-chained: viewing a watch-list on staff is
  // itself privileged).
  app.get(
    "/api/ueba/anomalies",
    requireRole("admin", "risk_manager"),
    asyncHandler(async (req, res) => {
      const traceId = (req as any).traceId;
      const userId = req.session.userId!;
      const tenantId = (req as any).tenantId as string | undefined;
      if (!tenantId) {
        apiLogger.error("UEBA anomalies list: no tenant context", { traceId, userId });
        return res.status(500).json(createErrorResponse("AEGIS_ERR_500", undefined, traceId));
      }

      const limit = Math.min(parseInt(String(req.query.limit ?? "100"), 10) || 100, 500);
      const anomalies = await withTenantDbPhase(req, () => storage.listUebaAnomalies(tenantId, { limit }));

      await storage.createAuditLog({
        userId,
        action: "UEBA_ANOMALIES_VIEWED",
        resource: "ueba_anomalies:tenant",
        details: JSON.stringify({ tenantId, count: anomalies.length }),
        ipAddress: getClientIp(req),
      });

      return res.status(200).json({
        count: anomalies.length,
        anomalies: anomalies.map((a) => ({
          id: a.id,
          userId: a.userId,
          rule: a.rule,
          observed: a.observed,
          expected: a.expected,
          confidence: a.confidence,
          // The cited REAL audit_logs ids — a human can inspect the exact rows.
          triggeringAuditIds: JSON.parse(a.triggeringAuditIds) as string[],
          openedIncidentId: a.openedIncidentId,
          detectedAt: a.detectedAt,
        })),
      });
    }),
  );

  // ============ AUDIT LOG ROUTES ============

  // Get audit logs
  app.get("/api/audit-logs", requireAuth, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    
    const action = req.query.action as string | undefined;
    const limit = parseInt(req.query.limit as string) || 100;
    
    const logs = await storage.getAuditLogs({ action, limit });
    
    apiLogger.debug("Audit logs fetched", { traceId, duration: Date.now() - startTime, metadata: { count: logs.length } });
    res.json(logs);
  }));

  // ============ SETTINGS ROUTES ============

  // Get AI thresholds
  app.get("/api/settings/thresholds", requireAuth, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    
    const thresholds = await storage.getThresholds();
    
    apiLogger.debug("Thresholds fetched", { traceId });
    res.json(thresholds);
  }));

  // Update AI thresholds (admin only) - with Configuration Drift Detection
  app.post("/api/settings/thresholds", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    const { thresholds } = req.body;
    const userId = req.session.userId!;

    const newSettings: Record<string, string> = {};
    
    for (const threshold of thresholds) {
      const existing = await storage.updateThreshold(threshold.id, threshold.value, userId);
      
      newSettings[threshold.name?.toLowerCase().replace(/\s+/g, "_") || threshold.id] = threshold.value.toString();
      
      await storage.createAuditLog({
        userId,
        action: "THRESHOLD_CHANGED",
        resource: "AI Configuration",
        details: `${threshold.name} updated`,
        ipAddress: getClientIp(req),
        previousValue: existing?.thresholdValue?.toString(),
        newValue: threshold.value.toString(),
      });
    }

    const { detectDrift } = await import("./lib/drift-detection");
    const driftEvents = await detectDrift(userId, newSettings);
    
    if (driftEvents.some(e => e.severity === "CRITICAL")) {
      apiLogger.error("CRITICAL DRIFT DETECTED in AI thresholds", {
        traceId,
        userId,
        metadata: { 
          criticalChanges: driftEvents.filter(e => e.severity === "CRITICAL").map(e => e.setting)
        }
      });
    }

    apiLogger.info("AI thresholds updated", { 
      traceId, 
      userId, 
      duration: Date.now() - startTime,
      metadata: { count: thresholds.length, driftEvents: driftEvents.length }
    });
    
    res.json({ success: true, driftEvents: driftEvents.length > 0 ? driftEvents : undefined });
  }));

  app.post("/api/settings/change-password", requireAuth, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const userId = req.session.userId!;
    const body = req.body || {};
    const { currentPassword, newPassword } = body;

    if (!currentPassword || !newPassword) {
      return res.status(400).json({ error: "Current password and new password are required" });
    }

    if (newPassword.length < 12) {
      return res.status(400).json({ error: "New password must be at least 12 characters" });
    }

    if (newPassword.length > 128) {
      return res.status(400).json({ error: "Password must not exceed 128 characters" });
    }

    if (currentPassword === newPassword) {
      return res.status(400).json({ error: "New password must be different from current password" });
    }

    const user = await storage.getUser(userId);
    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }

    const { valid: isValid } = await verifyPassword(currentPassword, user.password);
    if (!isValid) {
      await storage.createAuditLog({
        userId,
        action: "PASSWORD_CHANGE_FAILED",
        resource: "User Account",
        details: "Incorrect current password provided",
        ipAddress: getClientIp(req),
      });
      return res.status(401).json({ error: "Current password is incorrect" });
    }

    const hasUppercase = /[A-Z]/.test(newPassword);
    const hasLowercase = /[a-z]/.test(newPassword);
    const hasNumber = /[0-9]/.test(newPassword);
    const hasSpecial = /[^A-Za-z0-9]/.test(newPassword);
    const complexityCount = [hasUppercase, hasLowercase, hasNumber, hasSpecial].filter(Boolean).length;

    if (complexityCount < 3) {
      return res.status(400).json({
        error: "Password must contain at least 3 of: uppercase letter, lowercase letter, number, special character"
      });
    }

    const hashedPassword = await hashPasswordAsync(newPassword);
    await storage.updateUserPassword(userId, hashedPassword);

    await storage.createAuditLog({
      userId,
      action: "PASSWORD_CHANGED",
      resource: "User Account",
      details: "Password changed successfully",
      ipAddress: getClientIp(req),
    });

    apiLogger.info("Password changed successfully", { traceId, userId });
    res.json({ success: true, message: "Password changed successfully" });
  }));

  // ============ WEBSOCKET FOR REAL-TIME UPDATES ============
  //
  // CO-016 closure (Carve-Outs Register v1.1, 2026-05-18):
  //   FIND-F1 — upgrade-time authentication via verifyClient (was: auth
  //     performed post-upgrade by sessionParser inside the connection
  //     handler, with a 5s timeout grace window). verifyClient reuses the
  //     same `sessionMiddleware` instance defined above so the cookie
  //     parsing, signature verification, and pg-backed store lookup are
  //     identical to the HTTP request path.
  //   FIND-F2 / F3 hardening lives in server/lib/event-bus.ts where the
  //     per-message dispatch and per-socket rate limiter are wired. The
  //     wss instance below currently registers no `ws.on("message")` —
  //     attaching to event-bus via eventBus.attachWebSocket(wss) would
  //     route incoming messages through the Zod-validated, rate-limited
  //     pipeline there.
  const wss = new WebSocketServer({
    server: httpServer,
    path: "/ws",
    verifyClient: (
      info: { req: IncomingMessage },
      cb: (verified: boolean, code?: number, message?: string) => void
    ) => {
      sessionMiddleware(info.req as any, {} as any, () => {
        const sess = (info.req as any).session;
        if (sess?.userId) {
          cb(true);
        } else {
          cb(false, 401, "Unauthorized");
        }
      });
    },
  });

  const clients = new Set<WebSocket>();

  wss.on("connection", (ws) => {
    clients.add(ws);
    // Upgrade already authenticated via verifyClient above; no in-handler
    // session parsing, no auth-timeout window, no auth-as-first-message
    // pattern remains.
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: "connected", message: "AEGIS CYBER WebSocket connected" }));
    }

    ws.on("close", () => {
      clients.delete(ws);
    });
  });

  // REMOVED (2026-06-30, zero-drop fabrication excision): the demo-threat
  // emitter (`setInterval` guarded by `Math.random() > 0.7`) that auto-emitted
  // fabricated threats (random maker/amount/threatType/risk/IP/branch and a
  // random `anomalyScore`) over the authenticated WebSocket and persisted them
  // via `storage.createThreat`. The fabricated `anomalyScore` was being re-read
  // as a real input by the (now-removed) `/api/ai-scoring/analyze` route —
  // synthetic data laundered into the scoring pipeline. The WebSocket server
  // above is REAL and KEPT; only the fabricated-threat generator is gone (its
  // sole consumer, the `broadcastThreat` helper, is removed with it).

  // ============ WEBHOOK ROUTES ============

  // Get all webhooks
  app.get("/api/webhooks", requireAuth, asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    
    const webhooks = await storage.getWebhooks();
    
    webhookLogger.debug("Webhooks fetched", { traceId, duration: Date.now() - startTime, metadata: { count: webhooks.length } });
    res.json(webhooks);
  }));

  // Create a webhook
  app.post("/api/webhooks", requireRole("admin"), asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    
    const config = {
      ...req.body,
      createdBy: req.session.userId,
      // AS/PLATFORM/2026/008 Tenant-Sep Chunk B — bind tenant from req ctx (the
      // GUC source set by tenant-middleware), NEVER the client body.
      tenantId: (req as any).tenantId,
    };
    const webhook = await storage.createWebhook(config);

    await storage.createAuditLog({
      userId: req.session.userId!,
      action: "WEBHOOK_CREATED",
      resource: `Webhook: ${webhook.name}`,
      details: `Created ${webhook.integrationType} integration`,
      ipAddress: getClientIp(req),
    });

    webhookLogger.info("Webhook created", { 
      traceId, 
      userId: req.session.userId, 
      duration: Date.now() - startTime,
      metadata: { webhookId: webhook.id, name: webhook.name, type: webhook.integrationType }
    });
    
    res.status(201).json({ success: true, webhook });
  }));

  // Update a webhook
  app.patch("/api/webhooks/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    const { id } = req.params;
    
    const webhook = await storage.updateWebhook(String(id), req.body);
    
    if (!webhook) {
      webhookLogger.warn("Webhook not found for update", { traceId, metadata: { webhookId: id } });
      return res.status(404).json(createErrorResponse("AEGIS_ERR_401", { webhookId: id }, traceId));
    }

    await storage.createAuditLog({
      userId: req.session.userId!,
      action: "WEBHOOK_UPDATED",
      resource: `Webhook: ${webhook.name}`,
      details: `Updated integration configuration`,
      ipAddress: getClientIp(req),
    });

    webhookLogger.info("Webhook updated", { 
      traceId, 
      userId: req.session.userId, 
      duration: Date.now() - startTime,
      metadata: { webhookId: id, name: webhook.name }
    });
    
    res.json({ success: true, webhook });
  }));

  // Delete a webhook
  app.delete("/api/webhooks/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    const { id } = req.params;
    
    const webhook = await storage.getWebhookById(String(id));
    
    if (!webhook) {
      webhookLogger.warn("Webhook not found for deletion", { traceId, metadata: { webhookId: id } });
      return res.status(404).json(createErrorResponse("AEGIS_ERR_401", { webhookId: id }, traceId));
    }

    await storage.deleteWebhook(String(id));

    await storage.createAuditLog({
      userId: req.session.userId!,
      action: "WEBHOOK_DELETED",
      resource: `Webhook: ${webhook.name}`,
      details: `Deleted ${webhook.integrationType} integration`,
      ipAddress: getClientIp(req),
    });

    webhookLogger.info("Webhook deleted", { 
      traceId, 
      userId: req.session.userId, 
      duration: Date.now() - startTime,
      metadata: { webhookId: id, name: webhook.name }
    });
    
    res.status(204).send();
  }));

  // Get webhook logs
  app.get("/api/webhooks/logs", requireRole("admin"), asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();
    
    const webhookId = req.query.webhookId as string | undefined;
    const logs = await storage.getWebhookLogs(webhookId);
    
    webhookLogger.debug("Webhook logs fetched", { traceId, duration: Date.now() - startTime, metadata: { count: logs.length } });
    res.json(logs);
  }));

  // ========================================
  // COMMERCIAL-GRADE RESILIENCE ENDPOINTS
  // ========================================

  // Initialize resilience systems on startup
  initializeDriftDetection().catch(err => 
    logger.error("Drift detection init failed", { error: err instanceof Error ? err : new Error(String(err)) })
  );
  initializeHoneypots();

  // Get resilience status (all systems combined)
  app.get("/api/resilience/status", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const startTime = Date.now();

    const [chainStats, driftStats, honeypotStats] = await Promise.all([
      getChainStats(),
      getDriftStats(),
      Promise.resolve(getHoneypotStats())
    ]);

    const aiCircuitStats = aiCircuitBreaker.getStats();
    const cbsCircuitStats = cbsCircuitBreaker.getStats();
    const idempotencyStats = await getIdempotencyStats();

    const status = {
      timestamp: new Date().toISOString(),
      overallStatus: chainStats.integrityStatus === "VERIFIED" && 
                     aiCircuitStats.state === "CLOSED" ? "OPERATIONAL" : "DEGRADED",
      circuitBreakers: {
        aiEngine: aiCircuitStats,
        coreBanking: cbsCircuitStats
      },
      idempotency: idempotencyStats,
      forensicChain: chainStats,
      configDrift: driftStats,
      honeypots: honeypotStats,
      slaCompliance: {
        target: "<200ms",
        current: `${Date.now() - startTime}ms`,
        met: (Date.now() - startTime) < 200
      }
    };

    apiLogger.info("Resilience status fetched", { 
      traceId, 
      duration: Date.now() - startTime,
      metadata: { overallStatus: status.overallStatus }
    });

    res.json(status);
  }));

  // Get circuit breaker status
  app.get("/api/resilience/circuit-breakers", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json({
      aiEngine: aiCircuitBreaker.getStats(),
      coreBanking: cbsCircuitBreaker.getStats()
    });
  }));

  // Reset circuit breaker (admin only)
  app.post("/api/resilience/circuit-breakers/reset", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { breaker } = req.body;
    
    if (breaker === "ai") {
      aiCircuitBreaker.reset();
    } else if (breaker === "cbs") {
      cbsCircuitBreaker.reset();
    } else {
      aiCircuitBreaker.reset();
      cbsCircuitBreaker.reset();
    }

    await storage.createAuditLog({
      action: "CIRCUIT_BREAKER_RESET",
      resource: breaker || "all",
      userId: req.session.userId!,
      details: `Circuit breaker ${breaker || "all"} manually reset`,
      ipAddress: getClientIp(req),
    });

    res.json({ success: true, message: "Circuit breaker(s) reset" });
  }));

  // Validate forensic chain integrity
  app.get("/api/resilience/chain/validate", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const validation = await validateChain();
    const stats = await getChainStats();
    
    res.json({
      ...stats,
      validation
    });
  }));

  // Get drift detection stats
  app.get("/api/resilience/drift", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await getDriftStats());
  }));

  // Get honeypot status
  app.get("/api/resilience/honeypots", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json({
      stats: getHoneypotStats(),
      accounts: getGhostAccounts().map(g => ({
        ...g,
        accountNumber: g.accountNumber.substring(0, 4) + "****" + g.accountNumber.substring(8)
      }))
    });
  }));

  // Get idempotency cache stats
  app.get("/api/resilience/idempotency", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(await getIdempotencyStats());
  }));

  // Get static fallback status and rules
  app.get("/api/resilience/fallback", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getFallbackStatus, getStaticRules } = await import("./lib/static-fallback");
    res.json({
      status: getFallbackStatus(),
      rules: getStaticRules()
    });
  }));

  // Get crypto-agility status
  app.get("/api/resilience/crypto", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { getCryptoStatus, getSupportedAlgorithms } = await import("./lib/crypto-agility");
    res.json({
      status: getCryptoStatus(),
      supportedAlgorithms: getSupportedAlgorithms()
    });
  }));

  // Update crypto algorithm (hot-swap)
  app.post("/api/resilience/crypto/algorithm", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { algorithm } = req.body;
    const { setAlgorithm, getCryptoStatus } = await import("./lib/crypto-agility");
    
    setAlgorithm(algorithm);
    
    await storage.createAuditLog({
      action: "CRYPTO_ALGORITHM_CHANGED",
      resource: "Crypto Service",
      userId: req.session.userId!,
      details: `Encryption algorithm hot-swapped to ${algorithm}`,
      ipAddress: getClientIp(req),
      newValue: algorithm,
    });
    
    res.json({ success: true, status: getCryptoStatus() });
  }));

  // Get Ghost API status (active deception technology)
  app.get("/api/resilience/ghost-api", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { getGhostApiStats } = await import("./lib/ghost-api");
    res.json(getGhostApiStats());
  }));

  // Get behavioral biometrics stats
  app.get("/api/resilience/biometrics", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getBiometricsStats } = await import("./lib/behavioral-biometrics");
    res.json(getBiometricsStats());
  }));

  // Submit behavioral telemetry for analysis
  app.post("/api/biometrics/analyze", requireAuth, asyncHandler(async (req, res) => {
    const { keystroke, mouse } = req.body;
    const userId = req.session.userId!;
    const {
      performBehavioralAnalysis,
      updateKeystrokeBaseline,
      updateMouseBaseline
    } = await import("./lib/behavioral-biometrics");
    const { rehydrateBiometricProfile, persistBiometricProfile } =
      await import("./lib/behavioral-biometrics-persistence");

    // Load the durable baseline into the in-memory authority before scoring (survives restart), then
    // mirror the engine-computed baseline back after. Both are server-pinned and never throw.
    await rehydrateBiometricProfile(userId);
    if (keystroke) {
      updateKeystrokeBaseline(userId, keystroke);
    }
    if (mouse) {
      updateMouseBaseline(userId, mouse);
    }

    const analysis = performBehavioralAnalysis(userId, keystroke, mouse);
    await persistBiometricProfile(userId);
    
    if (analysis.requiresStepUp) {
      // ENFORCE (auth-hardening tranche 1): flag the session so the next requireStepUp-gated action
      // demands a fresh second factor. Previously this signal only logged and was never acted on.
      req.session.stepUpDemanded = true;
      await storage.createAuditLog({
        action: "STEP_UP_MFA_TRIGGERED",
        resource: "Behavioral Biometrics",
        userId,
        details: `Behavioral anomaly detected: ${analysis.reason}`,
        ipAddress: getClientIp(req),
      });
    }
    
    res.json(analysis);
  }));

  // Model Drift Monitoring (MLOps Command Center)
  app.get("/api/resilience/model-drift", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getModelDriftStatus } = await import("./lib/model-drift");
    res.json(getModelDriftStatus());
  }));

  // ============ FINANCIAL INFRASTRUCTURE PLATFORM ============

  // KYT (Know Your Transaction) Analysis
  app.post("/api/kyt/analyze", requireAuth, asyncHandler(async (req, res) => {
    const { analyzeTransaction, recordKYTResult, persistKytResultDurable, observeKytPersistCommitFate } = await import("./lib/kyt-engine");
    const result = analyzeTransaction(req.body);
    recordKYTResult(result);
    // VF-S5: durable, tenant-scoped persist on the request connection (awaited,
    // savepoint-contained, fail-closed). Never throws → the score is always
    // returned even if the persist drops/fails. On success, arm the one-shot
    // observer that detects the row being rolled back with the outer request tx.
    const tenantId = (req as any).tenantId as string | undefined;
    const persisted = await persistKytResultDurable(result, req.body, tenantId);
    if (persisted) observeKytPersistCommitFate(res, result, tenantId);
    res.json(result);
  }));

  // KYT Statistics
  app.get("/api/kyt/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getKYTStats } = await import("./lib/kyt-engine");
    res.json(getKYTStats());
  }));

  // ============ DYNAMIC KYT CONFIGURATION (2026-05-23) ============
  // All endpoints are admin-only. The current-config and config-status
  // endpoints are also readable by risk_manager and auditor for read-only
  // verification workflows. Apply/rollback are admin-only to match the
  // spec's "operator-driven only" discipline.

  app.get("/api/kyt/config-status",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (_req, res) => {
      const { getConfigStatus } = await import("./lib/kyt-config-loader");
      res.json(getConfigStatus());
    }),
  );

  app.get("/api/kyt/current-config",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (_req, res) => {
      const { getActiveConfig } = await import("./lib/kyt-config-loader");
      res.json(getActiveConfig());
    }),
  );

  app.post("/api/kyt/validate-config",
    requireRole("admin"),
    asyncHandler(async (req, res) => {
      const { validateCandidate } = await import("./lib/kyt-config-apply");
      // Accept either { candidate: <config> } envelope or the raw config body.
      const candidate = req.body && typeof req.body === "object" && "candidate" in req.body
        ? (req.body as any).candidate
        : req.body;
      const result = validateCandidate(candidate);
      if (result.success) {
        res.json({ valid: true, schema_version: result.parsed.schema_version });
      } else {
        res.status(400).json({ valid: false, errors: result.errors });
      }
    }),
  );

  app.post("/api/kyt/apply-config",
    requireRole("admin"),
    asyncHandler(async (req, res) => {
      const { applyKytConfig } = await import("./lib/kyt-config-apply");
      const body = (req.body || {}) as { candidate?: unknown; reason?: string };
      if (!body.candidate) {
        return res.status(400).json({ success: false, error: "request body must include 'candidate' (the full config object)" });
      }
      // Look up actor identity from session
      const userId = req.session?.userId || null;
      let username = "unknown";
      if (userId) {
        try {
          const user = await storage.getUser(userId);
          if (user) username = user.username;
        } catch { /* fall through with 'unknown' — apply still proceeds, audited */ }
      }
      const result = await applyKytConfig({
        candidate: body.candidate,
        actorUserId: userId,
        actorUsername: username,
        reason: body.reason || "",
        sourceIp: getClientIp(req),
      });
      if (!result.success) {
        return res.status(400).json(result);
      }
      res.json(result);
    }),
  );

  app.post("/api/kyt/rollback-config",
    requireRole("admin"),
    asyncHandler(async (req, res) => {
      const { rollbackKytConfig } = await import("./lib/kyt-config-apply");
      const body = (req.body || {}) as { steps?: number; reason?: string };
      const userId = req.session?.userId || null;
      let username = "unknown";
      if (userId) {
        try {
          const user = await storage.getUser(userId);
          if (user) username = user.username;
        } catch { /* fall through */ }
      }
      const result = await rollbackKytConfig({
        steps: body.steps ?? 1,
        actorUserId: userId,
        actorUsername: username,
        reason: body.reason || "",
        sourceIp: getClientIp(req),
      });
      if (!result.success) {
        return res.status(400).json(result);
      }
      res.json(result);
    }),
  );

  // Recent KYT_CONFIG_* audit events joined to their audit_chain_entries rows
  // so the response carries the spec's previous_event_hash / this_event_hash /
  // chain_position fields without a schema change (Deviation 3). Replaces the
  // original runbook's `docker compose exec app psql ...` step which was
  // unworkable because the node:20-alpine image does not ship psql.
  app.get("/api/kyt/recent-config-changes",
    requireRole("admin", "risk_manager", "auditor"),
    asyncHandler(async (req, res) => {
      const limit = Math.min(Math.max(parseInt(String(req.query.limit ?? "20"), 10) || 20, 1), 200);
      const { db } = await import("./db");
      const { auditLogs, auditChainEntries } = await import("@shared/schema");
      const { eq, or, desc, inArray } = await import("drizzle-orm");

      const rows = await db
        .select({
          event_id: auditLogs.id,
          timestamp: auditLogs.timestamp,
          event_type: auditLogs.action,
          actor_user_id: auditLogs.userId,
          source_ip: auditLogs.ipAddress,
          details: auditLogs.details,
          this_event_hash: auditChainEntries.hash,
          previous_event_hash: auditChainEntries.previousHash,
          chain_position: auditChainEntries.id,
        })
        .from(auditLogs)
        .leftJoin(auditChainEntries, eq(auditChainEntries.sourceAuditId, auditLogs.id))
        .where(inArray(auditLogs.action, ["KYT_CONFIG_CHANGE", "KYT_CONFIG_ROLLBACK", "KYT_CONFIG_RELOADED"]))
        .orderBy(desc(auditLogs.timestamp))
        .limit(limit);

      const result = rows.map((r) => {
        let parsedDetails: any = null;
        try { parsedDetails = r.details ? JSON.parse(r.details) : null; } catch { /* leave null */ }
        return {
          event_id: r.event_id,
          timestamp: r.timestamp,
          event_type: r.event_type,
          actor: parsedDetails?.actor ?? { user_id: r.actor_user_id, source_ip: r.source_ip },
          change: parsedDetails?.change ?? null,
          context: parsedDetails?.context ?? null,
          rolled_back_from_event_id: parsedDetails?.rolled_back_from_event_id ?? null,
          integrity: {
            previous_event_hash: r.previous_event_hash,
            this_event_hash: r.this_event_hash,
            chain_position: r.chain_position,
          },
        };
      });

      res.json(result);
    }),
  );

  // Agentic Commerce - Validate Agent Transaction
  app.post("/api/agents/validate", requireAuth, asyncHandler(async (req, res) => {
    const { validateAgentTransaction } = await import("./lib/agentic-commerce");
    const result = validateAgentTransaction(req.body);
    
    if (result.recursiveLoopDetected) {
      await storage.createAuditLog({
        action: "RECURSIVE_LOOP_DETECTED",
        resource: `Agent: ${result.agentId}`,
        userId: req.session.userId!,
        details: `Recursive spend loop detected: ${result.riskFlags.join(", ")}`,
        ipAddress: getClientIp(req),
      });
    }
    
    res.json(result);
  }));

  // Agentic Commerce Stats
  app.get("/api/agents/stats", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getAgentStats } = await import("./lib/agentic-commerce");
    res.json(getAgentStats());
  }));

  // SupTech Gateway - Generate Threat Summary Report
  app.post("/api/suptech/report/threat-summary", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { generateThreatSummaryReport } = await import("./lib/suptech-gateway");
    const { threatCount, neutralizedCount, topThreatTypes, avgResponseTime } = req.body;
    const report = generateThreatSummaryReport(threatCount, neutralizedCount, topThreatTypes, avgResponseTime);
    res.json(report);
  }));

  // SupTech Gateway Stats & DORA Compliance
  app.get("/api/suptech/status", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const { getSupTechStats, getDoraComplianceStatus } = await import("./lib/suptech-gateway");
    res.json({
      gateway: getSupTechStats(),
      dora: getDoraComplianceStatus()
    });
  }));

  // Submit Report to Regulator
  app.post("/api/suptech/submit/:reportId", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { submitToRegulator } = await import("./lib/suptech-gateway");
    const result = await submitToRegulator(String(req.params.reportId));
    
    if (result.success) {
      await storage.createAuditLog({
        action: "REGULATORY_REPORT_SUBMITTED",
        resource: `Report: ${req.params.reportId}`,
        userId: req.session.userId!,
        details: result.message,
        ipAddress: getClientIp(req),
      });
    }
    
    res.json(result);
  }));

  // ============ eBPF EDR / SIEM / APT DETECTION ============

  // APT_MAKE_REAL Layer 1 — these read REAL ingested telemetry (edr_events/edr_endpoints), not the
  // former synthetic arrays. Honest-empty until a bank's SIEM/syslog forwarder pushes events.
  app.get("/api/edr/dashboard", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const { getEdrRealStats } = await import("./lib/edr-ingest");
    res.json(await getEdrRealStats(tenantId));
  }));

  // REAL telemetry ingestion — a bank's SIEM/syslog forwarder (or agent) pushes normalized events.
  // First increment: operator/service-authenticated (admin/risk_manager) + tenant-scoped. NOTE:
  // machine-to-machine per-tenant API-key auth for the bank's forwarder is the immediate follow-on.
  app.post("/api/edr/ingest", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const parsed = z
      .object({
        source: z.enum(["siem", "syslog", "agent", "cef"]).optional(),
        eventType: z.string().trim().min(1).max(256),
        severity: z.enum(["critical", "high", "medium", "low", "info"]).optional(),
        message: z.string().trim().min(1).max(4000),
        hostname: z.string().trim().min(1).max(256).optional(),
        ipAddress: z.string().trim().max(64).optional(),
        os: z.string().trim().max(128).optional(),
        observedAt: z.string().datetime().optional(),
        raw: z.unknown().optional(),
      })
      .strict()
      .safeParse(req.body ?? {});
    if (!parsed.success) {
      return res.status(400).json(createErrorResponse("AEGIS_ERR_100", { validation: "edr_ingest" }, (req as any).traceId));
    }
    const { ingestEdrEvent } = await import("./lib/edr-ingest");
    const ev = await ingestEdrEvent({
      tenantId,
      source: parsed.data.source ?? "siem",
      eventType: parsed.data.eventType,
      severity: parsed.data.severity,
      message: parsed.data.message,
      hostname: parsed.data.hostname,
      ipAddress: parsed.data.ipAddress,
      os: parsed.data.os,
      observedAt: parsed.data.observedAt,
      rawJson: parsed.data.raw,
    });
    return res.status(201).json({ ingested: true, eventId: ev.id });
  }));

  app.get("/api/edr/endpoints", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const { listEdrEndpoints } = await import("./lib/edr-ingest");
    res.json(await listEdrEndpoints(tenantId));
  }));

  app.post("/api/edr/endpoints/:id/isolate", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const { requestEdrIsolation } = await import("./lib/edr/isolation");
    const action = req.body?.action === "release" ? "release" : "isolate";
    const detail = typeof req.body?.detail === "string" ? req.body.detail.slice(0, 500) : undefined;
    const row = await requestEdrIsolation(tenantId, String(req.params.id), action, req.session.userId ?? null, detail);
    if (!row) return res.status(404).json({ error: "Endpoint not found" });
    await storage.createAuditLog({
      action: action === "release" ? "ENDPOINT_ISOLATION_RELEASE_REQUESTED" : "ENDPOINT_ISOLATION_REQUESTED",
      resource: `Endpoint: ${req.params.id}`,
      userId: req.session.userId!,
      details: `SIMULATED ${action} recorded (NOT executed — no on-host agent effector). action id ${row.id}`,
      ipAddress: getClientIp(req),
    });
    // Honest response: recorded + simulated, never a fake "isolated" success.
    res.status(201).json({ recorded: true, simulated: true, executed: false, action: row });
  }));

  app.get("/api/edr/isolation-actions", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const { listEdrIsolationActions } = await import("./lib/edr/isolation");
    const limit = parseInt(req.query.limit as string) || 100;
    res.json(await listEdrIsolationActions(tenantId, { limit }));
  }));

  app.get("/api/edr/probes", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getProbes } = await import("./lib/ebpf-edr");
    res.json(getProbes());
  }));

  app.post("/api/edr/probes/:id/toggle", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { toggleProbe } = await import("./lib/ebpf-edr");
    res.json(toggleProbe(String(req.params.id)));
  }));

  app.get("/api/edr/events", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const { listEdrEvents } = await import("./lib/edr-ingest");
    const limit = parseInt(req.query.limit as string) || 100;
    res.json(await listEdrEvents(tenantId, { limit }));
  }));

  app.get("/api/edr/alerts", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const { listEdrAlerts } = await import("./lib/edr/detection");
    const limit = parseInt(req.query.limit as string) || 100;
    res.json(await listEdrAlerts(tenantId, { limit }));
  }));

  app.get("/api/edr/campaigns", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getAptCampaigns } = await import("./lib/ebpf-edr");
    res.json(getAptCampaigns());
  }));

  app.post("/api/edr/campaigns/:id/status", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { updateCampaignStatus } = await import("./lib/ebpf-edr");
    const { status } = req.body;
    const result = updateCampaignStatus(String(req.params.id), status);
    if (result.success) {
      await storage.createAuditLog({
        action: "APT_CAMPAIGN_STATUS_UPDATED",
        resource: `Campaign: ${req.params.id}`,
        userId: req.session.userId!,
        details: result.message,
        ipAddress: getClientIp(req),
      });
    }
    res.json(result);
  }));

  app.get("/api/edr/siem-events", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getSiemEvents } = await import("./lib/ebpf-edr");
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(getSiemEvents(limit));
  }));

  app.get("/api/edr/central-bank-alerts", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getCentralBankAlerts } = await import("./lib/ebpf-edr");
    res.json(getCentralBankAlerts());
  }));

  app.post("/api/edr/central-bank-alerts/:id/acknowledge", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { acknowledgeCentralBankAlert } = await import("./lib/ebpf-edr");
    const result = acknowledgeCentralBankAlert(String(req.params.id));
    if (result.success) {
      await storage.createAuditLog({
        action: "CENTRAL_BANK_ALERT_ACKNOWLEDGED",
        resource: `Alert: ${req.params.id}`,
        userId: req.session.userId!,
        details: result.message,
        ipAddress: getClientIp(req),
      });
    }
    res.json(result);
  }));

  app.get("/api/edr/correlations", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { correlateCentralBankAlerts } = await import("./lib/ebpf-edr");
    res.json(await correlateCentralBankAlerts());
  }));

  app.get("/api/edr/mitre-matrix", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved" });
    const { getEdrMitreMatrix } = await import("./lib/edr/detection");
    res.json(await getEdrMitreMatrix(tenantId));
  }));

  app.get("/api/edr/timing-protection", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { getTimingSideChannelStatus } = await import("./lib/ebpf-edr");
    res.json(getTimingSideChannelStatus());
  }));

  app.post("/api/edr/timing-protection/constant-time", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { toggleConstantTimeOps } = await import("./lib/ebpf-edr");
    const { enabled } = req.body;
    toggleConstantTimeOps(enabled);
    res.json({ success: true, constantTimeOps: enabled });
  }));

  app.post("/api/edr/timing-protection/traffic-padding", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { toggleTrafficPadding } = await import("./lib/ebpf-edr");
    const { enabled } = req.body;
    toggleTrafficPadding(enabled);
    res.json({ success: true, trafficPadding: enabled });
  }));

  // ============ INTERACTION DNA / BEHAVIORAL BIOMETRICS ============

  // Telemetry endpoint for continuous trust scoring (Interaction DNA)
  app.post("/api/resilience/biometrics/telemetry", requireAuth, asyncHandler(async (req, res) => {
    const { updateKeystrokeBaseline, updateMouseBaseline } = await import("./lib/behavioral-biometrics");
    const { rehydrateBiometricProfile, persistBiometricProfile } =
      await import("./lib/behavioral-biometrics-persistence");
    const { keystrokes, mouse, sessionId } = req.body;
    const userId = req.session.userId!;

    // Rehydrate the durable baseline into the in-memory authority (replaces the old initializeProfile —
    // updateKeystrokeBaseline/updateMouseBaseline self-initialize an absent profile). Persist after.
    await rehydrateBiometricProfile(userId);
    
    if (keystrokes && keystrokes.length > 0) {
      // Compute REAL dwell/flight times from the client-supplied keystroke
      // timestamps (`time` = performance.now() ms, `type` = "down"|"up"),
      // sent by the Interaction-DNA hook (client/src/hooks/use-interaction-dna.ts).
      // Previously these were FABRICATED via Math.random — removed (2026-06-30).
      //  - Dwell time: per key, the gap between its "down" and the next matching
      //    "up" for the same key.
      //  - Flight time: gap between consecutive "down" presses.
      type KE = { key?: string; time?: number; type?: string };
      const events: KE[] = (keystrokes as KE[])
        .filter((k) => typeof k.time === "number")
        .slice()
        .sort((a, b) => (a.time! - b.time!));

      const dwellTimes: number[] = [];
      const pendingDowns = new Map<string, number>(); // key -> last down time
      for (const e of events) {
        const k = e.key ?? "*";
        if (e.type === "down") {
          pendingDowns.set(k, e.time!);
        } else if (e.type === "up") {
          const downTime = pendingDowns.get(k);
          if (downTime !== undefined) {
            const dwell = e.time! - downTime;
            if (dwell >= 0 && dwell < 5000) dwellTimes.push(dwell); // guard against clock jumps
            pendingDowns.delete(k);
          }
        }
      }

      const downTimes = events.filter((e) => e.type === "down").map((e) => e.time!);
      const flightTimes: number[] = [];
      for (let i = 1; i < downTimes.length; i++) {
        const flight = downTimes[i] - downTimes[i - 1];
        if (flight >= 0 && flight < 10000) flightTimes.push(flight); // guard against idle gaps/clock jumps
      }

      const backspaceCount = keystrokes.filter((k: { key?: string }) => k.key === "Backspace" || k.key === "Delete").length;
      const keyCount = keystrokes.length;
      const avgDwellTime = dwellTimes.length > 0 ? dwellTimes.reduce((a: number, b: number) => a + b, 0) / dwellTimes.length : 75;
      const avgFlightTime = flightTimes.length > 0 ? flightTimes.reduce((a: number, b: number) => a + b, 0) / flightTimes.length : 150;
      const cycleTimeMs = avgDwellTime + avgFlightTime;
      const typingSpeed = cycleTimeMs > 0 ? 60000 / cycleTimeMs : 240; // keys/min

      updateKeystrokeBaseline(userId, {
        keyCount,
        avgDwellTime,
        avgFlightTime,
        typingSpeed,
        backspaceRatio: keyCount > 0 ? backspaceCount / keyCount : 0,
        timestamp: Date.now(),
      });
    }
    
    if (mouse && mouse.length > 1) {
      const velocities: number[] = [];
      let straightSegments = 0;
      let totalSegments = 0;
      for (let i = 1; i < mouse.length; i++) {
        const dx = mouse[i].x - mouse[i-1].x;
        const dy = mouse[i].y - mouse[i-1].y;
        const dt = mouse[i].t - mouse[i-1].t;
        if (dt > 0) {
          velocities.push(Math.sqrt(dx*dx + dy*dy) / dt);
        }
        if (i >= 2) {
          totalSegments++;
          const prevDx = mouse[i-1].x - mouse[i-2].x;
          const prevDy = mouse[i-1].y - mouse[i-2].y;
          const dot = dx*prevDx + dy*prevDy;
          const magCurr = Math.sqrt(dx*dx + dy*dy);
          const magPrev = Math.sqrt(prevDx*prevDx + prevDy*prevDy);
          if (magCurr > 0 && magPrev > 0 && (dot / (magCurr * magPrev)) > 0.95) {
            straightSegments++;
          }
        }
      }
      
      const avgVelocity = velocities.length > 0 ? velocities.reduce((a, b) => a + b, 0) / velocities.length : 0.5;
      const jitter = velocities.length > 1 
        ? Math.sqrt(velocities.map(v => Math.pow(v - avgVelocity, 2)).reduce((a, b) => a + b, 0) / velocities.length) 
        : 0.1;
      const clickCount = mouse.filter((m: { type?: string }) => m.type === "click" || m.type === "mousedown").length;
      const scrollPatterns = mouse.filter((m: { type?: string }) => m.type === "scroll" || m.type === "wheel").length;
      const straightLineRatio = totalSegments > 0 ? straightSegments / totalSegments : 0.5;
      
      updateMouseBaseline(userId, {
        avgVelocity,
        avgJitter: jitter,
        clickCount,
        scrollPatterns,
        straightLineRatio,
        timestamp: Date.now(),
      });
    }
    
    await persistBiometricProfile(userId);
    res.json({ received: true, sessionId });
  }));

  // ============ EXECUTIVE RESILIENCE REPORT ============

  // Generate Executive Report (CISO Dashboard)
  app.get("/api/executive/report", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { generateExecutiveReport } = await import("./lib/executive-report");
    const entityName = req.query.entity as string || "[Deploying Institution]";
    const sovereignNode = req.query.node as string || "Kampala HQ-01";
    const report = generateExecutiveReport(entityName, sovereignNode);
    res.json(report);
  }));

  // Generate Executive Report as formatted text
  app.get("/api/executive/report/text", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { generateExecutiveReport, formatReportAsText } = await import("./lib/executive-report");
    const entityName = req.query.entity as string || "[Deploying Institution]";
    const sovereignNode = req.query.node as string || "Kampala HQ-01";
    const report = generateExecutiveReport(entityName, sovereignNode);
    const textReport = formatReportAsText(report);
    res.type("text/plain").send(textReport);
  }));

  // ============ IT HANDOVER DOCUMENTATION ============

  // Serve IT Handover Suite documentation
  app.get("/api/docs/handover", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const fs = await import("fs/promises");
    const path = await import("path");
    const docPath = path.join(process.cwd(), "docs", "AEGIS_IT_HANDOVER_SUITE.md");
    const content = await fs.readFile(docPath, "utf-8");
    res.type("text/markdown").send(content);
  }));

  // Get system architecture summary
  app.get("/api/docs/architecture", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { getCryptoStatus } = await import("./lib/crypto-agility");
    const { aiCircuitBreaker, cbsCircuitBreaker } = await import("./lib/circuit-breaker");
    const { getFallbackStatus } = await import("./lib/static-fallback");
    const { getGhostApiStats } = await import("./lib/ghost-api");
    const { getBiometricsStats } = await import("./lib/behavioral-biometrics");
    const { getModelDriftStatus } = await import("./lib/model-drift");
    const { getKYTStats } = await import("./lib/kyt-engine");
    const { getAgentStats } = await import("./lib/agentic-commerce");
    const { getSupTechStats, getDoraComplianceStatus } = await import("./lib/suptech-gateway");

    res.json({
      platform: "AEGIS CYBER",
      version: "4.2.1",
      deploymentType: "Sovereign Node",
      location: "Kampala HQ-01",
      components: {
        sentinelAI: {
          status: "ACTIVE",
          modelVersion: getModelDriftStatus().champion.modelVersion,
          driftMonitoring: false // model-drift is NOT_ASSESSED — no live ML drift monitor wired (Tier-3 2026-07-05)
        },
        circuitBreakers: {
          ai: aiCircuitBreaker.getStats(),
          cbs: cbsCircuitBreaker.getStats()
        },
        staticFallback: getFallbackStatus(),
        cryptoAgility: getCryptoStatus(),
        ghostAPI: getGhostApiStats(),
        bioVault: getBiometricsStats(),
        kytEngine: getKYTStats(),
        agenticCommerce: getAgentStats(),
        supTechGateway: getSupTechStats(),
        doraCompliance: getDoraComplianceStatus()
      },
      integrations: {
        cbs: ["Finacle", "T24", "FLEXCUBE"],
        regulatory: ["BOU-SOC", "PDPO-UG", "EAC-FSCC"]
      },
      sla: {
        uptime: "99.999%",
        inferenceLatency: "<200ms",
        threatDetection: "<500ms",
        sessionIsolation: "<100ms"
      }
    });
  }));

  // ============ TRAINING MODE (3-Day Workshop) ============

  // Approve challenger model (Champion-Challenger swap)
  app.post("/api/resilience/model-drift/approve", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { approveChallenger } = await import("./lib/model-drift");
    const result = approveChallenger(req.session.userId!);
    
    if (result.success) {
      await storage.createAuditLog({
        action: "MODEL_PROMOTED",
        resource: "AI Model",
        userId: req.session.userId!,
        details: result.message,
        ipAddress: getClientIp(req),
      });
    }
    
    res.json(result);
  }));

  // Reject challenger model
  app.post("/api/resilience/model-drift/reject", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { reason } = req.body;
    const { rejectChallenger } = await import("./lib/model-drift");
    const result = rejectChallenger(req.session.userId!, reason || "Manual rejection");
    
    if (result.success) {
      await storage.createAuditLog({
        action: "MODEL_REJECTED",
        resource: "AI Model",
        userId: req.session.userId!,
        details: result.message,
        ipAddress: getClientIp(req),
      });
    }
    
    res.json(result);
  }));

  // ============================================
  // COMMERCIAL-GRADE FEATURES API ROUTES
  // ============================================

  // --- Priority 1: Revenue-Critical ---

  // Transaction Scoring Dashboard
  app.get("/api/commercial/transaction-scoring/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getTransactionStats, getRecentScores, getFraudPreventionSummary } = await import("./lib/transaction-scoring");
    res.json({
      stats: getTransactionStats(),
      recentScores: getRecentScores(20),
      summary: getFraudPreventionSummary(),
    });
  }));

  app.post("/api/commercial/transaction-scoring/score", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { scoreTransaction } = await import("./lib/transaction-scoring");
    // Production-honesty: score a REAL caller-provided transaction only — never fabricate one to fill
    // the gap (that silently substituted a fake transaction + risk score as real scored activity).
    const raw = req.body.transaction;
    if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
      return res.status(400).json({ error: "A real transaction object is required in { transaction }. This endpoint scores real transactions and does not generate one." });
    }
    // JSON delivers timestamp as a string; the scorer needs a real Date (getHours). Coerce it here so
    // the real path works on real input (previously masked by the removed synthetic-transaction fallback).
    const transaction = { ...raw, timestamp: raw.timestamp ? new Date(raw.timestamp) : new Date() };
    const result = scoreTransaction(transaction);
    res.json(result);
  }));

  // POST /api/commercial/transaction-scoring/simulate REMOVED (production-honesty): it fabricated
  // batches of random transactions and persisted their scores into the live dashboard as real activity.

  // Fraud Loss Prevention Calculator
  app.get("/api/commercial/fraud-calculator/dashboard", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getFraudDashboard, calculateROISummary } = await import("./lib/fraud-calculator");
    // HONESTY (CF-3 2026-07-02): this is an ILLUSTRATIVE fraud-prevention ROI calculator — the figures
    // are synthetic what-if estimates, NOT measured fraud data (the render already labels it SIMULATED).
    // Stamp simulated:true on the PAYLOAD so the synthetic nature travels with the data at the API layer
    // (closes the falsePositiveRate gap: honest render but silent API). Output is contained to this
    // endpoint — verified not persisted and not consumed by any other module or decision path.
    res.json({
      simulated: true,
      note: "Illustrative model — figures are synthetic what-if estimates, NOT measured fraud data.",
      dashboard: getFraudDashboard(),
      roiSummary: calculateROISummary(),
    });
  }));

  // Multi-Tenant tenant routes REMOVED (commercial-completion pass 2026-07-03): they served
  // fabricated named-bank tenants (Centenary/Stanbic) from lib/multi-tenant.ts (also deleted).
  // Sovereign-per-bank = one tenant per deploy; multi-tenant management is meaningless here.
  // The REAL per-request RLS plumbing (tenant-context/tenant-middleware) is unaffected.

  // White-Label Branding - Requires authentication for security
  // Gate C IDOR fix: white-label branding is an in-memory multi-tenant map (NO RLS backstop),
  // keyed by the :tenantId path param. A tenant-scoped admin could read/write ANOTHER tenant's
  // branding by changing the param. assertBrandingOwnership requires the param to match the
  // caller's own session tenant — unless they are a GLOBAL platform admin (who legitimately
  // administers any tenant). Returns true if allowed; writes 403 and returns false otherwise.
  const assertBrandingOwnership = async (req: any, res: any): Promise<boolean> => {
    const sessionTenant = String(req.tenantId ?? "");
    const paramTenant = String(req.params.tenantId);
    if (paramTenant === sessionTenant && sessionTenant !== "") return true;
    const u = req.session?.userId ? await storage.getUser(req.session.userId) : null;
    if (u && u.role === "admin") return true; // global platform admin
    res.status(403).json({ error: "Forbidden: branding is scoped to your own tenant" });
    return false;
  };

  // Gate-B re-run (2026-06-25) generalization of assertBrandingOwnership: the same in-memory /
  // RLS-exempt IDOR class recurs on several routes keyed by a caller-supplied tenant id (path or
  // query) — whitelabel, saas playbook executions, alerting, finops budgets, billing. This guard
  // takes the supplied tenant value explicitly and requires it to match the caller's own session
  // tenant, unless they are a GLOBAL platform admin. Returns true if allowed; 403s otherwise.
  const assertTenantOwnership = async (req: any, res: any, suppliedTenantId: string): Promise<boolean> => {
    const sessionTenant = String(req.tenantId ?? "");
    if (String(suppliedTenantId) === sessionTenant && sessionTenant !== "") return true;
    const u = req.session?.userId ? await storage.getUser(req.session.userId) : null;
    if (u && u.role === "admin") return true; // global platform admin
    res.status(403).json({ error: "Forbidden: this resource is scoped to your own tenant" });
    return false;
  };

  app.get("/api/commercial/branding/:tenantId", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    if (!(await assertBrandingOwnership(req, res))) return;
    const { getWhiteLabelAssets, getBranding } = await import("./lib/white-label");
    res.json({
      assets: getWhiteLabelAssets(String(req.params.tenantId)),
      config: getBranding(String(req.params.tenantId)),
    });
  }));

  app.put("/api/commercial/branding/:tenantId", requireRole("admin"), asyncHandler(async (req, res) => {
    if (!(await assertBrandingOwnership(req, res))) return;
    const { setBranding } = await import("./lib/white-label");
    const result = setBranding(String(req.params.tenantId), req.body);
    res.json(result);
  }));

  // --- Priority 2: Compliance & Audit ---

  // PDPO Breach Notification
  app.get("/api/commercial/breaches", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getAllBreaches, getBreachStats } = await import("./lib/pdpo-breach");
    res.json({
      breaches: getAllBreaches(),
      stats: getBreachStats(),
    });
  }));

  // /breaches/templates (literal) MUST register before /breaches/:id (param) — otherwise the :id
  // route catches "templates" as an id and 404s the literal. Literal-before-param, 2026-07-26.
  app.get("/api/commercial/breaches/templates", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getAllTemplates } = await import("./lib/pdpo-breach");
    res.json(getAllTemplates());
  }));

  app.get("/api/commercial/breaches/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getBreach } = await import("./lib/pdpo-breach");
    const breach = getBreach(String(req.params.id));
    if (!breach) {
      return res.status(404).json({ error: "Breach not found" });
    }
    res.json(breach);
  }));

  app.post("/api/commercial/breaches", requireRole("admin"), asyncHandler(async (req, res) => {
    const { createBreach } = await import("./lib/pdpo-breach");
    const { breachType, severity, description, affectedDataSubjects, affectedRecords, tenantId } = req.body;
    if (!breachType || !severity || !description || affectedDataSubjects === undefined || affectedRecords === undefined) {
      return res.status(400).json({ error: "Missing required fields: breachType, severity, description, affectedDataSubjects, affectedRecords" });
    }
    const breach = createBreach({ breachType, severity, description, affectedDataSubjects, affectedRecords, tenantId });
    await storage.createAuditLog({
      action: "BREACH_CREATED",
      resource: `Breach: ${breach.id}`,
      userId: req.session.userId!,
      details: `Breach notification created: ${breach.description}`,
      ipAddress: getClientIp(req),
    });
    res.json(breach);
  }));

  app.put("/api/commercial/breaches/:id/status", requireRole("admin"), asyncHandler(async (req, res) => {
    const { updateBreachStatus } = await import("./lib/pdpo-breach");
    const user = await storage.getUser(req.session.userId!);
    const breach = updateBreachStatus(String(req.params.id), req.body.status, user?.username || "Unknown", req.body.details);
    if (!breach) {
      return res.status(404).json({ error: "Breach not found" });
    }
    res.json(breach);
  }));

  // PCI-DSS Logging
  app.get("/api/commercial/pci-logs", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { getPCILogs, getPCIComplianceScore } = await import("./lib/pci-logging");
    const logs = getPCILogs({
      limit: parseInt(req.query.limit as string) || 100,
      minRiskScore: req.query.minRisk ? parseFloat(req.query.minRisk as string) : undefined,
    });
    res.json({
      logs,
      complianceScore: getPCIComplianceScore(),
    });
  }));

  app.post("/api/commercial/pci-logs/report", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { generatePCIAuditReport } = await import("./lib/pci-logging");
    const startDate = new Date(req.body.startDate || Date.now() - 30 * 24 * 60 * 60 * 1000);
    const endDate = new Date(req.body.endDate || Date.now());
    const report = generatePCIAuditReport(startDate, endDate);
    res.json(report);
  }));

  // Data Retention Policy Engine
  app.get("/api/commercial/retention/dashboard", requireRole("admin"), asyncHandler(async (req, res) => {
    const { getRetentionDashboard } = await import("./lib/data-retention");
    res.json(await getRetentionDashboard());
  }));

  app.get("/api/commercial/retention/policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { getAllPolicies, getDataInventory } = await import("./lib/data-retention");
    const inventory = await getDataInventory();
    res.json({
      policies: getAllPolicies(),
      inventory,
    });
  }));

  app.post("/api/commercial/retention/policies/:id/execute", requireRole("admin"), asyncHandler(async (req, res) => {
    const { executePolicy } = await import("./lib/data-retention");
    const result = executePolicy(String(req.params.id));
    await storage.createAuditLog({
      action: "RETENTION_EXECUTED",
      resource: `Policy: ${result.policyName}`,
      userId: req.session.userId!,
      details: `Processed ${result.recordsProcessed} records, archived ${result.recordsArchived}, deleted ${result.recordsDeleted}`,
      ipAddress: getClientIp(req),
    });
    res.json(result);
  }));

  // SOC 2 Evidence Collection
  app.get("/api/commercial/soc2/dashboard", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { getSOC2Dashboard } = await import("./lib/soc2-evidence");
    res.json(await getSOC2Dashboard((req as any).tenantId));
  }));

  app.get("/api/commercial/soc2/controls", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { getAllControls, getControlsByCategory } = await import("./lib/soc2-evidence");
    const category = req.query.category as string;
    res.json(category ? await getControlsByCategory((req as any).tenantId, category as any) : await getAllControls((req as any).tenantId));
  }));

  app.post("/api/commercial/soc2/evidence/collect", requireRole("admin"), asyncHandler(async (req, res) => {
    const { autoCollectEvidence } = await import("./lib/soc2-evidence");
    const evidence = autoCollectEvidence();
    await storage.createAuditLog({
      action: "SOC2_EVIDENCE_COLLECTED",
      resource: "SOC 2 Compliance",
      userId: req.session.userId!,
      details: `Auto-collected ${evidence.length} evidence artifacts`,
      ipAddress: getClientIp(req),
    });
    res.json(evidence);
  }));

  app.post("/api/commercial/soc2/report", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { generateSOC2Report } = await import("./lib/soc2-evidence");
    const user = await storage.getUser(req.session.userId!);
    const startDate = new Date(req.body.startDate || Date.now() - 365 * 24 * 60 * 60 * 1000);
    const endDate = new Date(req.body.endDate || Date.now());
    const report = await generateSOC2Report(startDate, endDate, user?.username || "Unknown", (req as any).tenantId);
    res.json(report);
  }));

  // --- Priority 3: Operational Excellence ---

  // Alert Fatigue Management
  app.get("/api/commercial/alerts", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getAlerts, getAlertGroups, getAlertFatigueStats } = await import("./lib/alert-fatigue");
    res.json({
      alerts: getAlerts({ limit: 50 }),
      groups: getAlertGroups("ACTIVE"),
      stats: getAlertFatigueStats(),
    });
  }));

  app.post("/api/commercial/alerts/:id/acknowledge", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { acknowledgeAlert } = await import("./lib/alert-fatigue");
    const alert = acknowledgeAlert(String(req.params.id), req.session.userId!);
    if (!alert) {
      return res.status(404).json({ error: "Alert not found" });
    }
    res.json(alert);
  }));

  app.post("/api/commercial/alerts/:id/resolve", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { resolveAlert } = await import("./lib/alert-fatigue");
    const alert = resolveAlert(String(req.params.id));
    if (!alert) {
      return res.status(404).json({ error: "Alert not found" });
    }
    res.json(alert);
  }));

  app.post("/api/commercial/alert-groups/:id/resolve", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { resolveAlertGroup } = await import("./lib/alert-fatigue");
    const group = resolveAlertGroup(String(req.params.id));
    if (!group) {
      return res.status(404).json({ error: "Alert group not found" });
    }
    res.json(group);
  }));

  app.get("/api/commercial/alerts/suppression-rules", requireRole("admin"), asyncHandler(async (req, res) => {
    const { getSuppressionRules } = await import("./lib/alert-fatigue");
    res.json(getSuppressionRules());
  }));

  // Shift Handover Reports
  app.get("/api/commercial/handovers", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getHandovers, getShiftMetrics, getCurrentShiftType } = await import("./lib/shift-handover");
    res.json({
      handovers: await getHandovers({ limit: 20 }),
      metrics: await getShiftMetrics(7),
      currentShift: getCurrentShiftType(),
    });
  }));

  app.get("/api/commercial/handovers/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getHandover, getHandoverReport } = await import("./lib/shift-handover");
    const handover = await getHandover(String(req.params.id));
    if (!handover) {
      return res.status(404).json({ error: "Handover not found" });
    }
    res.json({
      handover,
      report: await getHandoverReport(String(req.params.id)),
    });
  }));

  app.post("/api/commercial/handovers", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { createHandover } = await import("./lib/shift-handover");
    const user = await storage.getUser(req.session.userId!);
    const handover = await createHandover({
      shiftType: req.body.shiftType,
      outgoingAnalyst: user?.fullName || user?.username || "Unknown",
      notes: req.body.notes,
    });
    res.json(handover);
  }));

  app.post("/api/commercial/handovers/:id/submit", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { submitHandover } = await import("./lib/shift-handover");
    const handover = await submitHandover(String(req.params.id));
    if (!handover) {
      return res.status(404).json({ error: "Handover not found" });
    }
    res.json(handover);
  }));

  app.post("/api/commercial/handovers/:id/acknowledge", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { acknowledgeHandover } = await import("./lib/shift-handover");
    const user = await storage.getUser(req.session.userId!);
    const handover = await acknowledgeHandover(
      String(req.params.id),
      user?.fullName || user?.username || "Unknown",
      req.body.comments
    );
    if (!handover) {
      return res.status(404).json({ error: "Handover not found" });
    }
    res.json(handover);
  }));

  // SLA Breach Predictions
  app.get("/api/commercial/sla/dashboard", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getSLAMetrics, getAtRiskTickets } = await import("./lib/sla-prediction");
    res.json({
      metrics: getSLAMetrics(30),
      atRiskTickets: getAtRiskTickets(0.5),
    });
  }));

  app.get("/api/commercial/sla/tickets", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getTickets } = await import("./lib/sla-prediction");
    res.json(getTickets({
      limit: parseInt(req.query.limit as string) || 50,
      atRisk: req.query.atRisk === "true",
    }));
  }));

  app.get("/api/commercial/sla/tickets/:id/prediction", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getPrediction } = await import("./lib/sla-prediction");
    const prediction = getPrediction(String(req.params.id));
    if (!prediction) {
      return res.status(404).json({ error: "Ticket not found" });
    }
    res.json(prediction);
  }));

  // Incident Timeline Reconstruction
  app.get("/api/commercial/incidents", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getIncidents } = await import("./lib/incident-timeline");
    res.json(getIncidents({
      limit: parseInt(req.query.limit as string) || 20,
      severity: req.query.severity as any,
    }));
  }));

  app.get("/api/commercial/incidents/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getIncident, generateAttackChainVisualization, getIncidentReport } = await import("./lib/incident-timeline");
    const incident = getIncident(String(req.params.id));
    if (!incident) {
      return res.status(404).json({ error: "Incident not found" });
    }
    res.json({
      incident,
      visualization: generateAttackChainVisualization(String(req.params.id)),
      report: getIncidentReport(String(req.params.id)),
    });
  }));

  app.post("/api/commercial/incidents", requireRole("admin"), asyncHandler(async (req, res) => {
    const { createIncident } = await import("./lib/incident-timeline");
    const { title, description, severity, attackVector, affectedSystems, assignedTo } = req.body;
    if (!title || !description || !severity || !affectedSystems || !assignedTo) {
      return res.status(400).json({ error: "Missing required fields: title, description, severity, affectedSystems, assignedTo" });
    }
    if (!["LOW", "MEDIUM", "HIGH", "CRITICAL"].includes(severity)) {
      return res.status(400).json({ error: "Invalid severity. Must be LOW, MEDIUM, HIGH, or CRITICAL" });
    }
    const incident = createIncident({ title, description, severity, attackVector, affectedSystems, assignedTo });
    await storage.createAuditLog({
      action: "INCIDENT_CREATED",
      resource: `Incident: ${incident.id}`,
      userId: req.session.userId!,
      details: `Incident created: ${incident.title}`,
      ipAddress: getClientIp(req),
    });
    res.json(incident);
  }));

  app.post("/api/commercial/incidents/:id/timeline", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { addTimelineEvent } = await import("./lib/incident-timeline");
    const event = addTimelineEvent(String(req.params.id), req.body);
    res.json(event);
  }));

  // --- Priority 4: Advanced AI/ML ---

  // Explainable AI Panel
  app.get("/api/commercial/explainable-ai/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getExplainabilityStats } = await import("./lib/explainable-ai");
    res.json(getExplainabilityStats());
  }));

  app.post("/api/commercial/explainable-ai/explain", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { explainDecision } = await import("./lib/explainable-ai");
    const { transactionId, riskScore, decision, transactionData } = req.body;
    const explanation = explainDecision(transactionId, riskScore, decision, transactionData);
    res.json(explanation);
  }));

  app.get("/api/commercial/explainable-ai/:transactionId", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const { getExplanation, generateAuditableExplanation } = await import("./lib/explainable-ai");
    const explanation = getExplanation(String(req.params.transactionId));
    if (!explanation) {
      return res.status(404).json({ error: "Explanation not found" });
    }
    res.json({
      explanation,
      auditReport: generateAuditableExplanation(String(req.params.transactionId)),
    });
  }));

  // Adaptive Thresholds
  app.get("/api/commercial/thresholds/dashboard", requireRole("admin"), asyncHandler(async (req, res) => {
    const { getThresholdDashboard } = await import("./lib/adaptive-thresholds");
    res.json(getThresholdDashboard());
  }));

  app.get("/api/commercial/thresholds", requireRole("admin"), asyncHandler(async (req, res) => {
    const { getAllThresholds } = await import("./lib/adaptive-thresholds");
    res.json(getAllThresholds());
  }));

  app.put("/api/commercial/thresholds/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const { updateThreshold, getThreshold } = await import("./lib/adaptive-thresholds");
    const { value, reason } = req.body;
    if (value === undefined || typeof value !== "number") {
      return res.status(400).json({ error: "Missing required field: value (number)" });
    }
    const existingThreshold = getThreshold(String(req.params.id));
    if (existingThreshold && (value < existingThreshold.minValue || value > existingThreshold.maxValue)) {
      return res.status(400).json({ error: `Value must be between ${existingThreshold.minValue} and ${existingThreshold.maxValue}` });
    }
    const user = await storage.getUser(req.session.userId!);
    const threshold = updateThreshold(
      String(req.params.id),
      value,
      reason || "Manual update",
      user?.username || "ADMIN"
    );
    if (!threshold) {
      return res.status(404).json({ error: "Threshold not found" });
    }
    await storage.createAuditLog({
      action: "THRESHOLD_UPDATED",
      resource: `Threshold: ${threshold.name}`,
      userId: req.session.userId!,
      details: `Updated to ${req.body.value}`,
      ipAddress: getClientIp(req),
      previousValue: String(threshold.history[threshold.history.length - 1]?.previousValue),
      newValue: String(req.body.value),
    });
    res.json(threshold);
  }));

  app.post("/api/commercial/thresholds/auto-tune", requireRole("admin"), asyncHandler(async (req, res) => {
    const { runAutoTune } = await import("./lib/adaptive-thresholds");
    const recommendations = runAutoTune();
    res.json(recommendations);
  }));

  app.post("/api/commercial/thresholds/recommendations/:id/approve", requireRole("admin"), asyncHandler(async (req, res) => {
    const { approveRecommendation, applyRecommendation } = await import("./lib/adaptive-thresholds");
    const user = await storage.getUser(req.session.userId!);
    const approved = approveRecommendation(String(req.params.id), req.body.recommendedValue, user?.username || "Unknown");
    if (!approved) {
      return res.status(404).json({ error: "Recommendation not found or already processed" });
    }
    if (req.body.apply) {
      const threshold = applyRecommendation(String(req.params.id), req.body.recommendedValue);
      return res.json({ approved: true, applied: true, threshold });
    }
    res.json({ approved: true, applied: false });
  }));

  // Graph-Based Entity Resolution
  app.get("/api/commercial/entity-resolution/dashboard", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getEntityResolutionDashboard } = await import("./lib/entity-resolution");
    res.json(await getEntityResolutionDashboard({ tenantId: req.tenantId }));
  }));

  app.get("/api/commercial/entity-resolution/clusters", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getAllClusters } = await import("./lib/entity-resolution");
    res.json(await getAllClusters({ tenantId: req.tenantId }));
  }));

  app.get("/api/commercial/entity-resolution/clusters/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { getCluster, generateGraphVisualization } = await import("./lib/entity-resolution");
    const cluster = await getCluster(String(req.params.id), { tenantId: req.tenantId });
    if (!cluster) {
      return res.status(404).json({ error: "Cluster not found" });
    }
    res.json({
      cluster,
      visualization: await generateGraphVisualization(String(req.params.id), { tenantId: req.tenantId }),
    });
  }));

  app.get("/api/commercial/entity-resolution/entities/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { resolveEntity } = await import("./lib/entity-resolution");
    const result = await resolveEntity(String(req.params.id), { tenantId: req.tenantId });
    if (!result) {
      return res.status(404).json({ error: "Entity not found" });
    }
    res.json(result);
  }));

  app.post("/api/commercial/entity-resolution/detect", requireRole("admin"), asyncHandler(async (req, res) => {
    const { detectClusters } = await import("./lib/entity-resolution");
    const clusters = await detectClusters({ tenantId: req.tenantId });
    await storage.createAuditLog({
      action: "ENTITY_RESOLUTION_RUN",
      resource: "Entity Resolution",
      userId: req.session.userId!,
      details: `Detected ${clusters.length} entity clusters`,
      ipAddress: getClientIp(req),
    });
    res.json(clusters);
  }));

  app.get("/api/commercial/entity-resolution/graph", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { generateGraphVisualization } = await import("./lib/entity-resolution");
    res.json(await generateGraphVisualization(undefined, { tenantId: req.tenantId }));
  }));

  // ============================================
  // SECURITY FEATURES API ROUTES
  // ============================================

  // Two-Factor Authentication Management
  app.post("/api/security/2fa/setup", requireAuth, asyncHandler(async (req, res) => {
    const { initializeTwoFactor } = await import("./lib/two-factor-auth");
    const user = await storage.getUser(req.session.userId!);
    if (!user) {
      return res.status(404).json({ error: "User not found" });
    }
    const setup = await initializeTwoFactor(user.id, user.username);
    await storage.createAuditLog({
      action: "2FA_SETUP_INITIATED",
      resource: "Two-Factor Authentication",
      userId: user.id,
      details: "2FA setup started",
      ipAddress: getClientIp(req),
    });
    res.json(setup);
  }));

  app.post("/api/security/2fa/enable", requireAuth, asyncHandler(async (req, res) => {
    const { enableTwoFactor } = await import("./lib/two-factor-auth");
    const { token } = req.body;
    if (!token) {
      return res.status(400).json({ error: "Token required" });
    }
    const userId = req.session.userId!;
    const success = await enableTwoFactor(userId, token);
    if (success) {
      await storage.createAuditLog({
        action: "2FA_ENABLED",
        resource: "Two-Factor Authentication",
        userId,
        details: "2FA successfully enabled",
        ipAddress: getClientIp(req),
      });
    }
    res.json({ success });
  }));

  app.post("/api/security/2fa/disable", requireAuth, asyncHandler(async (req, res) => {
    const { disableTwoFactor } = await import("./lib/two-factor-auth");
    const userId = req.session.userId!;
    const success = await disableTwoFactor(userId);
    if (success) {
      await storage.createAuditLog({
        action: "2FA_DISABLED",
        resource: "Two-Factor Authentication",
        userId,
        details: "2FA disabled",
        ipAddress: getClientIp(req),
      });
    }
    res.json({ success });
  }));

  app.get("/api/security/2fa/status", requireAuth, asyncHandler(async (req, res) => {
    const { getTwoFactorStatus } = await import("./lib/two-factor-auth");
    const userId = req.session.userId!;
    const status = await getTwoFactorStatus(userId);
    res.json(status || { enabled: false });
  }));

  app.post("/api/security/2fa/backup-codes/regenerate", requireAuth, asyncHandler(async (req, res) => {
    const { regenerateBackupCodes } = await import("./lib/two-factor-auth");
    const userId = req.session.userId!;
    const codes = await regenerateBackupCodes(userId);
    if (codes) {
      await storage.createAuditLog({
        action: "2FA_BACKUP_CODES_REGENERATED",
        resource: "Two-Factor Authentication",
        userId,
        details: "Backup codes regenerated",
        ipAddress: getClientIp(req),
      });
    }
    res.json(codes ? { success: true, backupCodes: codes } : { success: false });
  }));

  // Password Validation
  app.post("/api/security/password/validate", asyncHandler(async (req, res) => {
    const { validatePassword: validatePw, getPasswordStrengthDescription } = await import("./lib/password-policy");
    const { password, username } = req.body;
    if (!password) {
      return res.status(400).json({ error: "Password required" });
    }
    const result = validatePw(password, username);
    res.json({
      ...result,
      strengthDescription: getPasswordStrengthDescription(result.strength),
    });
  }));

  // Security Dashboard
  app.get("/api/security/dashboard", requirePlatformAdmin, asyncHandler(async (req, res) => {
    const { getRateLimitStats, getBlockedIPs } = await import("./lib/rate-limiter");
    const { getLockoutStats, getLockedAccounts } = await import("./lib/account-lockout");
    const { getTwoFactorStats } = await import("./lib/two-factor-auth");
    const { getLoginAnomalyStats } = await import("./lib/login-anomaly");
    
    res.json({
      rateLimiting: await getRateLimitStats(),
      blockedIPs: await getBlockedIPs(),
      accountLockouts: await getLockoutStats(),
      lockedAccounts: await getLockedAccounts(),
      twoFactor: await getTwoFactorStats(),
      loginAnomalies: await getLoginAnomalyStats(),
    });
  }));

  // Admin: Unlock account
  app.post("/api/security/unlock-account", requirePlatformAdmin, asyncHandler(async (req, res) => {
    const { clearLockout } = await import("./lib/account-lockout");
    const { username, ipAddress } = req.body;
    if (!username) {
      return res.status(400).json({ error: "Username required" });
    }
    const success = await clearLockout(username, ipAddress);
    if (success) {
      await storage.createAuditLog({
        action: "ACCOUNT_UNLOCKED",
        resource: "Account Security",
        userId: req.session.userId!,
        details: `Account ${username} unlocked by admin`,
        ipAddress: getClientIp(req),
      });
    }
    res.json({ success });
  }));

  // Admin: Unblock IP
  app.post("/api/security/unblock-ip", requirePlatformAdmin, asyncHandler(async (req, res) => {
    const { unblockIP } = await import("./lib/rate-limiter");
    const { ip } = req.body;
    if (!ip) {
      return res.status(400).json({ error: "IP address required" });
    }
    const success = await unblockIP(ip);
    if (success) {
      await storage.createAuditLog({
        action: "IP_UNBLOCKED",
        resource: "Network Security",
        userId: req.session.userId!,
        details: `IP ${ip} unblocked by admin`,
        ipAddress: getClientIp(req),
      });
    }
    res.json({ success });
  }));

  // ========================================
  // THREAT INTELLIGENCE ENDPOINTS
  // ========================================
  
  app.get("/api/threat-intel/feeds", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await threatIntelligence.getFeeds((req as any).tenantId));
  }));

  app.post("/api/threat-intel/feeds", requireRole("admin"), asyncHandler(async (req, res) => {
    const feed = threatIntelligence.addFeed(req.body, (req as any).tenantId);
    res.json(feed);
  }));

  app.post("/api/threat-intel/feeds/:feedId/sync", requireRole("admin"), asyncHandler(async (req, res) => {
    const result = await threatIntelligence.syncFeed(String(req.params.feedId), (req as any).tenantId);
    res.json(result);
  }));

  app.get("/api/threat-intel/indicators", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { type, severity, source, search, limit } = req.query;
    res.json(await threatIntelligence.getIndicators((req as any).tenantId, {
      type: type as any,
      severity: severity as any,
      source: source as string,
      search: search as string,
      limit: limit ? parseInt(limit as string) : undefined
    }));
  }));

  app.post("/api/threat-intel/check", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { value, context } = req.body;
    const match = await threatIntelligence.checkValue(value, (req as any).tenantId, context);
    res.json({ match });
  }));

  app.post("/api/threat-intel/bulk-check", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { values } = req.body;
    const matches = await threatIntelligence.bulkCheck(values, (req as any).tenantId);
    res.json({ matches, matchCount: matches.length });
  }));

  app.get("/api/threat-intel/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await threatIntelligence.getStats((req as any).tenantId));
  }));

  app.get("/api/threat-intel/matches", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    res.json(await threatIntelligence.getRecentMatches((req as any).tenantId, limit));
  }));

  // ========================================
  // SOAR PLAYBOOK ENDPOINTS
  // ========================================

  app.get("/api/soar/playbooks", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await soarPlaybook.getPlaybooks({ tenantId: req.tenantId }));
  }));

  app.get("/api/soar/playbooks/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const playbook = await soarPlaybook.getPlaybook(String(req.params.id), { tenantId: req.tenantId });
    if (!playbook) {
      return res.status(404).json({ error: "Playbook not found" });
    }
    res.json(playbook);
  }));

  app.post("/api/soar/playbooks", requireRole("admin"), asyncHandler(async (req, res) => {
    const playbook = await soarPlaybook.createPlaybook(req.body, { tenantId: req.tenantId });
    res.json(playbook);
  }));

  app.patch("/api/soar/playbooks/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const playbook = await soarPlaybook.updatePlaybook(String(req.params.id), req.body, { tenantId: req.tenantId });
    if (!playbook) {
      return res.status(404).json({ error: "Playbook not found" });
    }
    res.json(playbook);
  }));

  app.post("/api/soar/playbooks/:id/execute", requireRole("admin"), asyncHandler(async (req, res) => {
    const body = req.body || {};
    const triggeredBy = body.triggeredBy || `user:${req.session.userId}`;
    const context = body.context || {};
    const execution = await soarPlaybook.executePlaybook(
      String(req.params.id),
      triggeredBy,
      context,
      { tenantId: req.tenantId },
    );
    res.json(execution);
  }));

  app.get("/api/soar/executions", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { playbookId, status, limit } = req.query;
    const raw = await soarPlaybook.getExecutions({
      playbookId: playbookId as string,
      status: status as any,
      limit: limit ? parseInt(limit as string) : undefined
    }, { tenantId: req.tenantId });
    // Fetch the tenant's playbooks once (RLS-scoped) to enrich without an async N+1.
    const enrichPlaybooks = await soarPlaybook.getPlaybooks({ tenantId: req.tenantId });
    const pbById = new Map(enrichPlaybooks.map(p => [p.id, p]));
    const mapped = raw.map(exec => {
      const playbook = pbById.get(exec.playbookId);
      const actionsExecuted = exec.actionResults.filter(a => a.status === "success").length;
      const duration = exec.endTime ? exec.endTime.getTime() - exec.startTime.getTime() : undefined;
      return {
        id: exec.id,
        playbookId: exec.playbookId,
        playbookName: exec.playbookName,
        trigger: playbook?.trigger || "manual",
        status: exec.status,
        startedAt: exec.startTime.toISOString(),
        completedAt: exec.endTime?.toISOString(),
        duration,
        actionsExecuted,
        actionsTotal: exec.actionResults.length,
      };
    });
    res.json(mapped);
  }));

  // /executions/history (literal) MUST register before /executions/:id (param) — else the :id
  // route catches "history" as an id and 404s the literal. Moved here 2026-07-26 (param-shadow fix).
  app.get("/api/soar/executions/history", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    const executions = await storage.getSoarExecutions(limit);
    res.json(executions);
  }));

  app.get("/api/soar/executions/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const execution = await soarPlaybook.getExecution(String(req.params.id), { tenantId: req.tenantId });
    if (!execution) {
      return res.status(404).json({ error: "Execution not found" });
    }
    res.json(execution);
  }));

  app.get("/api/soar/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await soarPlaybook.getStats({ tenantId: req.tenantId }));
  }));

  // SOAR Action Registry
  app.get("/api/soar/action-registry", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(soarPlaybook.getActionRegistry());
  }));

  // SOAR Safety Rails
  app.get("/api/soar/safety-rails", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const rails = soarPlaybook.getSafetyRails();
    const railsArray = [
      { id: "sr-confidence", name: "Confidence Threshold", description: `Minimum AI confidence to auto-execute: ${(rails.confidenceThreshold * 100).toFixed(0)}%`, enabled: rails.enabled },
      { id: "sr-manual-approval", name: "Manual Approval Threshold", description: `Require human approval below ${(rails.manualApprovalThreshold * 100).toFixed(0)}% confidence`, enabled: rails.enabled },
      { id: "sr-fp-protection", name: "False Positive Protection", description: `Max ${rails.falsePositiveProtection.maxAutoActionsPerHour} auto-actions/hour, impact cap ${rails.falsePositiveProtection.maxImpactScoreWithoutApproval}`, enabled: rails.falsePositiveProtection.enabled },
      { id: "sr-vip-protection", name: "VIP Account Protection", description: "Extra checks for VIP and executive accounts", enabled: rails.falsePositiveProtection.vipAccountProtection },
      { id: "sr-business-hours", name: "Business Hours Only", description: "High-impact actions restricted to business hours", enabled: rails.falsePositiveProtection.businessHoursOnly },
      { id: "sr-rollback", name: "Auto-Rollback on False Positive", description: `Rollback window: ${rails.rollbackCapability.rollbackWindowMinutes} minutes`, enabled: rails.rollbackCapability.autoRollbackOnFalsePositive },
      { id: "sr-hitl-vip", name: "Human-in-the-Loop (VIP)", description: "Always require approval for VIP accounts", enabled: rails.humanInTheLoop.alwaysRequireForVIP },
      { id: "sr-hitl-high-impact", name: "Human-in-the-Loop (High Impact)", description: `Escalation timeout: ${rails.humanInTheLoop.escalationTimeoutMinutes} minutes`, enabled: rails.humanInTheLoop.alwaysRequireForHighImpact },
    ];
    res.json(railsArray);
  }));

  app.patch("/api/soar/safety-rails", requirePlatformRole("admin"), requireStepUp, asyncHandler(async (req, res) => {
    const updated = soarPlaybook.updateSafetyRails(req.body);
    await storage.createAuditLog({
      action: "SAFETY_RAILS_UPDATED",
      resource: "SOAR Configuration",
      userId: req.session.userId!,
      details: `Safety rails updated: ${Object.keys(req.body).join(", ")}`,
      ipAddress: getClientIp(req),
    });
    res.json(updated);
  }));

  // SOAR Rollback
  app.post("/api/soar/executions/:id/rollback", requireRole("admin"), asyncHandler(async (req, res) => {
    const result = await soarPlaybook.rollbackExecution(String(req.params.id), { tenantId: req.tenantId });
    if (result.success) {
      await storage.createAuditLog({
        action: "PLAYBOOK_ROLLBACK",
        resource: "SOAR Execution",
        userId: req.session.userId!,
        details: `Rolled back execution ${req.params.id}: ${result.rolledBack.join(", ")}`,
        ipAddress: getClientIp(req),
      });
    }
    res.json(result);
  }));

  // ========================================
  // API GATEWAY ENDPOINTS
  // ========================================

  app.get("/api/gateway/clients", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(apiGateway.getClients());
  }));

  app.get("/api/gateway/clients/:id", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const client = apiGateway.getClient(String(req.params.id));
    if (!client) {
      return res.status(404).json({ error: "Client not found" });
    }
    res.json(client);
  }));

  app.post("/api/gateway/clients", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { client, plainApiKey } = apiGateway.createClient(req.body);
    res.json({ client, apiKey: plainApiKey });
  }));

  app.patch("/api/gateway/clients/:id", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const client = apiGateway.updateClient(String(req.params.id), req.body);
    if (!client) {
      return res.status(404).json({ error: "Client not found" });
    }
    res.json(client);
  }));

  app.post("/api/gateway/clients/:id/rotate-key", requirePlatformRole("admin"), requireStepUp, asyncHandler(async (req, res) => {
    const result = apiGateway.rotateApiKey(String(req.params.id));
    if (!result) {
      return res.status(404).json({ error: "Client not found" });
    }
    res.json({ client: result.client, apiKey: result.plainApiKey });
  }));

  app.post("/api/gateway/clients/:id/revoke", requirePlatformRole("admin"), requireStepUp, asyncHandler(async (req, res) => {
    const success = apiGateway.revokeClient(String(req.params.id));
    res.json({ success });
  }));

  app.get("/api/gateway/usage", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { clientId, endpoint, limit } = req.query;
    res.json(apiGateway.getUsage({
      clientId: clientId as string,
      endpoint: endpoint as string,
      limit: limit ? parseInt(limit as string) : 100
    }));
  }));

  app.get("/api/gateway/analytics", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const period = (req.query.period as "hour" | "day" | "week") || "day";
    res.json(apiGateway.getAnalytics(period));
  }));

  app.get("/api/gateway/stats", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(apiGateway.getStats());
  }));

  app.get("/api/gateway/blocked-ips", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(apiGateway.getBlockedIPs());
  }));

  app.post("/api/gateway/block-ip", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { ip, duration, reason } = req.body;
    apiGateway.blockIP(ip, duration || 3600, reason || "Manual block");
    res.json({ success: true });
  }));

  app.post("/api/gateway/unblock-ip", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { ip } = req.body;
    const success = apiGateway.unblockIP(ip);
    res.json({ success });
  }));

  // ========================================
  // COMPLIANCE DASHBOARD ENDPOINTS
  // ========================================

  // ========================================
  // Governance Documentation Pack (downloads)
  // ========================================
  const GOVERNANCE_DOC_PATH = path.resolve(process.cwd(), "attached_assets", "aegis-cyber-governance-documentation_1777442430971.docx");
  const EXEC_SUMMARY_PATH = path.resolve(process.cwd(), "attached_assets", "AEGIS_CYBER_Executive_Summary.md");

  app.get("/api/compliance/governance-pack/metadata", requireRole("admin", "risk_manager", "auditor", "viewer"), asyncHandler(async (req, res) => {
    const govExists = fs.existsSync(GOVERNANCE_DOC_PATH);
    const summaryExists = fs.existsSync(EXEC_SUMMARY_PATH);
    await storage.createAuditLog({
      action: "GOVERNANCE_PACK_METADATA_VIEWED",
      resource: "Compliance Documents",
      userId: req.session.userId!,
      details: "Viewed governance pack metadata",
      ipAddress: getClientIp(req),
    });
    res.json({
      governancePack: {
        available: govExists,
        filename: "AEGIS_CYBER_Governance_Pack_v1.0.docx",
        sizeBytes: govExists ? fs.statSync(GOVERNANCE_DOC_PATH).size : 0,
        // available + sizeBytes above are DERIVED (existsSync/statSync) — honest either way.
        // Everything below describes the CONTENTS of the pack: its version, review dates, its
        // eight-policy register, its framework alignments. None is read from the document —
        // they are literals — and they were emitted even when the file is ABSENT, which it is
        // in this deployment. /compliance-documents rendered them to any viewer, asserting a
        // SOC2 / ISO-27001 / PDPO-aligned governance framework with no artifact behind it.
        // A property of a document cannot be asserted for a document that is not there.
        // Two honest end states only: no register (this), or a real document with these fields
        // DERIVED from it. Never the literals standing in for one.
        version: govExists ? "1.0" : null,
        effectiveDate: govExists ? "April 2026" : null,
        nextReview: govExists ? "April 2027" : null,
        policyCount: govExists ? 8 : null,
        policies: govExists
          ? ["ISP-001", "ACP-002", "CMP-003", "IRP-004", "BCP-005", "RA-006", "VMP-007", "DPP-008"]
          : null,
        frameworks: govExists
          ? ["SOC2 TSC", "ISO/IEC 27001:2022", "Uganda PDPO 2019", "BoU ICT Risk Guidelines"]
          : null,
      },
      executiveSummary: {
        available: summaryExists,
        filename: "AEGIS_CYBER_Executive_Summary.md",
        sizeBytes: summaryExists ? fs.statSync(EXEC_SUMMARY_PATH).size : 0,
      },
    });
  }));

  app.get("/api/compliance/governance-pack/download", requireRole("admin", "risk_manager", "auditor", "viewer"), asyncHandler(async (req, res) => {
    if (!fs.existsSync(GOVERNANCE_DOC_PATH)) {
      return res.status(404).json({ error: "Governance pack not available" });
    }
    // FU-053 T001 Shape 3 — bounded tenant DB phase for the audit write; the
    // file is then piped with no DB connection held (carved-out streaming route,
    // raw `db` forbidden — storage.createAuditLog uses the `db` proxy).
    await withTenantDbPhase(req, async () => {
      await storage.createAuditLog({
        action: "GOVERNANCE_PACK_DOWNLOADED",
        resource: "Compliance Documents",
        userId: req.session.userId!,
        details: "Downloaded AEGIS CYBER Governance Pack v1.0",
        ipAddress: getClientIp(req),
      });
    });
    res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    res.setHeader("Content-Disposition", 'attachment; filename="AEGIS_CYBER_Governance_Pack_v1.0.docx"');
    fs.createReadStream(GOVERNANCE_DOC_PATH).pipe(res);
  }));

  app.get("/api/compliance/executive-summary/download", requireRole("admin", "risk_manager", "auditor", "viewer"), asyncHandler(async (req, res) => {
    if (!fs.existsSync(EXEC_SUMMARY_PATH)) {
      return res.status(404).json({ error: "Executive summary not available" });
    }
    // FU-053 T001 Shape 3 — bounded tenant DB phase for the audit write; file
    // piped after with no DB held (carved-out streaming route).
    await withTenantDbPhase(req, async () => {
      await storage.createAuditLog({
        action: "EXEC_SUMMARY_DOWNLOADED",
        resource: "Compliance Documents",
        userId: req.session.userId!,
        details: "Downloaded AEGIS CYBER Executive Summary",
        ipAddress: getClientIp(req),
      });
    });
    res.setHeader("Content-Type", "text/markdown; charset=utf-8");
    res.setHeader("Content-Disposition", 'attachment; filename="AEGIS_CYBER_Executive_Summary.md"');
    fs.createReadStream(EXEC_SUMMARY_PATH).pipe(res);
  }));

  app.get("/api/compliance/executive-summary/view", requireRole("admin", "risk_manager", "auditor", "viewer"), asyncHandler(async (req, res) => {
    if (!fs.existsSync(EXEC_SUMMARY_PATH)) {
      return res.status(404).json({ error: "Executive summary not available" });
    }
    await storage.createAuditLog({
      action: "EXEC_SUMMARY_VIEWED",
      resource: "Compliance Documents",
      userId: req.session.userId!,
      details: "Previewed AEGIS CYBER Executive Summary",
      ipAddress: getClientIp(req),
    });
    res.setHeader("Content-Type", "text/markdown; charset=utf-8");
    res.send(fs.readFileSync(EXEC_SUMMARY_PATH, "utf-8"));
  }));

  // ========================================
  // Load Test (honest baseline benchmarks)
  // ========================================
  const { runLoadTest, SCENARIO_CATALOG } = await import("./lib/load-test");
  const { loadTestRuns } = await import("@shared/schema");
  const { z: zLoadTest } = await import("zod");

  const loadTestParamsSchema = zLoadTest.object({
    scenario: zLoadTest.enum(["kyt_scoring", "audit_log_write", "audit_log_read", "http_health", "http_loopback_ping"]),
    durationMs: zLoadTest.number().int().min(1000).max(60000),
    concurrency: zLoadTest.number().int().min(1).max(100),
    notes: zLoadTest.string().max(500).optional(),
  });

  let loadTestInFlight = false;

  // Ultra-thin admin-only ping. Bypasses the /api rate limiter (allow-listed
  // in server/lib/rate-limiter.ts) so the http_loopback_ping load-test scenario
  // can measure raw end-to-end HTTP throughput without being throttled.
  app.get("/api/load-test/ping", requirePlatformRole("admin"), (_req, res) => {
    res.json({ ok: true, t: Date.now() });
  });

  app.get("/api/load-test/scenarios", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(SCENARIO_CATALOG);
  }));

  app.get("/api/load-test/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(loadTestRuns).orderBy(desc(loadTestRuns.startedAt)).limit(50);
    res.json(rows);
  }));

  // Helper: detect short git SHA (best-effort, never throws).
  async function detectGitSha(): Promise<string> {
    try {
      const envSha =
        process.env.REPLIT_GIT_COMMIT ||
        process.env.GIT_COMMIT ||
        process.env.COMMIT_SHA;
      if (envSha) return envSha.slice(0, 7);
      const { execSync } = await import("child_process");
      const sha = execSync("git rev-parse --short HEAD", {
        timeout: 1500,
        stdio: ["ignore", "pipe", "ignore"],
      })
        .toString()
        .trim();
      return sha || "unknown";
    } catch {
      return "unknown";
    }
  }

  // Standard suite — same shape every time so before/after deltas are apples-to-apples.
  // 4 scenarios × concurrency 20 × 5s each = ~20s of wall-clock + small overhead.
  type SuiteScenarioId = "kyt_scoring" | "audit_log_write" | "audit_log_read" | "http_loopback_ping";
  const DEPLOY_SUITE_SCENARIOS: Array<{ scenario: SuiteScenarioId; concurrency: number; durationMs: number }> = [
    { scenario: "kyt_scoring", concurrency: 20, durationMs: 5000 },
    { scenario: "audit_log_write", concurrency: 20, durationMs: 5000 },
    { scenario: "audit_log_read", concurrency: 20, durationMs: 5000 },
    { scenario: "http_loopback_ping", concurrency: 20, durationMs: 5000 },
  ];

  const deploySuiteSchema = zLoadTest.object({
    phase: zLoadTest.enum(["pre", "post"]),
    gitSha: zLoadTest.string().trim().min(1).max(40).optional(),
  });

  app.post("/api/load-test/suite", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const parsed = deploySuiteSchema.safeParse(req.body || {});
    if (!parsed.success) {
      return res.status(400).json({ error: "Invalid parameters", details: parsed.error.flatten() });
    }
    if (loadTestInFlight) {
      return res.status(409).json({ error: "A load test is already running. Wait for it to finish." });
    }
    loadTestInFlight = true;
    try {
      const internalPort = parseInt(process.env.PORT || "5000", 10);
      const baseUrl = `http://127.0.0.1:${internalPort}`;
      const username = (req.session as any)?.username || "admin";
      const sha = (parsed.data.gitSha || (await detectGitSha())).slice(0, 12);
      const tag = `${parsed.data.phase}-deploy:${sha}`;

      // Regression-alert thresholds: a scenario is flagged when its current p95 is more than
      // REGRESSION_RATIO times the median of the last REGRESSION_BASELINE_SIZE clean baseline
      // runs (errorCount=0, excluding the row we just wrote). The absolute floor avoids noisy
      // alerts when baseline p95 is sub-millisecond and a 2x bump is still trivially fast.
      // MIN_BASELINE_SAMPLE_SIZE prevents false positives during cold-start/sparse history —
      // a fresh database or scenario with <5 prior clean runs simply won't alert.
      const REGRESSION_RATIO = 2.0;
      const REGRESSION_FLOOR_MS = 50;
      const REGRESSION_BASELINE_SIZE = 10;
      const MIN_BASELINE_SAMPLE_SIZE = 5;
      const median = (xs: number[]) => {
        if (xs.length === 0) return null;
        const sorted = [...xs].sort((a, b) => a - b);
        const mid = Math.floor(sorted.length / 2);
        return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
      };

      const savedRuns: any[] = [];
      const alerts: Array<{
        scenario: string;
        currentP95Ms: number;
        baselineP95Ms: number | null;
        ratio: number | null;
        baselineSampleSize: number;
        severity: "warning" | "critical";
      }> = [];

      for (const step of DEPLOY_SUITE_SCENARIOS) {
        // DIAG-SUITE-1: record wall-clock start so hung scenarios are visible in logs.
        const scenarioStartMs = Date.now();
        logger.info(`[suite-diag] scenario START: ${step.scenario}`, {
          metadata: { scenario: step.scenario, tag },
        });

        const result = await runLoadTest({
          scenario: step.scenario,
          durationMs: step.durationMs,
          concurrency: step.concurrency,
          baseUrl,
          sessionCookie: req.headers.cookie,
        });

        // DIAG-SUITE-2: log elapsed time + any worker-side errors so hang timing
        // and per-scenario error samples are visible even if they were caught internally.
        logger.info(`[suite-diag] scenario COMPLETE: ${step.scenario}`, {
          metadata: {
            scenario: step.scenario,
            tag,
            wallClockMs: Date.now() - scenarioStartMs,
            successCount: result.successCount,
            errorCount: result.errorCount,
            errorSample: result.errorSample,
          },
        });

        // DIAG-SUITE-3: wrap ALS-tx DB operations so the first PostgreSQL error
        // (SQLSTATE, message) is logged before the 25P02 cascade makes it invisible.
        let saved: typeof loadTestRuns.$inferSelect;
        try {
          [saved] = await db.insert(loadTestRuns).values({
          scenario: result.scenario,
          concurrency: result.concurrency,
          durationMs: result.durationMs,
          totalRequests: result.totalRequests,
          successCount: result.successCount,
          errorCount: result.errorCount,
          throughputPerSec: result.throughputPerSec,
          latencyAvgMs: result.latencyAvgMs,
          latencyMinMs: result.latencyMinMs,
          latencyMaxMs: result.latencyMaxMs,
          latencyP50Ms: result.latencyP50Ms,
          latencyP95Ms: result.latencyP95Ms,
          latencyP99Ms: result.latencyP99Ms,
          cpuLoadAvg: result.cpuLoadAvg,
          memoryRssMb: result.memoryRssMb,
          triggeredBy: username,
          notes: tag,
        }).returning();
        savedRuns.push(saved);

        // Compute baseline from prior clean runs of this scenario (exclude the row we just wrote).
        const baselineRows = await db
          .select({ p95: loadTestRuns.latencyP95Ms })
          .from(loadTestRuns)
          .where(and(
            eq(loadTestRuns.scenario, result.scenario),
            eq(loadTestRuns.errorCount, 0),
            ne(loadTestRuns.id, saved.id),
          ))
          .orderBy(desc(loadTestRuns.startedAt))
          .limit(REGRESSION_BASELINE_SIZE);

        const baselineP95s = baselineRows
          .map(r => Number(r.p95))
          .filter(n => Number.isFinite(n));
        const baselineP95 = median(baselineP95s);
        const currentP95 = Number(saved.latencyP95Ms);

        if (
          baselineP95s.length >= MIN_BASELINE_SAMPLE_SIZE &&
          baselineP95 !== null &&
          baselineP95 > 0 &&
          currentP95 >= REGRESSION_FLOOR_MS &&
          currentP95 > baselineP95 * REGRESSION_RATIO
        ) {
          const ratio = currentP95 / baselineP95;
          alerts.push({
            scenario: result.scenario,
            currentP95Ms: currentP95,
            baselineP95Ms: baselineP95,
            ratio: Number(ratio.toFixed(2)),
            baselineSampleSize: baselineP95s.length,
            severity: ratio >= 4 ? "critical" : "warning",
          });
        }
        } catch (err: any) {
          // DIAG-SUITE-3 catch: log the first PostgreSQL error on the ALS tx so the
          // 25P02 cascade can be traced back to its SQLSTATE of origin.
          logger.fatal(`[suite-diag] ALS-TX ERROR on scenario "${step.scenario}"`, {
            metadata: {
              scenario: step.scenario,
              sqlstate: err.code,
              pgMessage: err.message,
              pgSeverity: err.severity,
              pgDetail: err.detail,
            },
          });
          throw err;
        }
      }

      await storage.createAuditLog({
        action: "LOAD_TEST_SUITE_EXECUTED",
        resource: "Load Test",
        userId: req.session.userId!,
        details: `phase=${parsed.data.phase} sha=${sha} scenarios=${DEPLOY_SUITE_SCENARIOS.length} alerts=${alerts.length}`,
        ipAddress: getClientIp(req),
      });

      // Emit a separate audit row per regression so SOC2 reviewers see them in the audit feed.
      for (const a of alerts) {
        await storage.createAuditLog({
          action: "LOAD_TEST_REGRESSION_DETECTED",
          resource: "Load Test",
          userId: req.session.userId!,
          details: `scenario=${a.scenario} p95=${a.currentP95Ms.toFixed(2)}ms baseline=${a.baselineP95Ms?.toFixed(2)}ms ratio=${a.ratio}x severity=${a.severity} sha=${sha}`,
          ipAddress: getClientIp(req),
        });
      }

      res.json({
        tag,
        gitSha: sha,
        phase: parsed.data.phase,
        runs: savedRuns,
        alerts,
        regressionDetected: alerts.length > 0,
      });
    } finally {
      loadTestInFlight = false;
    }
  }));

  app.post("/api/load-test/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const parsed = loadTestParamsSchema.safeParse(req.body || {});
    if (!parsed.success) {
      return res.status(400).json({ error: "Invalid parameters", details: parsed.error.flatten() });
    }
    if (loadTestInFlight) {
      return res.status(409).json({ error: "A load test is already running. Wait for it to finish." });
    }
    loadTestInFlight = true;
    try {
      // Use a fixed loopback URL for the http_health scenario.
      // Never derive the target from the Host header — that would allow SSRF.
      const internalPort = parseInt(process.env.PORT || "5000", 10);
      const baseUrl = `http://127.0.0.1:${internalPort}`;

      const result = await runLoadTest({
        scenario: parsed.data.scenario,
        durationMs: parsed.data.durationMs,
        concurrency: parsed.data.concurrency,
        baseUrl,
        sessionCookie: req.headers.cookie,
      });

      const username = (req.session as any)?.username || "admin";
      const [saved] = await db.insert(loadTestRuns).values({
        scenario: result.scenario,
        concurrency: result.concurrency,
        durationMs: result.durationMs,
        totalRequests: result.totalRequests,
        successCount: result.successCount,
        errorCount: result.errorCount,
        throughputPerSec: result.throughputPerSec,
        latencyAvgMs: result.latencyAvgMs,
        latencyMinMs: result.latencyMinMs,
        latencyMaxMs: result.latencyMaxMs,
        latencyP50Ms: result.latencyP50Ms,
        latencyP95Ms: result.latencyP95Ms,
        latencyP99Ms: result.latencyP99Ms,
        cpuLoadAvg: result.cpuLoadAvg,
        memoryRssMb: result.memoryRssMb,
        triggeredBy: username,
        notes: parsed.data.notes || null,
      }).returning();

      await storage.createAuditLog({
        action: "LOAD_TEST_EXECUTED",
        resource: "Load Test",
        userId: req.session.userId!,
        details: `scenario=${result.scenario} concurrency=${result.concurrency} duration=${result.durationMs}ms tps=${result.throughputPerSec.toFixed(1)}`,
        ipAddress: getClientIp(req),
      });

      res.json({ run: saved, errorSample: result.errorSample });
    } finally {
      loadTestInFlight = false;
    }
  }));

  // ========================================
  // Pilot-Readiness: Audit Chain Verifier, RBAC + Tenant Isolation, Breach Drill, Backup Restore Test
  // ========================================
  const {
    runAuditChainVerification,
    runRbacMatrixTest,
    runTenantIsolationTest,
    runBreachDrill,
    runBackupRestoreTest,
    pilotReadinessJanitor,
  } = await import("./lib/pilot-readiness");
  // Sweep orphan rbac_test_* users and restore_test_* schemas at startup.
  void pilotReadinessJanitor();
  const {
    runChaosDrill,
    runDsarDrill,
    runRedteamProbe,
    runSovereigntyTest,
    runSloConformance,
    runPentest,
    runCryptoRotation,
    runExitPortabilityDrill,
    runFullDatabaseExport,
    signEvidenceBundle,
    verifyEvidenceBundle,
    getPilotTrend,
    seedRegulatorAccount,
  } = await import("./lib/pilot-readiness-extras");
  void seedRegulatorAccount();
  // seedSovereignTenant() + seedUserTenantRoles() MOVED to their own awaited boot
  // phase in server/index.ts ("seedTenantBindings", after registerRoutes, before
  // httpServer.listen()). They were `void`-fired here, which detached them from the
  // boot await chain: a failure could not abort the boot, only surface later as an
  // unhandled rejection — after the port was already open. The binding outcome is
  // now fail-closed at startup. Both imports are dropped from this destructuring
  // because nothing else in this file calls them — no route handler re-runs either
  // seed; index.ts imports them directly in the new phase.
  const {
    auditChainVerifications,
    securityTestRuns,
    breachDrillRuns,
    backupRestoreTests,
    chaosDrillRuns,
    dsarDrillRuns,
    redteamProbeRuns,
    sovereigntyTestRuns,
    sloConformanceRuns,
    pentestRuns,
    cryptoRotationRuns,
    exitPortabilityRuns,
  } = await import("@shared/schema");

  let pilotTestInFlight = false;

  // ----- Audit Chain Verifier -----
  app.post("/api/audit-chain/verify", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) {
      return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    }
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runAuditChainVerification(username);
      await storage.createAuditLog({
        action: "AUDIT_CHAIN_VERIFIED",
        resource: "Audit Chain",
        userId: req.session.userId!,
        details: `valid=${result.valid} entries=${result.totalEntries} brokenAt=${result.brokenAt ?? "n/a"}`,
        ipAddress: getClientIp(req),
      });
      // H6: surface coverage reconciliation alongside chain-internal integrity, so a missing
      // chain entry for an audit_logs row (the silent-gap blind spot) cannot hide. Read-only;
      // wrapped so a reconciliation failure never breaks the integrity response itself.
      let reconciliation: unknown;
      try {
        const { reconcileAuditChain } = await import("./lib/audit-chain");
        reconciliation = await reconcileAuditChain();
      } catch (reconErr: any) {
        reconciliation = { error: "reconciliation_failed", message: String(reconErr?.message ?? reconErr) };
      }
      res.json({ ...result, reconciliation });
    } finally {
      pilotTestInFlight = false;
    }
  }));

  app.get("/api/audit-chain/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(auditChainVerifications).orderBy(desc(auditChainVerifications.createdAt)).limit(50);
    res.json(rows);
  }));

  // Read-only surface for signed AUDIT_CHAIN_FORK_RECONCILIATION chain events (integrity Part 2 / 1a).
  // Returns each record VERBATIM (full details incl. claims_and_limits + signature) plus the chain
  // entry's id/hash/previous_hash, so a reader can verify the record's own chain linkage from the API
  // (its self_protection claim). This is EXPLANATORY, not exculpatory: it does NOT alter the verify
  // verdict — /api/audit-chain/verify still returns valid=false when the chain is forked.
  app.get("/api/audit-chain/reconciliations", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const result: any = await db.execute(sql`
      SELECT id, hash, previous_hash, entry_timestamp, details
      FROM audit_chain_entries WHERE action = 'AUDIT_CHAIN_FORK_RECONCILIATION'
      ORDER BY id DESC`);
    const rows = ((result?.rows ?? result ?? []) as any[]).map((r) => {
      let record: any = null;
      try { record = JSON.parse(r.details); } catch { record = { parse_error: true, raw: r.details }; }
      return {
        entryId: r.id,
        entryHash: r.hash,
        entryPreviousHash: r.previous_hash,
        entryTimestamp: r.entry_timestamp,
        record,
      };
    });
    res.json(rows);
  }));

  app.get("/api/audit-chain/proof/:id", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const [row] = await db.select().from(auditChainVerifications).where(sql`id = ${req.params.id}`).limit(1);
    if (!row) return res.status(404).json({ error: "Verification not found" });
    await storage.createAuditLog({
      action: "AUDIT_CHAIN_PROOF_DOWNLOADED",
      resource: "Audit Chain",
      userId: req.session.userId!,
      details: `proofId=${row.id}`,
      ipAddress: getClientIp(req),
    });
    res.setHeader("Content-Type", "application/json");
    res.setHeader("Content-Disposition", `attachment; filename="audit-chain-proof-${row.id}.json"`);
    res.send(row.proofJson || "{}");
  }));

  // M4: regulator-facing self-verifying audit-chain export. An examiner (global-auditor role is a
  // legitimate evidence reader — gate admit+auditor, not admin-only) can recompute every hash,
  // confirm linkage, and confirm coverage independently — tamper-evident by reconstruction.
  app.get("/api/audit-chain/export", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { buildAuditChainExport } = await import("./lib/audit-chain");
    const bundle = await buildAuditChainExport();
    await storage.createAuditLog({
      action: "AUDIT_CHAIN_EXPORTED",
      resource: "Audit Chain",
      userId: req.session.userId!,
      details: `entries=${bundle.entryCount} integrityValid=${bundle.internalIntegrity.valid} reconciled=${bundle.reconciliation.reconciled}`,
      ipAddress: getClientIp(req),
    });
    res.setHeader("Content-Type", "application/json");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-audit-chain-export.json"`);
    res.send(JSON.stringify(bundle, null, 2));
  }));

  // M5: on-demand signed chain-head snapshot (notarization). The export also snapshots automatically;
  // this allows a manual or scheduled snapshot. Platform-admin only (it mints a signed record).
  app.post("/api/audit-chain/snapshot", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { createAuditChainSnapshot } = await import("./lib/audit-chain");
    const result = await createAuditChainSnapshot();
    await storage.createAuditLog({
      action: "AUDIT_CHAIN_SNAPSHOT_TAKEN",
      resource: "Audit Chain",
      userId: req.session.userId!,
      details: result.created ? `entryCount=${result.entryCount} headHash=${String(result.headHash).slice(0, 16)}…` : `not_created reason=${result.reason}`,
      ipAddress: getClientIp(req),
    });
    if (!result.created) {
      return res.status(503).json({ error: "notarization_not_configured", detail: "AUDIT_SNAPSHOT_SIGNING_KEY is not set; chain-head snapshots cannot be signed." });
    }
    res.status(201).json(result);
  }));

  // M5 phase-2 core: transport-agnostic BoU anchor package. Produces a self-contained, independently-
  // verifiable signed chain-head commitment to lodge with an external custodian (BoU) — the channel is
  // intentionally NOT encoded (a separate, undecided decision). Platform-gated like the M4 export.
  app.get("/api/audit-chain/anchor", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { buildAuditChainAnchor } = await import("./lib/audit-chain");
    const anchor = await buildAuditChainAnchor();
    await storage.createAuditLog({
      action: "AUDIT_CHAIN_ANCHOR_ISSUED",
      resource: "Audit Chain",
      userId: req.session.userId!,
      details: anchor.status === "anchored"
        ? `entryCount=${anchor.commitment.entryCount} snapshotId=${anchor.sequence.snapshotId}`
        : `status=not_configured`,
      ipAddress: getClientIp(req),
    });
    res.setHeader("Content-Type", "application/json");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-audit-chain-anchor.json"`);
    res.send(JSON.stringify(anchor, null, 2));
  }));

  // Post-quantum audit-chain checkpoint attestation (ML-DSA-65, FIPS 204). The asymmetric-signature
  // companion to the M5 HMAC snapshot: verifiable with the PUBLIC key alone (no shared secret). See
  // server/lib/pqc-attestation.ts for the honest scope (point-in-time, key lifecycle, threat framing).
  app.post("/api/pqc-attestation/checkpoint", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { generatePqcAttestation } = await import("./lib/pqc-attestation");
    const attestation = await generatePqcAttestation();
    await storage.createAuditLog({
      action: "PQC_CHAIN_ATTESTATION_ISSUED",
      resource: "Audit Chain",
      userId: req.session.userId!,
      details: `algorithm=ML-DSA-65 entryCount=${attestation.claim.entryCount} headHash=${attestation.claim.headHash.slice(0, 16)}… keySource=${attestation.keySource} pkFp=${attestation.publicKeyFingerprint}`,
      ipAddress: getClientIp(req),
    });
    res.status(201).json(attestation);
  }));

  // Verify a posted PQC attestation (ML-DSA-65 signature over the canonical claim) + report whether
  // its embedded public key is this node's current published key. Admin/auditor (a verification action).
  app.post("/api/pqc-attestation/verify", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { verifyPqcAttestation } = await import("./lib/pqc-attestation");
    const att = req.body;
    if (!att || typeof att !== "object" || !att.claim || !att.signatureHex || !att.publicKeyHex) {
      return res.status(400).json({ error: "invalid_attestation", detail: "Body must be a PQC attestation with claim, signatureHex, publicKeyHex." });
    }
    res.json(verifyPqcAttestation(att));
  }));

  // The node's current published ML-DSA-65 attestation public key (the trust anchor for verification).
  app.get("/api/pqc-attestation/public-key", requirePlatformRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    const { getAttestationPublicKey } = await import("./lib/pqc-attestation");
    res.json(getAttestationPublicKey());
  }));

  // RFC-3161 external timestamp anchoring — the phase-2 external anchor SNAPSHOT_THREAT_BOUNDARY names:
  // an INDEPENDENT third-party TSA timestamps the chain-head digest, closing the host-attacker
  // forge-the-timeline gap. Seam-gated on TSA_URL (the BoU-channel decision). See server/lib/rfc3161-anchor.ts.
  app.get("/api/audit-chain/rfc3161-anchor/status", requirePlatformRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    const { tsaAnchorStatus, listAnchors } = await import("./lib/rfc3161-anchor");
    res.json({ ...tsaAnchorStatus(), anchors: await listAnchors(50) });
  }));

  // Request an anchor timestamp from the configured TSA. Admin-only; 503 (honest) if not configured.
  app.post("/api/audit-chain/rfc3161-anchor", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { requestAnchor, isTsaConfigured, tsaAnchorStatus } = await import("./lib/rfc3161-anchor");
    if (!isTsaConfigured()) {
      return res.status(503).json({ ok: false, reason: "not_configured", message: tsaAnchorStatus().note });
    }
    const result = await requestAnchor();
    if (result.ok) {
      await storage.createAuditLog({
        action: "RFC3161_ANCHOR_ISSUED",
        resource: "Audit Chain",
        userId: req.session.userId!,
        details: `tsa=${result.anchor?.tsaHost} tsaName=${result.anchor?.tsaName} entryCount=${result.anchor?.entryCount} genTime=${result.anchor?.genTime} serial=${result.anchor?.tsaSerialHex ?? "-"}`,
        ipAddress: getClientIp(req),
      });
    }
    res.status(result.ok ? 201 : 502).json(result);
  }));

  // Verify an RFC-3161 token against a given (entryCount, headHash). Admin/auditor (a verification action).
  app.post("/api/audit-chain/rfc3161-anchor/verify", requirePlatformRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { verifyAnchor } = await import("./lib/rfc3161-anchor");
    const { tokenB64, entryCount, headHash } = req.body ?? {};
    if (typeof tokenB64 !== "string" || typeof entryCount !== "number" || typeof headHash !== "string") {
      return res.status(400).json({ error: "invalid_request", detail: "Body must be { tokenB64: string, entryCount: number, headHash: string }." });
    }
    res.json(verifyAnchor(tokenB64, entryCount, headHash));
  }));

  // ----- Security Tests (RBAC matrix + Tenant isolation) -----
  app.post("/api/security-tests/rbac-matrix", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) {
      return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    }
    pilotTestInFlight = true;
    try {
      const internalPort = parseInt(process.env.PORT || "5000", 10);
      const baseUrl = `http://127.0.0.1:${internalPort}`;
      const username = (req.session as any)?.username || "admin";
      const result = await runRbacMatrixTest(username, baseUrl, req.headers.cookie);
      await storage.createAuditLog({
        action: "RBAC_MATRIX_TESTED",
        resource: "Security Tests",
        userId: req.session.userId!,
        details: `passed=${result.passed} totalChecks=${result.totalChecks} failed=${result.failedChecks}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));

  app.post("/api/security-tests/tenant-isolation", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) {
      return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    }
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runTenantIsolationTest(username);
      await storage.createAuditLog({
        action: "TENANT_ISOLATION_TESTED",
        resource: "Security Tests",
        userId: req.session.userId!,
        details: `passed=${result.passed} totalChecks=${result.totalChecks} failed=${result.failedChecks}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));

  app.get("/api/security-tests/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(securityTestRuns).orderBy(desc(securityTestRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- Breach Drill -----
  app.post("/api/breach-drill/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) {
      return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    }
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const scenario = String((req.body || {}).scenario || "synthetic_pdpo_personal_data_exposure").slice(0, 200);
      const result = await runBreachDrill(username, scenario);
      await storage.createAuditLog({
        action: "BREACH_DRILL_EXECUTED",
        resource: "Breach Drill",
        userId: req.session.userId!,
        details: `scenario=${scenario} steps=${result.stepsCompleted}/${result.totalSteps} within72h=${result.within72h}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));

  app.get("/api/breach-drill/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(breachDrillRuns).orderBy(desc(breachDrillRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- Backup Restorability Smoke Test -----
  app.post("/api/backup-test/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) {
      return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    }
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runBackupRestoreTest(username);
      await storage.createAuditLog({
        action: "BACKUP_RESTORE_TESTED",
        resource: "Backup Test",
        userId: req.session.userId!,
        details: `passed=${result.passed} tablesMatched=${result.tablesMatched}/${result.tablesChecked} rows=${result.totalRowsCopied}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));

  app.get("/api/backup-test/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(backupRestoreTests).orderBy(desc(backupRestoreTests.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- Pilot Readiness Aggregator -----
  app.get("/api/pilot-readiness/summary", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const [latestAudit] = await db.select().from(auditChainVerifications).orderBy(desc(auditChainVerifications.createdAt)).limit(1);
    const [latestRbac] = await db.select().from(securityTestRuns).where(sql`test_type = 'rbac_matrix'`).orderBy(desc(securityTestRuns.createdAt)).limit(1);
    const [latestTenant] = await db.select().from(securityTestRuns).where(sql`test_type = 'tenant_isolation'`).orderBy(desc(securityTestRuns.createdAt)).limit(1);
    const [latestBreach] = await db.select().from(breachDrillRuns).orderBy(desc(breachDrillRuns.createdAt)).limit(1);
    const [latestBackup] = await db.select().from(backupRestoreTests).orderBy(desc(backupRestoreTests.createdAt)).limit(1);
    const recentLoadRuns = await db.select().from(loadTestRuns).orderBy(desc(loadTestRuns.startedAt)).limit(4);

    function statusOf(row: any, validKey: string = "valid"): "pass" | "fail" | "missing" {
      if (!row) return "missing";
      return row[validKey] === 1 || row[validKey] === true ? "pass" : "fail";
    }

    const checks = [
      { id: "audit_chain", label: "Audit Chain Integrity", status: statusOf(latestAudit, "valid"), at: latestAudit?.createdAt ?? null, runId: latestAudit?.id ?? null },
      { id: "rbac_matrix", label: "RBAC Matrix Self-Test", status: statusOf(latestRbac, "passed"), at: latestRbac?.createdAt ?? null, runId: latestRbac?.id ?? null },
      { id: "tenant_isolation", label: "Tenant Isolation", status: statusOf(latestTenant, "passed"), at: latestTenant?.createdAt ?? null, runId: latestTenant?.id ?? null },
      { id: "breach_drill", label: "PDPO 72h Breach Drill", status: statusOf(latestBreach, "within72h"), at: latestBreach?.createdAt ?? null, runId: latestBreach?.id ?? null },
      { id: "backup_restore", label: "Backup Restorability", status: statusOf(latestBackup, "passed"), at: latestBackup?.createdAt ?? null, runId: latestBackup?.id ?? null },
      { id: "load_test", label: "Load Test (recent runs)", status: recentLoadRuns.length > 0 ? "pass" : "missing", at: recentLoadRuns[0]?.startedAt ?? null, runId: recentLoadRuns[0]?.id ?? null },
    ];

    const passes = checks.filter((c) => c.status === "pass").length;
    const fails = checks.filter((c) => c.status === "fail").length;
    const missing = checks.filter((c) => c.status === "missing").length;
    const overall: "pass" | "warn" | "fail" =
      fails > 0 ? "fail" : missing > 0 ? "warn" : "pass";

    res.json({ overall, passes, fails, missing, checks, recentLoadRuns });
  }));

  app.get("/api/pilot-readiness/evidence-pack", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const [latestAudit] = await db.select().from(auditChainVerifications).orderBy(desc(auditChainVerifications.createdAt)).limit(1);
    const recentSecurity = await db.select().from(securityTestRuns).orderBy(desc(securityTestRuns.createdAt)).limit(10);
    const recentBreaches = await db.select().from(breachDrillRuns).orderBy(desc(breachDrillRuns.createdAt)).limit(10);
    const recentBackups = await db.select().from(backupRestoreTests).orderBy(desc(backupRestoreTests.createdAt)).limit(10);
    const recentLoadRuns = await db.select().from(loadTestRuns).orderBy(desc(loadTestRuns.startedAt)).limit(20);

    const pack = {
      generatedAt: new Date().toISOString(),
      generatedBy: (req.session as any)?.username || "admin",
      platform: "AEGIS CYBER",
      latestAuditChainVerification: latestAudit || null,
      securityTestRuns: recentSecurity,
      breachDrillRuns: recentBreaches,
      backupRestoreTests: recentBackups,
      loadTestRuns: recentLoadRuns,
    };

    await storage.createAuditLog({
      action: "EVIDENCE_PACK_DOWNLOADED",
      resource: "Pilot Readiness",
      userId: req.session.userId!,
      details: `audit=${latestAudit?.id ?? "none"} security=${recentSecurity.length} breach=${recentBreaches.length} backup=${recentBackups.length} load=${recentLoadRuns.length}`,
      ipAddress: getClientIp(req),
    });

    res.setHeader("Content-Type", "application/json");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-pilot-evidence-pack-${Date.now()}.json"`);
    res.send(JSON.stringify(pack, null, 2));
  }));

  // ----- Signed Evidence Pack (HMAC-SHA256 signature included) -----
  app.get("/api/pilot-readiness/evidence-pack-signed", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const [latestAudit] = await db.select().from(auditChainVerifications).orderBy(desc(auditChainVerifications.createdAt)).limit(1);
    const recentSecurity = await db.select().from(securityTestRuns).orderBy(desc(securityTestRuns.createdAt)).limit(10);
    const recentBreaches = await db.select().from(breachDrillRuns).orderBy(desc(breachDrillRuns.createdAt)).limit(10);
    const recentBackups = await db.select().from(backupRestoreTests).orderBy(desc(backupRestoreTests.createdAt)).limit(10);
    const recentLoadRuns = await db.select().from(loadTestRuns).orderBy(desc(loadTestRuns.startedAt)).limit(20);
    const [latestChaos] = await db.select().from(chaosDrillRuns).orderBy(desc(chaosDrillRuns.createdAt)).limit(1);
    const [latestDsar] = await db.select().from(dsarDrillRuns).orderBy(desc(dsarDrillRuns.createdAt)).limit(1);
    const [latestRedteam] = await db.select().from(redteamProbeRuns).orderBy(desc(redteamProbeRuns.createdAt)).limit(1);
    const [latestSov] = await db.select().from(sovereigntyTestRuns).orderBy(desc(sovereigntyTestRuns.createdAt)).limit(1);
    const [latestSlo] = await db.select().from(sloConformanceRuns).orderBy(desc(sloConformanceRuns.createdAt)).limit(1);
    const [latestPentest] = await db.select().from(pentestRuns).orderBy(desc(pentestRuns.createdAt)).limit(1);
    const [latestCrypto] = await db.select().from(cryptoRotationRuns).orderBy(desc(cryptoRotationRuns.createdAt)).limit(1);
    const [latestExit] = await db.select().from(exitPortabilityRuns).orderBy(desc(exitPortabilityRuns.createdAt)).limit(1);

    const pack = {
      generatedAt: new Date().toISOString(),
      generatedBy: (req.session as any)?.username || "admin",
      platform: "AEGIS CYBER",
      latestAuditChainVerification: latestAudit || null,
      securityTestRuns: recentSecurity,
      breachDrillRuns: recentBreaches,
      backupRestoreTests: recentBackups,
      loadTestRuns: recentLoadRuns,
      latestChaosDrill: latestChaos || null,
      latestDsarDrill: latestDsar || null,
      latestRedteamProbe: latestRedteam || null,
      latestSovereigntyTest: latestSov || null,
      latestSloConformance: latestSlo || null,
      latestPentest: latestPentest || null,
      latestCryptoRotation: latestCrypto || null,
      latestExitPortability: latestExit || null,
    };

    const body = Buffer.from(JSON.stringify(pack, null, 2), "utf8");
    const sig = signEvidenceBundle(body);
    const envelope = {
      manifest: {
        signature: sig.signature,
        algorithm: sig.algorithm,
        sha256: sig.sha256,
        signedAt: new Date().toISOString(),
        signedBy: (req.session as any)?.username || "admin",
        verifyEndpoint: "/api/pilot-readiness/evidence-pack/verify",
      },
      pack,
    };

    await storage.createAuditLog({
      action: "EVIDENCE_PACK_SIGNED_DOWNLOADED",
      resource: "Pilot Readiness",
      userId: req.session.userId!,
      details: `sha256=${sig.sha256.slice(0, 16)}... signature=${sig.signature.slice(0, 16)}...`,
      ipAddress: getClientIp(req),
    });

    res.setHeader("Content-Type", "application/json");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-pilot-evidence-pack-signed-${Date.now()}.json"`);
    res.send(JSON.stringify(envelope, null, 2));
  }));

  app.post("/api/pilot-readiness/evidence-pack/verify", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const envelope = req.body;
    if (!envelope?.manifest?.signature || !envelope?.pack) {
      return res.status(400).json({ valid: false, error: "Envelope missing manifest.signature or pack" });
    }
    const body = Buffer.from(JSON.stringify(envelope.pack, null, 2), "utf8");
    const valid = verifyEvidenceBundle(body, envelope.manifest.signature);
    res.json({
      valid,
      sha256Matches: valid,
      algorithm: envelope.manifest.algorithm,
      signedAt: envelope.manifest.signedAt,
      signedBy: envelope.manifest.signedBy,
    });
  }));

  // ----- Pilot Readiness Trend (last N days, pass/fail per check) -----
  app.get("/api/pilot-readiness/trend", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const days = Math.max(1, Math.min(90, parseInt(String(req.query.days || "30"), 10)));
    const trend = await getPilotTrend(days);
    res.json(trend);
  }));

  // ----- 1. Chaos Drill -----
  app.post("/api/chaos-drill/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const scenario = String((req.body || {}).scenario || "primary_db_stall").slice(0, 200);
      const result = await runChaosDrill(username, scenario);
      await storage.createAuditLog({
        action: "CHAOS_DRILL_EXECUTED",
        resource: "Chaos Drill",
        userId: req.session.userId!,
        details: `scenario=${scenario} passed=${result.passed} recoveryMs=${result.recoveryMs}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/chaos-drill/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(chaosDrillRuns).orderBy(desc(chaosDrillRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- 2. DSAR Drill -----
  app.post("/api/dsar-drill/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const requestType = String((req.body || {}).requestType || "access").slice(0, 50);
      const result = await runDsarDrill(username, requestType);
      await storage.createAuditLog({
        action: "DSAR_DRILL_EXECUTED",
        resource: "DSAR Drill",
        userId: req.session.userId!,
        details: `type=${requestType} passed=${result.passed} within30Days=${result.within30Days}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/dsar-drill/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(dsarDrillRuns).orderBy(desc(dsarDrillRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- 3. AI Red-Team Probe -----
  app.post("/api/redteam-probe/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runRedteamProbe(username);
      await storage.createAuditLog({
        action: "REDTEAM_PROBE_EXECUTED",
        resource: "AI Red-Team",
        userId: req.session.userId!,
        details: `probes=${result.totalProbes} blocked=${result.blockedProbes} bypassed=${result.bypassedProbes} score=${result.scorePercent}%`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/redteam-probe/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(redteamProbeRuns).orderBy(desc(redteamProbeRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- 4. Sovereignty Test -----
  app.post("/api/sovereignty-test/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runSovereigntyTest(username);
      await storage.createAuditLog({
        action: "SOVEREIGNTY_TEST_EXECUTED",
        resource: "Sovereignty Test",
        userId: req.session.userId!,
        details: `passed=${result.passed} totalChecks=${result.totalChecks} failed=${result.failedChecks}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/sovereignty-test/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(sovereigntyTestRuns).orderBy(desc(sovereigntyTestRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- 5. SLO Conformance -----
  app.post("/api/slo-conformance/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const internalPort = parseInt(process.env.PORT || "5000", 10);
      const result = await runSloConformance(username, internalPort);
      await storage.createAuditLog({
        action: "SLO_CONFORMANCE_EXECUTED",
        resource: "SLO Conformance",
        userId: req.session.userId!,
        details: `passed=${result.passed} p95=${result.latencyP95Ms}ms p99=${result.latencyP99Ms}ms err=${result.errorRatePercent}%`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/slo-conformance/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(sloConformanceRuns).orderBy(desc(sloConformanceRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- 6. Penetration Self-Test -----
  app.post("/api/pentest/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const internalPort = parseInt(process.env.PORT || "5000", 10);
      const result = await runPentest(username, internalPort);
      await storage.createAuditLog({
        action: "PENTEST_EXECUTED",
        resource: "Pentest",
        userId: req.session.userId!,
        details: `passed=${result.passed} probes=${result.totalProbes} highSev=${result.highSeverityFindings}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/pentest/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(pentestRuns).orderBy(desc(pentestRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- 7. Key Rotation / Crypto-Agility Drill -----
  app.post("/api/crypto-rotation/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runCryptoRotation(username);
      await storage.createAuditLog({
        action: "CRYPTO_ROTATION_EXECUTED",
        resource: "Crypto Rotation",
        userId: req.session.userId!,
        details: `passed=${result.passed} steps=${result.stepsCompleted}/${result.totalSteps}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/crypto-rotation/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(cryptoRotationRuns).orderBy(desc(cryptoRotationRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // ----- 8. Exit / Portability Drill -----
  app.post("/api/exit-portability/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness test is currently running." });
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runExitPortabilityDrill(username);
      await storage.createAuditLog({
        action: "EXIT_PORTABILITY_EXECUTED",
        resource: "Exit Portability",
        userId: req.session.userId!,
        details: `passed=${result.passed} tables=${result.tablesExported}/${result.totalTables} bytes=${result.bundleSizeBytes} sla=${result.withinSlaWindow}`,
        ipAddress: getClientIp(req),
      });
      res.json(result);
    } finally {
      pilotTestInFlight = false;
    }
  }));
  app.get("/api/exit-portability/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const rows = await db.select().from(exitPortabilityRuns).orderBy(desc(exitPortabilityRuns.createdAt)).limit(50);
    res.json(rows);
  }));

  // Full-database portability export — the anti-lock-in deliverable. Operator-gated
  // (requirePlatformAdmin: global-role, not a tenant admin) because it emits DECRYPTED
  // PII. The operator supplies the 32-byte AES bundle key as hex in the body; the key
  // is used transiently and is NEVER persisted or logged (no body logger exists; the
  // audit `details` below deliberately excludes it).
  app.post("/api/exit-portability/full-export", requirePlatformAdmin, asyncHandler(async (req, res) => {
    if (pilotTestInFlight) return res.status(409).json({ error: "Another pilot-readiness operation is currently running." });
    const keyHex = (req.body || {}).bundleKeyHex;
    if (typeof keyHex !== "string" || !/^[0-9a-fA-F]{64}$/.test(keyHex)) {
      return res.status(400).json({ error: "bundleKeyHex must be a 64-char hex string (operator-supplied 32-byte AES-256 key)" });
    }
    const bundleKey = Buffer.from(keyHex, "hex");
    pilotTestInFlight = true;
    try {
      const username = (req.session as any)?.username || "admin";
      const result = await runFullDatabaseExport(username, bundleKey);
      // Forensic-chain audit: record WHAT was exported (tables, rows, bundle hash,
      // operator) — NOT the key. Ties a specific bundle to a specific authorised action.
      await storage.createAuditLog({
        action: "FULL_DATABASE_EXPORT_GENERATED",
        resource: "Data Portability",
        userId: req.session.userId!,
        details: `runId=${result.id} tables=${result.tableCount} excluded=${result.excludedCount} rows=${result.totalRecords} bundleSha256=${result.manifestSha256} cipherBytes=${result.bundleCipherBytes}`,
        ipAddress: getClientIp(req),
      });
      // Never echo the key. Return the manifest summary + run id for download.
      res.json({
        id: result.id,
        tableCount: result.tableCount,
        excludedCount: result.excludedCount,
        totalRecords: result.totalRecords,
        manifestSha256: result.manifestSha256,
        bundleCipherBytes: result.bundleCipherBytes,
        durationMs: result.durationMs,
      });
    } finally {
      pilotTestInFlight = false;
      // Best-effort: drop the transient key buffer's contents.
      bundleKey.fill(0);
    }
  }));

  // Download the encrypted bundle for a full-database-export run as a ZIP (the .enc
  // files are already AES-256-GCM ciphertext; the recipient needs the operator key
  // to decrypt, so the transport ZIP carries no plaintext PII).
  app.get("/api/exit-portability/full-export/:id/download", requirePlatformAdmin, asyncHandler(async (req, res) => {
    const [run] = await db.select().from(exitPortabilityRuns).where(eq(exitPortabilityRuns.id, String(req.params.id))).limit(1);
    if (!run) return res.status(404).json({ error: "export run not found" });
    let details: any = {};
    try { details = JSON.parse(run.detailsJson || "{}"); } catch { /* ignore */ }
    if (details.kind !== "full-database-export" || !details.exportDir) {
      return res.status(400).json({ error: "run is not a full-database-export" });
    }
    const fs = await import("fs");
    if (!fs.existsSync(details.exportDir)) {
      return res.status(410).json({ error: "export bundle is no longer on disk (retention/cleanup)" });
    }
    await storage.createAuditLog({
      action: "FULL_DATABASE_EXPORT_DOWNLOADED",
      resource: "Data Portability",
      userId: req.session.userId!,
      details: `runId=${run.id}`,
      ipAddress: getClientIp(req),
    });
    res.setHeader("Content-Type", "application/zip");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-full-export-${run.id}.zip"`);
    const archiver = (await import("archiver")).default;
    const archive = archiver("zip", { zlib: { level: 9 } });
    archive.on("error", (e: any) => { try { res.status(500).end(); } catch { /* already streaming */ } });
    archive.pipe(res);
    archive.directory(details.exportDir, false);
    await archive.finalize();
  }));

  // ====================================================================
  // Tier 1-3 regulator-pilot enhancements (15 features)
  // ====================================================================
  const extras2 = await import("./lib/pilot-readiness-extras-2");
  // Start the continuous scheduler at boot
  extras2.startContinuousScheduler();
  // P5: pilot-pack metadata snapshot scheduler. Records signed per-table
  // row counts to audit_logs every PILOT_PACK_SNAPSHOT_INTERVAL_MS (default
  // 6h). Trail proves the pack would have been generatable + that no rows
  // were retroactively deleted between snapshots.
  (await import("./lib/pilot-pack-scheduler")).startPilotPackScheduler();
  // FU-011 silent-pass conv #1 (2026-05-05): DSAR purge worker. Background
  // worker that bridges DSAR erasure requests to the destructive cascade in
  // runErasureDrill(). See server/lib/dsar-purge-worker.ts. Boot kickoff
  // staggered at 10s per the scheduled-worker boot-stagger convention
  // (PLATFORM_BEHAVIOUR_NOTES.md, 2026-05-05).
  (await import("./lib/dsar-purge-worker")).startDsarPurgeWorker();
  // FU-026 (2026-05-12): backup scheduler. Daily full backup via
  // BackupService.createBackup, weekly verify via BackupService.verifyBackup.
  // Closes the claim-vs-reality gap where backup_records was empty in prod.
  // Boot kickoff staggered at 15s per the scheduled-worker boot-stagger
  // convention (PLATFORM_BEHAVIOUR_NOTES.md, 2026-05-05).
  (await import("./lib/backup-scheduler")).startBackupScheduler();
  // OFAC SDN sanctions-list auto-refresh. Keeps the list inside its 48h freshness SLA so the
  // mandated sanctions control never silently fails closed (which would block onboarding).
  // Leader-locked (distinct advisory key, one instance refreshes not N); no-op unless
  // KYC_SANCTIONS_PROVIDER=ofac_sdn. A failed refresh leaves the last-good list intact
  // (atomic ingest) and logs loudly. Boot kickoff staggered at 20s.
  (await import("./lib/kyc/sanctions-refresh-scheduler")).startSanctionsRefreshScheduler();

  // #2 Continuous Scheduler
  app.post("/api/continuous-scheduler/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.runScheduledPilotSweep((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/continuous-scheduler/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getContinuousScheduleRuns(30));
  }));
  app.get("/api/continuous-scheduler/status", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(extras2.getSchedulerStatus());
  }));

  // #3 Tamper Demo
  app.post("/api/tamper-demo/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.runTamperDemo((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/tamper-demo/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getTamperDemoRuns(20));
  }));

  // #4 Restore Drill
  app.post("/api/restore-drill/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.runRestoreDrill((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/restore-drill/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getRestoreDrillRuns(20));
  }));

  // #5 Breach SLA Drill
  app.post("/api/breach-sla-drill/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.runBreachSlaDrill((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/breach-sla-drill/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getBreachSlaDrillRuns(20));
  }));

  // #6 Bias Drill
  app.post("/api/bias-drill/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.runBiasDrill((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/bias-drill/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getBiasDrillRuns(20));
  }));

  // #7 Model Drift
  app.post("/api/model-drift/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const modelName = req.body?.modelName || "ai-threat-scorer";
    const r = await extras2.runModelDriftCheck((req as any).user?.username || "admin", modelName);
    res.json(r);
  }));
  app.get("/api/model-drift/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getModelDriftRuns(20));
  }));

  // #8 SBOM
  app.post("/api/sbom/generate", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.generateSbom((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/sbom/snapshots", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getSbomSnapshots(10));
  }));
  app.get("/api/sbom/download/:id", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const r = await extras2.downloadSbom(String(req.params.id));
    if (!r) return res.status(404).json({ error: "Not found" });
    res.setHeader("Content-Type", "application/vnd.cyclonedx+json");
    res.setHeader("Content-Disposition", `attachment; filename="sbom-${req.params.id}.cdx.json"`);
    res.setHeader("X-SHA256", r.sha256);
    res.send(r.bomJson);
  }));

  // #9 PIA Generator
  app.post("/api/pia/generate", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const featureName = req.body?.featureName || "Unnamed Feature";
    const ctx = {
      encryptedFields: req.body?.encryptedFields,
      retentionDays: req.body?.retentionDays,
      legalBasis: req.body?.legalBasis,
    };
    const r = await extras2.generatePia((req as any).user?.username || "admin", featureName, ctx);
    res.json(r);
  }));
  app.get("/api/pia/documents", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getPiaDocuments(20));
  }));
  app.get("/api/pia/download/:id", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const r = await extras2.downloadPia(String(req.params.id));
    if (!r) return res.status(404).json({ error: "Not found" });
    res.setHeader("Content-Type", "text/markdown");
    res.setHeader("Content-Disposition", `attachment; filename="pia-${r.featureName.replace(/\s+/g, "-")}.md"`);
    res.setHeader("X-SHA256", r.sha256);
    res.send(r.contentMarkdown);
  }));

  // #10 Runbook Executor
  app.get("/api/runbooks/templates", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(extras2.listRunbookTemplates());
  }));
  app.post("/api/runbooks/start", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const operator = (req as any).user?.username || "admin";
    const runbookName = req.body?.runbookName;
    if (!runbookName) return res.status(400).json({ error: "runbookName required" });
    try {
      const r = await extras2.startRunbook(operator, runbookName);
      res.json(r);
    } catch (err: any) {
      res.status(400).json({ error: err.message });
    }
  }));
  app.post("/api/runbooks/:id/complete-step", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const stepNumber = parseInt(req.body?.stepNumber, 10);
    if (!stepNumber) return res.status(400).json({ error: "stepNumber required" });
    try {
      const r = await extras2.completeRunbookStep(String(req.params.id), stepNumber);
      res.json(r);
    } catch (err: any) {
      res.status(400).json({ error: err.message });
    }
  }));
  app.get("/api/runbooks/executions", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getRunbookExecutions(20));
  }));

  // #11 Regulator Inbox
  app.post("/api/regulator-inbox/post", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const user = (req as any).user;
    const r = await extras2.postInboxMessage({
      threadId: req.body?.threadId,
      fromRole: user?.role || "auditor",
      fromUser: user?.username || "anonymous",
      subject: req.body?.subject || "(no subject)",
      body: req.body?.body || "",
      evidenceLinks: req.body?.evidenceLinks,
    });
    res.json(r);
  }));
  app.get("/api/regulator-inbox/messages", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getInboxMessages(100));
  }));
  app.post("/api/regulator-inbox/close/:threadId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras2.closeInboxThread(String(req.params.threadId)));
  }));

  // #12 Cost of Control
  app.post("/api/control-cost/snapshot", requirePlatformRole("admin"), asyncHandler(async (_req, res) => {
    res.json(await extras2.snapshotControlCosts());
  }));
  app.get("/api/control-cost/latest", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getControlCostsLatest());
  }));

  // #13 Failover Demo
  app.post("/api/failover-demo/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const fromRegion = req.body?.fromRegion || "kampala-central";
    const toRegion = req.body?.toRegion || "entebbe-airport";
    const r = await extras2.runFailoverDemo((req as any).user?.username || "admin", fromRegion, toRegion);
    res.json(r);
  }));
  app.get("/api/failover-demo/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getFailoverDemoRuns(20));
  }));

  // #14 Business Logic Pentest
  app.post("/api/business-logic-pentest/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.runBusinessLogicPentest((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/business-logic-pentest/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getBusinessLogicPentestRuns(20));
  }));

  // #15 Accessibility Audit
  app.post("/api/accessibility-audit/run", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras2.runAccessibilityAudit((req as any).user?.username || "admin");
    res.json(r);
  }));
  app.get("/api/accessibility-audit/runs", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras2.getAccessibilityAudits(20));
  }));

  // ====================================================================
  // Wave-3 Regulator Pilot Enhancements (10 modules)
  // ====================================================================
  const extras3 = await import("./lib/pilot-readiness-extras-3");

  // Auto-seed default model cards & sub-processors on first run
  try { await extras3.seedDefaultModelCards(); await extras3.seedDefaultSubProcessors(); } catch (e) { /* best-effort */ }

  // 1. Pentest evidence locker
  app.post("/api/pentest-reports", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const u = (req as any).user?.username || "admin";
    const r = await extras3.uploadPentestReport({ ...req.body, uploadedBy: u });
    res.json(r);
  }));
  app.get("/api/pentest-reports", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listPentestReports());
  }));
  app.get("/api/pentest-reports/:id/verify", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await extras3.verifyPentestReport(String(req.params.id)));
  }));

  // 2. Reproducible build manifest
  app.post("/api/build-manifest/capture", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const u = (req as any).user?.username || "admin";
    res.json(await extras3.captureBuildManifest(u));
  }));
  app.get("/api/build-manifest/list", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listBuildManifests());
  }));
  app.get("/api/build-manifest/latest", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.getLatestBuildManifest());
  }));

  // 3. AI Model Cards
  app.post("/api/model-cards", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras3.upsertModelCard(req.body));
  }));
  app.get("/api/model-cards", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listModelCards());
  }));

  // 4. AI Appeals
  app.post("/api/ai-appeals", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras3.createAiAppeal(req.body));
  }));
  app.post("/api/ai-appeals/:id/decide", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const u = (req as any).user?.username || "admin";
    res.json(await extras3.decideAiAppeal({ id: req.params.id, ...req.body, reviewerId: u }));
  }));
  app.get("/api/ai-appeals", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await extras3.listAiAppeals(req.query.status as string | undefined));
  }));

  // 5. Capacity / load drill
  app.post("/api/load-drill/run", requireRole("admin"), asyncHandler(async (req, res) => {
    const u = (req as any).user?.username || "admin";
    res.json(await extras3.runLoadDrill({ triggeredBy: u, ...req.body }));
  }));
  app.get("/api/load-drill/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listLoadDrillRuns());
  }));

  // 6. NTP / time-sync drift
  app.post("/api/ntp-drift/check", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const u = (req as any).user?.username || "admin";
    res.json(await extras3.runNtpDriftCheck({ triggeredBy: u, ...req.body }));
  }));
  app.get("/api/ntp-drift/checks", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listNtpDriftChecks());
  }));

  // 7. Sub-processors register
  app.post("/api/sub-processors", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(await extras3.upsertSubProcessor(req.body));
  }));
  app.get("/api/sub-processors", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listSubProcessors());
  }));

  // 8a. Consent ledger
  app.post("/api/consent", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras3.recordConsent(req.body));
  }));
  app.post("/api/consent/:id/revoke", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras3.revokeConsent(String(req.params.id)));
  }));
  app.get("/api/consent", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await extras3.listConsent(req.query.customerRef as string | undefined));
  }));

  // 8b. Right-to-erasure cascade drill
  // POST endpoint REMOVED 2026-05-04 (FU-014): runErasureCascadeDrill seeded
  // fake consent_ledger rows before deletion (refusal-criterion #1 violation).
  // Real-wired erasure now lives at runErasureDrill in
  // server/lib/wave13-pilot-readiness.ts and is exercised via the Wave-13 smoke
  // runner (POST /api/wave13/smoke/run) and the standalone verification script
  // scripts/verify-erasure-drill.ts. See FOLLOW-UPS.md FU-014.
  //
  // GET endpoint RETAINED as historical-only — provides read-only access to
  // the 1 pre-cutover synthetic receipt per immutability. New receipts no
  // longer write to erasure_cascade_runs.
  app.get("/api/erasure-cascade/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listErasureCascadeRuns());
  }));

  // 9. Quarterly attestation
  app.post("/api/quarterly-attestation/generate", requireRole("admin"), asyncHandler(async (req, res) => {
    const u = (req as any).user?.username || "admin";
    const now = new Date();
    const year = req.body?.year ?? now.getFullYear();
    const quarter = req.body?.quarter ?? Math.floor(now.getMonth() / 3) + 1;
    res.json(await extras3.generateQuarterlyAttestation({ year, quarter, generatedBy: u }));
  }));
  app.get("/api/quarterly-attestation/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras3.listQuarterlyAttestations());
  }));
  app.get("/api/quarterly-attestation/:id", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const r = await extras3.getQuarterlyAttestation(String(req.params.id));
    if (!r) return res.status(404).json({ error: "Not found" });
    res.json(r);
  }));

  // Public verifier endpoints (no auth — anyone with a signed bundle can verify)
  app.post("/api/public/evidence/verify", asyncHandler(async (req, res) => {
    const { payload, signature } = req.body || {};
    if (!payload || !signature) return res.status(400).json({ valid: false, error: "Both payload and signature are required" });
    res.json(extras3.publicVerifyEvidenceBundle({ payload, signature }));
  }));
  app.post("/api/public/attestation/verify", asyncHandler(async (req, res) => {
    const { contentMd, signature } = req.body || {};
    if (!contentMd || !signature) return res.status(400).json({ valid: false, error: "Both contentMd and signature are required" });
    res.json(await extras3.verifyQuarterlyAttestation({ contentMd, signature }));
  }));

  // ============= WAVE-4 PILOT-READINESS EXTRAS (Tier-A) =============
  const extras4 = await import("./lib/pilot-readiness-extras-4");
  try { await extras4.seedDefaultCrossBorderEntries(); } catch (e) { /* best-effort */ }

  // Public Trust Portal — NO AUTH (regulator + customer facing)
  app.get("/api/public/trust-portal", asyncHandler(async (_req, res) => {
    // DISABLED (honest-floor pass): this PUBLIC, no-auth endpoint previously served SYNTHETIC
    // pilot-readiness trust/compliance data. A public trust surface must never publish fabricated
    // compliance data — a SIMULATED label cannot travel with scraped/cached/quoted public data, so the
    // honest state is "nothing real to attest yet". Disabled until it serves REAL measured attestation.
    res.status(503).json({ status: "unavailable", message: "The public trust portal is not yet available; it will return once it serves real, measured attestation data." });
  }));

  // Customer breach-notification drill — REMOVED (Tier-1 cleanup 2026-06-30):
  // extras4.runBreachNotificationDrill / listBreachNotificationDrills were synthetic
  // generators (deleted). The separate REAL /api/breach-drill/run module is unaffected.

  // Cross-border data transfer log
  const crossBorderSchema = z.object({
    destinationCountry: z.string().min(2).max(100),
    destinationVendor: z.string().min(1).max(200),
    dataCategories: z.string().min(1).max(500),
    legalBasis: z.string().min(1).max(500),
    encryptionMethod: z.string().min(1).max(200),
    retentionDays: z.number().int().min(0).max(36500),
    bytesTransferred: z.number().int().min(0).optional(),
    recordCount: z.number().int().min(0).optional(),
    pdpoSection29Compliant: z.boolean().optional(),
    notes: z.string().max(2000).optional(),
  });
  app.post("/api/cross-border/log", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const parsed = crossBorderSchema.safeParse(req.body || {});
    if (!parsed.success) return res.status(400).json({ error: "Invalid input", details: parsed.error.errors });
    const u = req.session?.user?.username || "system";
    res.json(await extras4.logCrossBorderTransfer({ ...parsed.data, loggedBy: u }));
  }));
  app.get("/api/cross-border/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras4.listCrossBorderTransfers());
  }));
  app.get("/api/cross-border/report", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras4.crossBorderReport());
  }));

  // SLA breach tracker + service credits
  app.post("/api/sla-breaches/scan", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras4.scanSlaBreaches({ triggeredBy: u }));
  }));
  app.get("/api/sla-breaches/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras4.listSlaBreaches());
  }));
  app.post("/api/sla-breaches/:id/issue-credit", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras4.issueServiceCreditsForBreach({ breachId: req.params.id, issuedBy: u }));
  }));
  app.get("/api/service-credits/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras4.listServiceCredits());
  }));

  // ========================= WAVE-5: Regulator-Pilot Suite (7 modules) =========================
  const extras5 = await import("./lib/pilot-readiness-extras-5");
  try { await extras5.seedDefaultAmlTypologies(); } catch { /* best-effort */ }

  // 1. Regulator Challenge Console
  const regChallengeSchema = z.object({
    scenario: z.object({
      txnAmountUgx: z.number().min(0).max(10_000_000_000),
      channel: z.string().min(1).max(40),
      counterpartyCountry: z.string().max(4).optional(),
      customerSegment: z.string().max(40).optional(),
      hourOfDay: z.number().min(0).max(23).optional(),
      deviceTrustScore: z.number().min(0).max(100).optional(),
      description: z.string().max(500).optional(),
    }),
  });
  app.post("/api/regulator-challenge/submit", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const parsed = regChallengeSchema.safeParse(req.body || {});
    if (!parsed.success) return res.status(400).json({ error: "Invalid scenario", details: parsed.error.format() });
    const u = req.session?.user?.username || "regulator";
    res.json(await extras5.submitRegulatorChallenge({ submittedBy: u, scenario: parsed.data.scenario }));
  }));
  app.get("/api/regulator-challenge/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.listRegulatorChallenges());
  }));

  // 2. AML Typology Coverage Matrix
  app.get("/api/aml-typologies/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.listAmlTypologies());
  }));
  app.post("/api/aml-typologies/run-tests", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras5.runAmlTypologyTests({ triggeredBy: u }));
  }));

  // 3. SAR Filing SLA Tracker
  const sarCreateSchema = z.object({
    customerRef: z.string().min(1).max(100),
    suspicionType: z.string().min(1).max(100),
    amountUgxMicros: z.number().min(0).optional(),
    slaHours: z.number().min(1).max(720).optional(),
    notes: z.string().max(2000).optional(),
  });
  app.post("/api/sar-filings/create", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const parsed = sarCreateSchema.safeParse(req.body || {});
    if (!parsed.success) return res.status(400).json({ error: "Invalid SAR draft", details: parsed.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras5.createSarFiling({ ...parsed.data, createdBy: u }));
  }));
  app.post("/api/sar-filings/:id/file", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const fiaRef = typeof req.body?.fiaConfirmationRef === "string" ? req.body.fiaConfirmationRef.slice(0, 100) : undefined;
    try {
      res.json(await extras5.fileSarFiling({ sarId: req.params.id, fiaConfirmationRef: fiaRef, filedBy: u }));
    } catch (e: any) {
      res.status(400).json({ error: e.message || "Failed to file SAR" });
    }
  }));
  app.get("/api/sar-filings/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.listSarFilings());
  }));
  app.get("/api/sar-filings/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.sarFilingStats());
  }));

  // 4. Vulnerability Disclosure Portal — public submit + security.txt
  app.get("/.well-known/security.txt", (_req, res) => {
    res.type("text/plain").send(extras5.getSecurityTxt());
  });
  const vdpSubmitSchema = z.object({
    reporterHandle: z.string().max(80).optional(),
    reporterEmail: z.string().email().max(200).optional(),
    reportTitle: z.string().min(5).max(200),
    reportSummary: z.string().min(20).max(8000),
    severity: z.enum(["critical", "high", "medium", "low", "info"]).optional(),
    affectedComponent: z.string().max(200).optional(),
  });
  app.post("/api/public/vdp/submit", asyncHandler(async (req: any, res) => {
    const parsed = vdpSubmitSchema.safeParse(req.body || {});
    if (!parsed.success) return res.status(400).json({ error: "Invalid report", details: parsed.error.format() });
    const ip = getClientIp(req);
    res.json(await extras5.submitVdpReport({ ...parsed.data, ipAddress: ip }));
  }));
  app.get("/api/vdp/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.listVdpReports());
  }));
  app.get("/api/vdp/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.vdpStats());
  }));
  const vdpTriageSchema = z.object({
    severity: z.enum(["critical", "high", "medium", "low", "info"]).optional(),
    triageNotes: z.string().min(5).max(4000),
  });
  app.post("/api/vdp/:id/triage", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const parsed = vdpTriageSchema.safeParse(req.body || {});
    if (!parsed.success) return res.status(400).json({ error: "Invalid triage", details: parsed.error.format() });
    const u = req.session?.user?.username || "system";
    try { res.json(await extras5.triageVdpReport({ reportId: req.params.id, ...parsed.data, triagedBy: u })); }
    catch (e: any) { res.status(404).json({ error: e.message }); }
  }));
  const vdpResolveSchema = z.object({
    resolutionNotes: z.string().min(5).max(4000),
    publicAcknowledged: z.boolean().optional(),
  });
  app.post("/api/vdp/:id/resolve", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const parsed = vdpResolveSchema.safeParse(req.body || {});
    if (!parsed.success) return res.status(400).json({ error: "Invalid resolution", details: parsed.error.format() });
    const u = req.session?.user?.username || "system";
    try { res.json(await extras5.resolveVdpReport({ reportId: req.params.id, ...parsed.data, resolvedBy: u })); }
    catch (e: any) { res.status(404).json({ error: e.message }); }
  }));

  // 5. Continuous Compliance Score
  app.post("/api/compliance-score/compute", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras5.computeComplianceScore({ computedBy: u }));
  }));
  app.get("/api/compliance-score/current", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.getCurrentComplianceScore());
  }));
  app.get("/api/compliance-score/trend", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const days = Math.min(365, Math.max(7, parseInt((req.query.days as string) || "90", 10) || 90));
    res.json(await extras5.getComplianceScoreTrend(days));
  }));

  // 6. Mobile-Money Fraud Pattern Suite
  app.get("/api/momo-fraud/scenarios", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(extras5.listMomoScenarios());
  }));
  app.post("/api/momo-fraud/run-suite", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras5.runMomoFraudSuite({ triggeredBy: u }));
  }));
  app.get("/api/momo-fraud/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.listMomoFraudTests());
  }));

  // 7. Right-to-Explanation Customer API (no-auth, rate-limited via existing global limiter)
  const decisionExplainSchema = z.object({
    transactionRef: z.string().min(3).max(100),
    customerRef: z.string().min(3).max(100),
  });
  app.post("/api/customer/decision/explain", asyncHandler(async (req: any, res) => {
    const parsed = decisionExplainSchema.safeParse(req.body || {});
    if (!parsed.success) return res.status(400).json({ error: "Invalid request", details: parsed.error.format() });
    const ip = getClientIp(req);
    res.json(await extras5.generateDecisionExplanation({ ...parsed.data, requestSourceIp: ip }));
  }));
  app.get("/api/decision-explanations/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras5.listDecisionExplanations());
  }));

  // Trust-portal Wave-5 supplemental snapshot (public no-auth)
  app.get("/api/public/trust-portal/wave5", asyncHandler(async (_req, res) => {
    // DISABLED (honest-floor pass): PUBLIC no-auth endpoint served SYNTHETIC wave-5 trust data. Public
    // fabricated compliance data is uncontainable once scraped/cached. Disabled until it serves REAL data.
    res.status(503).json({ status: "unavailable", message: "The public trust portal is not yet available; it will return once it serves real, measured attestation data." });
  }));

  // ========================= WAVE-6: Pilot Maturity Suite (14 modules) =========================
  const extras6 = await import("./lib/pilot-readiness-extras-6");
  try { await extras6.seedFeeDisclosures("system"); } catch { /* best-effort */ }
  // FU-021 2026-05-08: refreshSanctionsLists boot-time call removed —
  // function retired; calling it here only produced a stderr line and an audit
  // row on every boot with no useful side-effect. See FOLLOW-UPS.md FU-021.

  // 1. Regulator Observer Mode
  const issueObserverSchema = z.object({
    regulatorName: z.string().min(2).max(80),
    agencyCode: z.string().min(2).max(20),
    scopes: z.array(z.string().min(1).max(40)).min(1).max(20),
    ttlHours: z.number().int().min(1).max(720),
  });
  app.post("/api/regulator-observer/issue", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = issueObserverSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    // Commit-before-respond (security-token revocation-race class fix): the bare
    // `db` proxy commits with the ambient request tx on res.finish — AFTER the
    // response is flushed. Wrap the INSERT in a bounded withTenantDbPhase so it
    // COMMITS before res.json. regulator_observer_credentials is global/non-RLS,
    // so the tenant GUC set inside the phase is inert here.
    const result = await withTenantDbPhase(req, () => extras6.issueObserverCredential({ ...p.data, createdBy: u }));
    res.json(result);
  }));
  app.get("/api/regulator-observer/credentials", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listObserverCredentials());
  }));
  app.post("/api/regulator-observer/:id/revoke", requireRole("admin"), asyncHandler(async (req: any, res) => {
    // Commit-before-respond (see issue route): the revoke UPDATE must be durable
    // before we 200, or a zero-delay re-validate races the deferred commit and a
    // just-revoked observer token still authorizes.
    const result = await withTenantDbPhase(req, () => extras6.revokeObserverCredential(String(req.params.id)));
    res.json(result);
  }));
  const replaySchema = z.object({
    credentialId: z.string().min(1),
    resourceType: z.string().min(1).max(40),
    resourceRef: z.string().min(1).max(120),
    examinerNote: z.string().max(2000).optional(),
  });
  app.post("/api/regulator-observer/replay", requireRole("admin", "auditor"), asyncHandler(async (req: any, res) => {
    const p = replaySchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    try { res.json(await extras6.recordObserverReplay({ ...p.data, ipAddress: req.ip })); }
    catch (e: any) { res.status(403).json({ error: e?.message || "Replay rejected" }); }
  }));
  app.get("/api/regulator-observer/replays", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    res.json(await extras6.listObserverReplays(req.query.credentialId as string | undefined));
  }));
  // Token-authenticated observer access (no session — examiner uses one-time observer token)
  const tokenReplaySchema = z.object({
    resourceType: z.string().min(1).max(40),
    resourceRef: z.string().min(1).max(120),
    examinerNote: z.string().max(2000).optional(),
  });
  app.post("/api/regulator-observer/access", asyncHandler(async (req: any, res) => {
    const token = (req.get("x-observer-token") || req.body?.observerToken || "").toString().trim();
    if (!token) return res.status(401).json({ error: "Missing X-Observer-Token header" });
    const p = tokenReplaySchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    try { res.json(await extras6.recordObserverReplayByToken({ token, ...p.data, ipAddress: req.ip })); }
    catch (e: any) { res.status(401).json({ error: e?.message || "Token rejected" }); }
  }));
  app.get("/api/regulator-observer/whoami", asyncHandler(async (req: any, res) => {
    const token = (req.get("x-observer-token") || "").toString().trim();
    if (!token) return res.status(401).json({ error: "Missing X-Observer-Token header" });
    const cred = await extras6.verifyObserverToken(token);
    if (!cred) return res.status(401).json({ error: "Invalid, expired, or revoked observer token" });
    res.json({ id: cred.id, regulatorName: cred.regulatorName, agencyCode: cred.agencyCode, scopes: cred.scopes, expiresAt: cred.expiresAt });
  }));

  // 2. BoU Reports
  const bouReportSchema = z.object({
    reportCode: z.enum(["MM-DAILY-SETTLE", "AML-FIA-Q", "CYBER-RISK-Q"]),
    periodStart: z.string().datetime(),
    periodEnd: z.string().datetime(),
  });
  app.post("/api/bou-reports/generate", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = bouReportSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(500).json({ error: "No tenant context — refusing to generate an unscoped return" });
    const u = req.session?.user?.username || "system";
    res.json(await extras6.generateBouReport({ reportCode: p.data.reportCode, periodStart: new Date(p.data.periodStart), periodEnd: new Date(p.data.periodEnd), generatedBy: u, tenantId }));
  }));
  app.post("/api/bou-reports/:id/submit", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras6.submitBouReport(String(req.params.id)));
  }));
  app.get("/api/bou-reports/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listBouReports());
  }));

  // 3. Sanctions & PEP Screening — FU-021 RETIREMENT 2026-05-08.
  // POST /refresh and POST /run-test return HTTP 410 Gone with structured retirement
  // bodies. GET /lists and GET /tests preserved for read-only access to retained
  // sanctions_lists and sanctions_screening_tests rows (immutability). Substrate gap
  // was named in FU-019's retirement disclosure; FU-021 completes the disposition
  // (cross-pointer-completion relationship type — see extras-6.ts §3 header for the
  // disciplinary observation). Dual-layer audit pattern: function-body retirement
  // (Stage A1) fires *_RETIREMENT_INVOKED; route-handler 410 (Stage A2 below) fires
  // *_ROUTE_INVOKED. Distinct codes because the route returns 410 directly without
  // invoking the retired function, so each layer's audit fires from a different
  // bypass-attempt vector. See FOLLOW-UPS.md FU-021.
  app.post("/api/sanctions/refresh", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    try {
      await storage.createAuditLog({
        userId: null,
        action: "EXTRAS6_SANCTIONS_REFRESH_ROUTE_INVOKED",
        resource: "POST /api/sanctions/refresh",
        details: JSON.stringify({ retiredAt: "2026-05-08", fu: "FU-021", route: "POST /api/sanctions/refresh", username: req.session?.user?.username ?? null }).slice(0, 65000),
        ipAddress: req.ip ?? null,
      });
    } catch (auditErr: any) {
      logger.child('fu-021').error('route audit-log write failed; 410 proceeds', { error: auditErr instanceof Error ? auditErr : new Error(String(auditErr?.message || auditErr)) });
    }
    return res.status(410).json({
      error: "Gone",
      code: "EXTRAS6_SANCTIONS_REFRESH_RETIRED",
      message: "refreshSanctionsLists retired 2026-05-08 under FU-021. Schema fields (recordCount, version, listHashHex, source, refreshedAt) describe a refresh operation that pulls list data from authoritative upstream sources (OFAC, UN, EU, World-Check PEP). The function populated sanctions_lists from a hardcoded SANCTIONS_DEFAULTS constant array; no upstream pull occurred. The substrate gap was named in FU-019's retirement disclosure; FU-021 completes the disposition. Existing sanctions_lists rows retained per immutability and remain queryable at GET /api/sanctions/lists. See FOLLOW-UPS.md FU-021.",
      retiredAt: "2026-05-08",
      historical: { listEndpoint: "/api/sanctions/lists" },
    });
  }));
  app.get("/api/sanctions/lists", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listSanctionsLists());
  }));
  app.post("/api/sanctions/run-test", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    try {
      await storage.createAuditLog({
        userId: null,
        action: "EXTRAS6_SANCTIONS_SCREENING_TEST_ROUTE_INVOKED",
        resource: "POST /api/sanctions/run-test",
        details: JSON.stringify({ retiredAt: "2026-05-08", fu: "FU-021", route: "POST /api/sanctions/run-test", username: req.session?.user?.username ?? null }).slice(0, 65000),
        ipAddress: req.ip ?? null,
      });
    } catch (auditErr: any) {
      logger.child('fu-021').error('route audit-log write failed; 410 proceeds', { error: auditErr instanceof Error ? auditErr : new Error(String(auditErr?.message || auditErr)) });
    }
    return res.status(410).json({
      error: "Gone",
      code: "EXTRAS6_SANCTIONS_SCREENING_TEST_RETIRED",
      message: "runSanctionsScreeningTest retired 2026-05-08 under FU-021. Schema fields (totalSyntheticTargets, truePositives, falseNegatives, recallPct, passed, listsCheckedJson) describe a screening-test execution against synthetic positive targets to measure recall against the active sanctions/PEP lists. The function asserted outcome metrics that were hardcoded constants rather than results of test execution; no screening logic ran. listsCheckedJson was derived from sanctions_lists rows that themselves carry the substrate gap retired in refreshSanctionsLists (FU-021) and named in FU-019's retirement disclosure. Existing sanctions_screening_tests rows retained per immutability and remain queryable at GET /api/sanctions/tests. See FOLLOW-UPS.md FU-021.",
      retiredAt: "2026-05-08",
      historical: { listEndpoint: "/api/sanctions/tests" },
    });
  }));
  app.get("/api/sanctions/tests", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listSanctionsScreeningTests());
  }));

  // 4. Stress Tests
  const stressSchema = z.object({
    scenarioCode: z.enum(["UGX-DEPRECIATION-30", "OIL-SHOCK-LIQUIDITY", "INTERBANK-FREEZE", "MOMO-MASS-CASHOUT"]),
    parameters: z.record(z.any()).optional(),
  });
  app.get("/api/stress-tests/scenarios", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listStressScenarios());
  }));
  app.post("/api/stress-tests/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = stressSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras6.runStressTest({ ...p.data, ranBy: u }));
  }));
  app.get("/api/stress-tests/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listStressTestRuns());
  }));

  // 5. Insider Threat Pack
  app.get("/api/insider-threat/scenarios", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listInsiderScenarios());
  }));
  app.post("/api/insider-threat/run-pack", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras6.runInsiderThreatPack({ ranBy: u }));
  }));
  app.get("/api/insider-threat/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listInsiderRuns());
  }));

  // 6. DR Failover Drill
  const drDrillSchema = z.object({ regionFrom: z.string().min(1).max(40), regionTo: z.string().min(1).max(40) });
  app.post("/api/dr-failover/run-drill", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = drDrillSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras6.runDrFailoverDrill({ ...p.data, ranBy: u }));
  }));
  app.get("/api/dr-failover/drills", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listDrFailoverDrills());
  }));

  // 7. Code Provenance
  const provenanceSchema = z.object({
    gitSha: z.string().min(7).max(64),
    environment: z.enum(["production", "staging", "sandbox"]),
    approvers: z.array(z.string().min(1).max(80)).min(1).max(10),
  });
  app.post("/api/code-provenance/record", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = provenanceSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras6.recordCodeProvenance({ ...p.data, deployedBy: u }));
  }));
  app.get("/api/code-provenance/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listCodeProvenance());
  }));

  // 8. Bug Bounty Rewards
  const bountySchema = z.object({
    vdpReportId: z.string().min(1),
    tier: z.enum(["CRITICAL", "HIGH", "MEDIUM", "LOW"]),
    hallOfFameHandle: z.string().max(60).optional(),
    publicNote: z.string().max(500).optional(),
  });
  app.post("/api/bug-bounty/award", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = bountySchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras6.awardBugBounty({ ...p.data, awardedBy: u }));
  }));
  app.get("/api/bug-bounty/rewards", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listBugBountyRewards());
  }));
  app.get("/api/bug-bounty/metrics", asyncHandler(async (_req, res) => {
    res.json(await extras6.bugBountyMetrics());
  }));

  // 9. Customer Protection Hub
  const complaintSchema = z.object({
    customerRef: z.string().min(1).max(60),
    category: z.enum(["FEE_DISPUTE", "UNAUTHORIZED_TXN", "SERVICE_DENIED", "OTHER"]),
    description: z.string().min(10).max(2000),
    slaHours: z.number().int().min(1).max(720).optional(),
  });
  app.post("/api/complaints/open", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = complaintSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras6.openComplaint(p.data));
  }));
  const resolveComplaintSchema = z.object({ resolution: z.string().min(5).max(2000) });
  app.post("/api/complaints/:id/resolve", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = resolveComplaintSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras6.resolveComplaint({ id: String(req.params.id), resolution: p.data.resolution }));
  }));
  app.get("/api/complaints/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listComplaints());
  }));
  app.get("/api/fee-disclosures/list", asyncHandler(async (_req, res) => {
    res.json(await extras6.listFeeDisclosures());
  }));

  // 10. SWIFT Integrity
  const swiftSchema = z.object({
    messageRef: z.string().min(1).max(60),
    messageType: z.string().min(2).max(20),
    bicSender: z.string().min(8).max(11),
    bicReceiver: z.string().min(8).max(11),
    amount: z.number().min(0),
    currency: z.string().min(3).max(3),
    rawMessage: z.string().max(20000).optional(),
  });
  app.post("/api/swift-integrity/check", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = swiftSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras6.checkSwiftMessage(p.data));
  }));
  app.get("/api/swift-integrity/checks", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listSwiftChecks());
  }));

  // 11. Multi-Language Customer Strings (public no-auth — safe, returns static text only)
  app.get("/api/i18n/languages", asyncHandler(async (_req, res) => {
    res.json(extras6.listSupportedLanguages());
  }));
  app.get("/api/i18n/string", asyncHandler(async (req, res) => {
    const key = String(req.query.key ?? "");
    const lang = String(req.query.lang ?? "en");
    if (!key) return res.status(400).json({ error: "key required" });
    const value = extras6.getCustomerString(key, lang);
    if (!value) return res.status(404).json({ error: "Unknown key", key });
    res.json({ key, lang, value });
  }));

  // 12. Mock Supervisory Examination — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras6.runMockExam / listMockExams / listExamTypes were synthetic generators (deleted).

  // 13. Privacy Auto-Deletion Drill
  const privacyDrillSchema = z.object({ policyCode: z.enum(["AUDIT-LOGS", "TXN-PII", "CHAT-SESSIONS", "WEB-SESSIONS"]) });
  app.get("/api/privacy-deletion/policies", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(extras6.listRetentionPolicies());
  }));
  app.post("/api/privacy-deletion/run", requireRole("admin", "risk_manager"), requireStepUp, asyncHandler(async (req: any, res) => {
    const p = privacyDrillSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras6.runPrivacyDeletionDrill({ ...p.data, ranBy: u }));
  }));
  app.get("/api/privacy-deletion/drills", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listPrivacyDeletionDrills());
  }));

  // 14. Open Banking Pre-Readiness
  app.get("/api/open-banking/catalog", asyncHandler(async (_req, res) => {
    res.json(extras6.listOpenBankingCatalog());
  }));
  const obConsentSchema = z.object({
    customerRef: z.string().min(1).max(60),
    tppName: z.string().min(2).max(80),
    dataCategories: z.array(z.string().min(1).max(40)).min(1).max(10),
    scopes: z.array(z.string().min(1).max(40)).min(1).max(10),
    ttlDays: z.number().int().min(1).max(365),
  });
  app.post("/api/open-banking/consent/grant", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = obConsentSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras6.grantOpenBankingConsent(p.data));
  }));
  app.post("/api/open-banking/consent/:id/revoke", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras6.revokeOpenBankingConsent(String(req.params.id)));
  }));
  app.get("/api/open-banking/consents", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras6.listOpenBankingConsents());
  }));

  // Trust-portal Wave-6 supplemental snapshot (public no-auth)
  app.get("/api/public/trust-portal/wave6", asyncHandler(async (_req, res) => {
    // DISABLED (honest-floor pass): PUBLIC no-auth endpoint served SYNTHETIC wave-6 trust data. Public
    // fabricated compliance data is uncontainable once scraped/cached. Disabled until it serves REAL data.
    res.status(503).json({ status: "unavailable", message: "The public trust portal is not yet available; it will return once it serves real, measured attestation data." });
  }));

  // ========================= WAVE-7: Final Pilot Maturity (14 modules) =========================
  const extras7 = await import("./lib/pilot-readiness-extras-7");
  try { await extras7.seedExtras7(); } catch { /* best-effort */ }
  const extras8 = await import("./lib/pilot-readiness-extras-8");
  try { await extras8.seedExtras8(); } catch { /* best-effort */ }
  // P4.3 Option A (FU-045) — FU-003-sanctioned expected-findings register.
  // Idempotent ON CONFLICT DO NOTHING seed of the three FU-003 modules
  // (sod-checker, eol-inventory, model-card-audit) so the dashboard can
  // surface them as EXPECTED-FAIL with FU-003 + BoU §4 narrative pointer
  // instead of indistinguishable FAIL.
  try {
    const w13Expected = await import("./lib/wave13-expected-findings");
    await w13Expected.seedFU003ExpectedFindings();
  } catch { /* best-effort */ }
  // Per-request metric capture for the Prometheus /metrics endpoint
  app.use((req, res, next) => {
    const t0 = Date.now();
    res.on("finish", () => {
      try { extras8.recordRequestMetric(Date.now() - t0, res.statusCode >= 500); } catch { /* */ }
    });
    next();
  });

  // 1. Synthetic Canary
  app.post("/api/synthetic-canary/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const probeCode = typeof req.body?.probeCode === "string" ? req.body.probeCode.slice(0, 50) : "manual";
    res.json(await extras7.runSyntheticCanary(probeCode));
  }));
  app.get("/api/synthetic-canary/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listCanaryRuns());
  }));
  app.get("/api/synthetic-canary/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.getCanaryStats());
  }));

  // 2. CTR
  const ctrCreateSchema = z.object({
    customerRef: z.string().min(1).max(80),
    txnType: z.string().min(1).max(40),
    amountUgx: z.number().int().positive().max(1_000_000_000_000),
    branchCode: z.string().min(1).max(40),
    txnAt: z.string().datetime({ offset: true }).or(z.string().refine((s) => !Number.isNaN(new Date(s).getTime()), { message: "txnAt must be a valid ISO date" })),
  });
  app.post("/api/ctr/create", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = ctrCreateSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras7.createCtrFiling({ ...p.data, txnAt: new Date(p.data.txnAt) }));
  }));
  app.post("/api/ctr/:id/file", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const fiaRef = typeof req.body?.fiaConfirmationRef === "string" ? req.body.fiaConfirmationRef.slice(0, 100) : undefined;
    res.json(await extras7.fileCtrToFia({ id: req.params.id, filedBy: u, fiaConfirmationRef: fiaRef }));
  }));
  app.get("/api/ctr/filings", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listCtrFilings());
  }));
  app.get("/api/ctr/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.getCtrStats());
  }));

  // 3. UBO
  const uboSchema = z.object({
    corporateCustomerRef: z.string().min(1).max(80),
    corporateName: z.string().min(1).max(200),
    ownerName: z.string().min(1).max(120),
    ownerNationalId: z.string().min(1).max(60),
    ownerNationality: z.string().min(2).max(40),
    ownershipPct: z.number().int().min(1).max(100),
    controlType: z.string().min(1).max(60),
    pepStatus: z.number().int().min(0).max(1).optional(),
    sanctionsStatus: z.number().int().min(0).max(1).optional(),
  });
  app.post("/api/ubo/register", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = uboSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    const tenantId = (req as any).session?.tenantId || "default";
    res.json(await extras7.registerUbo({ ...p.data, registeredBy: u, tenantId }));
  }));
  app.get("/api/ubo/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listUboRegistrations());
  }));
  app.get("/api/ubo/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.getUboStats());
  }));

  // 4. Regulator Push-Notification
  const epSchema = z.object({
    endpointCode: z.string().min(2).max(80),
    agencyCode: z.string().min(2).max(20),
    webhookUrl: z.string().url().max(400),
    signingSecret: z.string().min(8).max(200),
  });
  app.post("/api/regulator-push/endpoints", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = epSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras7.createPushEndpoint({ ...p.data, createdBy: u }));
  }));
  app.get("/api/regulator-push/endpoints", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listPushEndpoints());
  }));
  const dispatchSchema = z.object({
    alertCode: z.string().min(2).max(80),
    severity: z.enum(["LOW", "MEDIUM", "HIGH", "CRITICAL"]),
    payload: z.record(z.any()).refine(
      (p) => JSON.stringify(p).length <= 32_768,
      { message: "payload JSON must be <= 32 KB" }
    ),
  });
  app.post("/api/regulator-push/dispatch", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = dispatchSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras7.pushAlertToRegulators(p.data));
  }));
  app.get("/api/regulator-push/deliveries", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listPushDeliveries());
  }));

  // 5. Independent Auditor Read-Only
  const auditorSchema = z.object({
    firmName: z.string().min(2).max(120),
    auditorEmail: z.string().email().max(160),
    scopes: z.array(z.string().min(1).max(40)).min(1).max(20),
    ttlDays: z.number().int().min(1).max(180),
  });
  app.post("/api/auditor/credentials", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = auditorSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    // Commit-before-respond (security-token revocation-race class fix): wrap the
    // INSERT in a bounded withTenantDbPhase so it COMMITS before res.json instead
    // of on the deferred res.finish ambient-tx commit. auditor_credentials is
    // global/non-RLS, so the tenant GUC set inside the phase is inert here.
    const result = await withTenantDbPhase(req, () => extras7.issueAuditorCredential({ ...p.data, createdBy: u }));
    res.json(result);
  }));
  app.get("/api/auditor/credentials", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listAuditorCredentials());
  }));
  app.post("/api/auditor/credentials/:id/revoke", requireRole("admin"), asyncHandler(async (req: any, res) => {
    // Commit-before-respond (see issue route): durable revoke before 200 so a
    // zero-delay re-validate cannot race the deferred commit.
    const result = await withTenantDbPhase(req, () => extras7.revokeAuditorCredential(String(req.params.id)));
    res.json(result);
  }));
  app.get("/api/auditor/access-logs", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listAuditorAccessLogs());
  }));
  // public no-auth endpoints for auditor token use
  app.get("/api/auditor-portal/whoami", asyncHandler(async (req, res) => {
    const token = String(req.headers["x-auditor-token"] || "");
    const cred = await extras7.verifyAuditorToken(token);
    if (!cred) return res.status(401).json({ error: "Invalid or expired auditor token" });
    res.json({ firmName: cred.firmName, auditorEmail: cred.auditorEmail, scopes: cred.scopes, expiresAt: cred.expiresAt });
  }));
  const auditorAccessSchema = z.object({
    resourceType: z.string().min(1).max(60),
    resourceRef: z.string().min(1).max(200),
  });
  app.post("/api/auditor-portal/access", asyncHandler(async (req, res) => {
    const token = String(req.headers["x-auditor-token"] || "");
    const ip = (req.ip || req.socket.remoteAddress || "").toString();
    const p = auditorAccessSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    try {
      const result = await extras7.recordAuditorAccess({ token, ...p.data, ipAddress: ip });
      res.json(result);
    } catch (e: any) {
      if (e instanceof extras7.AuditorAuthorizationError) {
        return res.status(403).json({ error: String(e.message) });
      }
      res.status(401).json({ error: String(e?.message || e) });
    }
  }));
  app.get("/api/auditor-portal/scope-matrix", asyncHandler(async (_req, res) => {
    res.json(extras7.listAuditorScopeMatrix());
  }));

  // 6. Phishing Simulation
  const phishSchema = z.object({
    campaignName: z.string().min(2).max(160),
    targetGroup: z.string().min(1).max(60),
    totalTargets: z.number().int().min(1).max(100000),
  });
  app.post("/api/phishing/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = phishSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras7.runPhishingCampaign({ ...p.data, ranBy: u }));
  }));
  app.get("/api/phishing/campaigns", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listPhishingCampaigns());
  }));
  app.get("/api/phishing/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.getPhishingStats());
  }));

  // 7. Ransomware Refusal Drill
  const ransomSchema = z.object({
    scenarioCode: z.string().min(2).max(60).optional(),
    ransomDemandUgx: z.number().int().positive().max(1_000_000_000_000),
  });
  app.post("/api/ransomware/drill", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = ransomSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras7.runRansomwareDrill({ ...p.data, ranBy: u }));
  }));
  app.get("/api/ransomware/drills", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listRansomwareDrills());
  }));

  // 8. Segmentation Proof
  app.post("/api/segmentation/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras7.runSegmentationTests(u));
  }));
  app.get("/api/segmentation/tests", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listSegmentationTests());
  }));

  // 9. OS Vuln Scanner
  const osScanSchema = z.object({ imageRef: z.string().min(2).max(200) });
  app.post("/api/os-vuln/scan", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = osScanSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras7.runOsVulnScan({ ...p.data, ranBy: u }));
  }));
  app.get("/api/os-vuln/scans", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listOsVulnScans());
  }));

  // 10. Performance Budget
  app.post("/api/perf-budget/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras7.runPerformanceBudget(u));
  }));
  app.get("/api/perf-budget/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listPerformanceBudgets());
  }));

  // 11. Board Report — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras7.generateBoardReport / listBoardReports / getBoardReportPayload were synthetic (deleted).

  // 12. Trust Dashboard — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras7.captureTrustSnapshot / getLatestTrustSnapshot / listTrustSnapshots were synthetic (deleted).
  // public no-auth (kept disabled — never referenced the deleted generators)
  app.get("/api/public/trust-dashboard/latest", asyncHandler(async (_req, res) => {
    // DISABLED (honest-floor pass): PUBLIC no-auth endpoint served SYNTHETIC trust-dashboard snapshots.
    // Public fabricated compliance data is uncontainable once scraped/cached. Disabled until REAL data.
    res.status(503).json({ status: "unavailable", message: "The public trust dashboard is not yet available; it will return once it serves real, measured attestation data." });
  }));

  // 13. NPS Settlement — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras7.captureSettlementWindow / listSettlementWindows / getSettlementStats were synthetic (deleted).

  // 14. Tabletop Exercise
  const ttSchema = z.object({
    scenarioCode: z.string().min(2).max(60).optional(),
    participants: z.array(z.string().min(1).max(80)).min(1).max(40),
    detectionScore: z.number().int().min(0).max(100),
    responseScore: z.number().int().min(0).max(100),
    recoveryScore: z.number().int().min(0).max(100),
    communicationScore: z.number().int().min(0).max(100),
    outcomes: z.array(z.string().min(1).max(400)).max(20),
    facilitator: z.string().min(2).max(120),
  });
  app.post("/api/tabletop/record", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = ttSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras7.recordTabletopExercise(p.data));
  }));
  app.get("/api/tabletop/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.listTabletopExercises());
  }));
  app.get("/api/tabletop/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras7.getTabletopStats());
  }));

  // ========================= WAVE-8: Examiner-Proof Suite (14 modules) =========================

  // 1. End-to-End Test Harness
  app.get("/api/e2e/scenarios", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listE2eScenarios());
  }));
  const e2eRunSchema = z.object({ scenarioCode: z.string().min(2).max(80) });
  app.post("/api/e2e/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = e2eRunSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    try { res.json(await extras8.runE2eScenario({ ...p.data, ranBy: u })); }
    catch (e: any) { res.status(404).json({ error: String(e?.message || e) }); }
  }));
  app.get("/api/e2e/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listE2eRuns());
  }));
  app.get("/api/e2e/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.getE2eStats());
  }));

  // 2. Load / Soak Test
  const loadRunSchema = z.object({
    targetEndpoint: z.string().min(1).max(160),
    concurrency: z.number().int().min(1).max(2000),
    durationSec: z.number().int().min(1).max(3600),
    sloP95Ms: z.number().int().min(1).max(10000).optional(),
  });
  app.post("/api/wave8/load-test/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = loadRunSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras8.runLoadTest({ ...p.data, ranBy: u }));
  }));
  app.get("/api/wave8/load-test/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listLoadRuns());
  }));

  // 3. Security Scan
  const scanRunSchema = z.object({
    scanType: z.enum(["headers", "zap-baseline", "csp-eval"]),
    targetUrl: z.string().url().max(400),
  });
  app.post("/api/security-scan/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = scanRunSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras8.runSecurityScan({ ...p.data, ranBy: u }));
  }));
  app.get("/api/security-scan/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listSecurityScans());
  }));

  // 4. Regulator Demo Pack
  app.post("/api/demo-pack/generate", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras8.generateDemoPack({ generatedBy: u }));
  }));
  app.get("/api/demo-pack/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listDemoPacks());
  }));
  const verifyPackSchema = z.object({ payloadJson: z.string().min(2).max(200_000), signatureHex: z.string().regex(/^[a-f0-9]{64}$/) });
  app.post("/api/demo-pack/verify", asyncHandler(async (req, res) => {
    const p = verifyPackSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json({ verified: extras8.verifyDemoPack(p.data.payloadJson, p.data.signatureHex) });
  }));

  // 5. i18n  (specific routes MUST come before /:locale catch-all)
  app.get("/api/i18n/keys/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listTranslationKeys());
  }));
  app.get("/api/i18n/:locale", asyncHandler(async (req, res) => {
    const raw = String(req.params.locale || "en").toLowerCase();
    if (!["en", "lg", "sw"].includes(raw)) {
      return res.status(404).json({ error: "Unsupported locale" });
    }
    res.json(await extras8.getTranslations(raw));
  }));

  // 6. MoMo Sandbox
  const momoSchema = z.object({
    provider: z.enum(["MTN_MOMO", "AIRTEL_MONEY"]),
    txnType: z.enum(["send", "receive", "cashout", "balance"]),
    msisdn: z.string().regex(/^\+?[0-9]{9,15}$/, "MSISDN must be 9-15 digits"),
    amountUgx: z.number().int().min(100).max(50_000_000),
  });
  app.post("/api/momo/sandbox/txn", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const p = momoSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras8.runMomoSandboxTxn(p.data));
  }));
  app.get("/api/momo/sandbox/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listMomoTxns());
  }));
  app.get("/api/momo/sandbox/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.getMomoStats());
  }));

  // 7. DR Failover Drill
  const drSchema = z.object({ scenarioCode: z.string().min(2).max(80) });
  app.post("/api/dr-drill/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = drSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras8.runDrDrill({ ...p.data, ranBy: u }));
  }));
  app.get("/api/dr-drill/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listDrDrills());
  }));

  // 8. Threat Intel (STIX/TAXII)
  app.get("/api/threat-intel/iocs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listIocs());
  }));
  // Public TAXII-style STIX bundle endpoint
  app.get("/api/public/threat-intel/stix", asyncHandler(async (_req, res) => {
    res.json(await extras8.getStixCollection());
  }));
  app.get("/api/threat-intel/check", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const value = String(req.query.value || "").slice(0, 400);
    if (!value) return res.status(400).json({ error: "value query parameter required" });
    res.json(await extras8.checkIoc(value));
  }));

  // 9. SLSA / in-toto
  const slsaSchema = z.object({
    buildId: z.string().min(2).max(120),
    gitCommitSha: z.string().regex(/^[a-f0-9]{7,40}$/),
    subjectName: z.string().min(2).max(200),
    subjectDigestSha256: z.string().regex(/^[a-f0-9]{64}$/),
  });
  app.post("/api/slsa/attest", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = slsaSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras8.generateSlsaAttestation({ ...p.data, createdBy: u }));
  }));
  app.get("/api/slsa/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listAttestations());
  }));
  const slsaVerifySchema = z.object({ predicateJson: z.string().min(2).max(200_000), signatureHex: z.string().regex(/^[a-f0-9]{64}$/) });
  app.post("/api/slsa/verify", asyncHandler(async (req, res) => {
    const p = slsaVerifySchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json({ verified: extras8.verifyAttestation(p.data.predicateJson, p.data.signatureHex) });
  }));

  // 10. Ombudsman Complaints
  const wave8ComplaintSchema = z.object({
    customerName: z.string().min(2).max(160),
    customerContact: z.string().min(5).max(200),
    channel: z.enum(["web", "ussd", "branch", "ombudsman", "email", "phone"]),
    category: z.string().min(2).max(80),
    description: z.string().min(5).max(4000),
    severity: z.enum(["LOW", "MEDIUM", "HIGH", "CRITICAL"]).optional(),
  });
  // Public no-auth complaint submission (consumer protection)
  app.post("/api/public/ombudsman/complaint", asyncHandler(async (req, res) => {
    const p = wave8ComplaintSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const row = await extras8.fileComplaint(p.data);
    res.json({ complaintRef: row.complaintRef, slaHours: row.slaHours, status: row.status });
  }));
  app.get("/api/ombudsman/complaints", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listComplaints());
  }));
  app.get("/api/ombudsman/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.getComplaintStats());
  }));
  const resolveSchema = z.object({ resolution: z.string().min(5).max(2000) });
  app.post("/api/ombudsman/complaints/:id/resolve", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = resolveSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras8.resolveComplaint({ id: req.params.id, resolvedBy: u, resolution: p.data.resolution }));
  }));
  app.post("/api/ombudsman/complaints/:id/escalate", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(await extras8.escalateComplaint({ id: String(req.params.id) }));
  }));

  // 11. Decision Replay
  const wave8ReplaySchema = z.object({
    originalDecisionRef: z.string().min(2).max(200),
    decisionType: z.string().min(2).max(80),
    originalScore: z.number().int().min(0).max(100),
    modelVersion: z.string().min(1).max(80),
    inputs: z.record(z.any()).refine(
      (v) => JSON.stringify(v).length <= 16_384,
      { message: "inputs JSON must be <= 16 KB" }
    ),
  });
  app.post("/api/decision-replay/run", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const p = wave8ReplaySchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras8.replayDecision({ ...p.data, ranBy: u }));
  }));
  app.get("/api/decision-replay/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listReplays());
  }));
  app.get("/api/decision-replay/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.getReplayStats());
  }));

  // 12. Regulator Onboarding Wizard
  const onboardSchema = z.object({
    regulatorAgency: z.enum(["BoU", "FIA", "UCC", "Other"]),
    examinerName: z.string().min(2).max(160),
    examinerEmail: z.string().email().max(160),
  });
  app.post("/api/onboarding/start", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = onboardSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    const u = req.session?.user?.username || "system";
    res.json(await extras8.startOnboardingSession({ ...p.data, startedBy: u }));
  }));
  const advanceSchema = z.object({ step: z.number().int().min(1).max(5) });
  app.post("/api/onboarding/:id/advance", requireRole("admin"), asyncHandler(async (req, res) => {
    const p = advanceSchema.safeParse(req.body);
    if (!p.success) return res.status(400).json({ error: "Invalid input", details: p.error.format() });
    res.json(await extras8.advanceOnboardingStep({ id: String(req.params.id), step: p.data.step }));
  }));
  app.post("/api/onboarding/:id/certificate", requireRole("admin"), asyncHandler(async (req, res) => {
    try { res.json(await extras8.issueReadinessCertificate({ id: String(req.params.id) })); }
    catch (e: any) { res.status(400).json({ error: String(e?.message || e) }); }
  }));
  app.get("/api/onboarding/sessions", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listOnboardingSessions());
  }));

  // 13. Prometheus Metrics + Snapshots
  // Public no-auth Prometheus scraping endpoint
  app.get("/api/public/metrics", asyncHandler(async (_req, res) => {
    const text = await extras8.getPrometheusMetrics();
    res.set("Content-Type", "text/plain; version=0.0.4");
    res.send(text);
  }));
  app.post("/api/metrics/snapshot", requireRole("admin", "risk_manager"), asyncHandler(async (_req, res) => {
    res.json(await extras8.captureMetricsSnapshot());
  }));
  app.get("/api/metrics/snapshots", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras8.listMetricsSnapshots());
  }));

  // 14. OpenAPI 3.1 Spec + Swagger UI (public)
  app.get("/api/public/openapi.json", asyncHandler(async (_req, res) => {
    res.json(extras8.generateOpenApiSpec());
  }));
  app.get("/api/public/swagger", asyncHandler(async (_req, res) => {
    res.set("Content-Type", "text/html; charset=utf-8");
    res.send(`<!DOCTYPE html><html><head><title>AEGIS CYBER Regulator API</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui.css"/>
</head><body>
<div id="swagger-ui"></div>
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/swagger-ui-bundle.js"></script>
<script>window.onload = () => SwaggerUIBundle({ url: '/api/public/openapi.json', dom_id: '#swagger-ui' });</script>
</body></html>`);
  }));

  // ========================= WAVE-9: Regulator Pilot Perfection Suite (12 modules) =========================
  const extras9 = await import("./lib/pilot-readiness-extras-9");
  try { await extras9.seedExtras9(); } catch (e: any) { logger.child('wave9-seed').error('seed failed', { error: e instanceof Error ? e : new Error(String(e?.message || e)) }); }

  const wave9BaseUrl = () => `http://localhost:${process.env.PORT || 5000}`;

  // 1. OpenAPI contract tests
  app.post("/api/wave9/openapi-contract/run", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras9.runOpenapiContractTest({ ranBy: u, baseUrl: wave9BaseUrl() }));
  }));
  app.get("/api/wave9/openapi-contract/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listOpenapiContractRuns());
  }));

  // 2. RBAC matrix tests
  app.post("/api/wave9/rbac-matrix/run", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras9.runRbacMatrixTest({ ranBy: u, baseUrl: wave9BaseUrl(), cookies: { admin: "", risk_manager: "", auditor: "", anonymous: "" } }));
  }));
  app.get("/api/wave9/rbac-matrix/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listRbacMatrixRuns());
  }));

  // 3. Cross-pillar smoke runner
  app.post("/api/wave9/cross-pillar/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras9.runCrossPillarSmoke({ ranBy: u }));
  }));
  app.get("/api/wave9/cross-pillar/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listCrossPillarRuns());
  }));

  // 4. Negative-path security pack
  app.post("/api/wave9/negative-path/scan", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({ scanType: z.enum(["all", "csrf", "auth", "sqli", "xss", "header", "headers"]).default("all") }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras9.runNegativePathScan({ scanType: p.data.scanType, ranBy: u, baseUrl: wave9BaseUrl() }));
  }));
  app.get("/api/wave9/negative-path/scans", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listNegativePathScans());
  }));

  // 5. WCAG 2.1 audits
  app.post("/api/wave9/wcag/audit", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({ routePath: z.string().default("/"), wcagLevel: z.enum(["A", "AA", "AAA"]).default("AA") }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras9.runWcagAudit({ ...p.data, ranBy: u, baseUrl: wave9BaseUrl() }));
  }));
  app.get("/api/wave9/wcag/audits", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listWcagAudits());
  }));

  // 6. CycloneDX SBOM exports
  app.post("/api/wave9/sbom/export", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({ format: z.enum(["cyclonedx-1.5", "spdx-2.3"]).default("cyclonedx-1.5") }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras9.generateSbomExport({ format: p.data.format, exportedBy: u }));
  }));
  app.get("/api/wave9/sbom/exports", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listSbomExports());
  }));
  app.get("/api/wave9/sbom/payload/:exportRef", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const row = await extras9.getSbomExportPayload(String(req.params.exportRef));
    if (!row) return res.status(404).json({ error: "not-found" });
    res.set("Content-Type", "application/json");
    res.set("Content-Disposition", `attachment; filename="${row.exportRef}.${row.format}.json"`);
    res.send(row.payloadJson);
  }));

  // 7. DPIA generator
  app.post("/api/wave9/dpia/generate", requireRole("admin", "auditor"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({
      systemName: z.string().min(2),
      processor: z.string().min(2),
      controller: z.string().min(2),
      lawfulBasis: z.string().min(2),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras9.generateDpia({ ...p.data, generatedBy: u }));
  }));
  app.get("/api/wave9/dpia/list", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listDpiaDocuments());
  }));

  // 8. Tenant data portability bundle
  app.post("/api/wave9/tenant-export/generate", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({ tenantId: z.string().min(1), ttlHours: z.number().int().min(1).max(8760).default(168) }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras9.generateTenantExportBundle({ ...p.data, generatedBy: u }));
  }));
  app.get("/api/wave9/tenant-export/bundles", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listTenantExportBundles());
  }));

  // 9. Public Status Page
  app.get("/api/public/status", asyncHandler(async (_req, res) => {
    res.json(await extras9.getPublicStatus());
  }));
  app.get("/api/wave9/status/incidents", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listStatusIncidents());
  }));
  app.post("/api/wave9/status/incidents", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({
      title: z.string().min(2),
      severity: z.enum(["operational", "degraded", "partial-outage", "major-outage"]),
      status: z.enum(["investigating", "identified", "monitoring", "resolved"]),
      affectedComponents: z.array(z.string()).default([]),
      publicMessage: z.string().min(2),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras9.createStatusIncident({ ...p.data, createdBy: u }));
  }));
  app.patch("/api/wave9/status/incidents/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const z = (await import("zod")).z;
    const p = z.object({
      status: z.enum(["investigating", "identified", "monitoring", "resolved"]),
      publicMessage: z.string().optional(),
      resolved: z.boolean().optional(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    res.json(await extras9.updateStatusIncident({ id: String(req.params.id), ...p.data }));
  }));

  // 10. Regulator scenario simulator — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras9.listRegulatorScenarios / runRegulatorSimulation / listRegulatorSimulations were
  //   synthetic generators (deleted). REAL probes (openapi/rbac/negative-path/cross-pillar) untouched.

  // 11. Examiner read-only tokens
  app.post("/api/wave9/examiner-tokens/issue", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({
      examinerName: z.string().min(2),
      examinerEmail: z.string().email(),
      scopes: z.array(z.string()).min(1),
      ttlHours: z.number().int().min(1).max(8760).default(72),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    // issuedBy MUST be a real username. The KYC-evidence feature (Feature 4)
    // resolves the examiner's effective tenant from the issuing admin's primary
    // tenant (resolveExaminerTenant → getUserByUsername(issuedBy)). The login
    // flow writes req.session.userId (NOT req.session.user), so the prior
    // `req.session?.user?.username || "system"` ALWAYS resolved to "system" —
    // which getUserByUsername cannot find, making every read:kyc token 403
    // (examiner-tenant-unresolved). Derive the username from the authenticated
    // userId (guaranteed present by requireRole("admin")) and FAIL CLOSED rather
    // than silently writing an un-resolvable issuer.
    const issuer = req.session?.userId ? await storage.getUser(req.session.userId) : undefined;
    const issuedBy = issuer?.username ?? req.session?.user?.username;
    if (!issuedBy) return res.status(401).json({ error: "issuer-unresolved", message: "Authenticated issuer username could not be resolved." });
    // Commit-before-respond: the bare `db` proxy commits with the ambient request
    // transaction on res.finish — i.e. AFTER the response is flushed (see
    // tenant-middleware.ts). For a security token whose lifecycle a client acts on
    // immediately (issue→use), that deferred commit is a respond-before-commit
    // race. Wrap the write in a bounded withTenantDbPhase so the INSERT COMMITS
    // before res.json (same pattern the fincrime routes use). examiner_tokens is
    // global/non-RLS, so the tenant GUC set inside the phase is inert here.
    const issued = await withTenantDbPhase(req, () => extras9.issueExaminerToken({ ...p.data, issuedBy }));
    res.json(issued);
  }));
  app.get("/api/wave9/examiner-tokens/list", requireRole("admin"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listExaminerTokens());
  }));
  app.delete("/api/wave9/examiner-tokens/:id", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    // Commit-before-respond (see issue route): the revoke UPDATE must be durable
    // BEFORE we 200, or a zero-delay re-validate races the deferred res.finish
    // commit and a just-revoked token still authorizes (the M4-5 revocation race).
    // The bounded phase commits the revoke before the response is flushed.
    const revoked = await withTenantDbPhase(req, () => extras9.revokeExaminerToken(req.params.id, u));
    res.json(revoked);
  }));

  // Examiner-token middleware: validates `Authorization: Bearer <rawToken>` and enforces scope.
  const requireExaminerToken = (requiredScope: string) => async (req: any, res: any, next: any) => {
    try {
      const auth = req.headers.authorization || req.headers.Authorization;
      if (!auth || typeof auth !== "string" || !auth.toLowerCase().startsWith("bearer ")) {
        return res.status(401).json({ error: "examiner-bearer-token-required" });
      }
      const raw = auth.slice(7).trim();
      // requiredScope of "*" means: any valid (non-revoked, non-expired) token is accepted.
      const v = await extras9.validateExaminerToken(raw, requiredScope === "*" ? undefined : requiredScope);
      if (!v.valid) return res.status(v.reason === "unknown-token" || v.reason === "expired" || v.reason === "revoked" ? 401 : 403).json({ error: "invalid-examiner-token", reason: v.reason });
      req.examiner = { tokenId: v.tokenId, scopes: v.scopes, issuedBy: v.issuedBy };
      next();
    } catch (e: any) { res.status(500).json({ error: e.message }); }
  };

  // Examiner-only read-only endpoints (proves the token actually grants access)
  app.get("/api/examiner/readiness-score", requireExaminerToken("read:metrics"), asyncHandler(async (_req: any, res) => {
    res.json(await extras9.getLatestReadinessScore());
  }));
  app.get("/api/examiner/status", requireExaminerToken("read:status"), asyncHandler(async (_req: any, res) => {
    res.json(await extras9.getPublicStatus());
  }));
  app.get("/api/examiner/sbom/latest", requireExaminerToken("read:sbom"), asyncHandler(async (_req: any, res) => {
    const all = await extras9.listSbomExports(1);
    res.json(all[0] ?? null);
  }));
  app.get("/api/examiner/whoami", requireExaminerToken("*"), asyncHandler(async (req: any, res) => {
    res.json({ tokenId: req.examiner?.tokenId, scopes: req.examiner?.scopes });
  }));

  // ── KYC v1 Feature 4 — examiner KYC-evidence (read-only; scope read:kyc) ─────
  // Resolve the examiner's EFFECTIVE tenant from the issuing admin's primary
  // tenant (EXAMINER-KYC-UTR bypass register entry — tenant resolution only).
  // FAIL CLOSED: any failure to resolve a concrete tenant refuses the request;
  // it NEVER falls back to "default" and NEVER reads across tenants. The KYC data
  // reads then run inside runWithTenantContext(effectiveTenant) so the GUC is set
  // and RLS enforces — NOT auditDb / NOT withBypassRls for the KYC DATA.
  const resolveExaminerTenant = async (req: any): Promise<string | null> => {
    const issuedBy = req.examiner?.issuedBy;
    if (!issuedBy || typeof issuedBy !== "string") return null;
    const issuer = await storage.getUserByUsername(issuedBy);
    if (!issuer) return null;
    const [primary] = await withBypassRls((bypassDb) =>
      bypassDb
        .select({ tenantId: userTenantRoles.tenantId })
        .from(userTenantRoles)
        .where(
          and(
            eq(userTenantRoles.userId, issuer.id),
            eq(userTenantRoles.isPrimary, true),
            eq(userTenantRoles.isActive, true),
          ),
        )
        .limit(1),
    );
    return primary?.tenantId ?? null;
  };

  // List customers as non-PII references. Synthetic test rows are filtered OUT of
  // the examiner view (they remain visible in internal/admin views).
  app.get("/api/examiner/kyc/customers", requireExaminerToken("read:kyc"), asyncHandler(async (req: any, res) => {
    const tenantId = await resolveExaminerTenant(req);
    if (!tenantId) return res.status(403).json({ error: "examiner-tenant-unresolved" });
    const rows = await runWithTenantContext(tenantId, () =>
      storage.listKycCustomerRefsForExaminer(tenantId, { limit: 500 }),
    );
    const visible = rows.filter((r) => !isSyntheticKycCustomer(r.id));
    res.json({ tenantId, count: visible.length, customers: visible.map(toExaminerCustomerRef) });
  }));

  // Per-customer decision history (synthetic decisions filtered OUT).
  app.get("/api/examiner/kyc/customers/:id/decisions", requireExaminerToken("read:kyc"), asyncHandler(async (req: any, res) => {
    const tenantId = await resolveExaminerTenant(req);
    if (!tenantId) return res.status(403).json({ error: "examiner-tenant-unresolved" });
    const customerId = String(req.params.id);
    if (isSyntheticKycCustomer(customerId)) return res.status(404).json({ error: "not-found" });
    const result = await runWithTenantContext(tenantId, async () => {
      const customer = await storage.getKycCustomerRefForExaminer(customerId, tenantId);
      if (!customer) return null;
      const decisions = await storage.listKycDecisionOutcomes(tenantId, { customerId, limit: 200 });
      return { customer, decisions };
    });
    if (!result) return res.status(404).json({ error: "not-found" });
    const decisions = result.decisions.filter((d) => !isSyntheticKycDecision(d.id));
    res.json({
      tenantId,
      customer: toExaminerCustomerRef(result.customer),
      count: decisions.length,
      decisions: decisions.map(toExaminerDecisionDTO),
    });
  }));

  // Single-decision detail + per-decision tamper-evidence (E2). The decision row
  // is read under tenant context (RLS); the integrity check then triangulates it
  // against the immutable audit chain (read via the independent auditDb path).
  app.get("/api/examiner/kyc/decisions/:id", requireExaminerToken("read:kyc"), asyncHandler(async (req: any, res) => {
    const tenantId = await resolveExaminerTenant(req);
    if (!tenantId) return res.status(403).json({ error: "examiner-tenant-unresolved" });
    const decisionId = String(req.params.id);
    if (isSyntheticKycDecision(decisionId)) return res.status(404).json({ error: "not-found" });
    const bundle = await runWithTenantContext(tenantId, async () => {
      const decision = await storage.getKycDecisionOutcomeById(decisionId, tenantId);
      if (!decision) return null;
      const approval = await storage.getKycDecisionApprovalByDecisionId(decisionId, tenantId);
      return { decision, approval };
    });
    if (!bundle) return res.status(404).json({ error: "not-found" });
    const integrity = await verifyDecisionIntegrity(bundle.decision);
    res.json({
      tenantId,
      decision: toExaminerDecisionDTO(bundle.decision),
      approval: bundle.approval ? toExaminerApprovalDTO(bundle.approval) : null,
      integrity,
    });
  }));

  // ── AEGIS SOAR M4 — regulator-facing SOAR surface (read-only; scope read:fincrime) ──
  // Read-only regulator view over the fincrime (SOAR) case spine: non-PII case
  // references, STR filing STATUS (roles only — no narrative / actor ids), and
  // per-case tamper-evidence over the immutable audit chain. Mirrors the KYC
  // Feature-4 examiner pattern EXACTLY: requireExaminerToken + resolveExaminerTenant
  // (FAIL CLOSED, never "default", never cross-tenant) + runWithTenantContext (GUC
  // set, RLS enforced) for the case-spine reads; the integrity check then reads the
  // system-level audit chain via the independent auditDb path (after the tenant
  // block, like the KYC decision-integrity call). NO non-GET route exists on this
  // surface — the M3 disposition/STR write edges and the locked finalizer are
  // untouched.
  app.get("/api/examiner/fincrime/cases", requireExaminerToken("read:fincrime"), asyncHandler(async (req: any, res) => {
    const tenantId = await resolveExaminerTenant(req);
    if (!tenantId) return res.status(403).json({ error: "examiner-tenant-unresolved" });
    const rows = await runWithTenantContext(tenantId, () =>
      storage.listFincrimeCasesForRegulator(tenantId, { limit: 500 }),
    );
    res.json({ tenantId, count: rows.length, cases: rows.map(toRegulatorCaseRefDTO) });
  }));

  // Single-case detail + per-case tamper-evidence. The case-spine rows are read
  // under tenant context (RLS); the integrity check then triangulates them against
  // the immutable audit chain (read via the independent auditDb path).
  app.get("/api/examiner/fincrime/cases/:id", requireExaminerToken("read:fincrime"), asyncHandler(async (req: any, res) => {
    const tenantId = await resolveExaminerTenant(req);
    if (!tenantId) return res.status(403).json({ error: "examiner-tenant-unresolved" });
    const caseId = String(req.params.id);
    const bundle = await runWithTenantContext(tenantId, async () => {
      const caseRow = await storage.getFincrimeCaseForRegulator(caseId, tenantId);
      if (!caseRow) return null;
      const integrityInputs = await storage.getFincrimeCaseIntegrityInputs(caseId, tenantId);
      if (!integrityInputs) return null;
      return { caseRow, integrityInputs };
    });
    if (!bundle) return res.status(404).json({ error: "not-found" });
    const integrity = await verifyFincrimeCaseIntegrity(bundle.integrityInputs);
    res.json({
      tenantId,
      case: toRegulatorCaseRefDTO(bundle.caseRow),
      str: toRegulatorStrStatusDTO(bundle.integrityInputs),
      integrity,
    });
  }));

  // 12. Continuous Pilot-Readiness Score
  app.post("/api/wave9/readiness-score/compute", requireRole("admin", "risk_manager"), asyncHandler(async (_req, res) => {
    res.json(await extras9.computeReadinessScore());
  }));
  app.get("/api/wave9/readiness-score/latest", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.getLatestReadinessScore());
  }));
  app.get("/api/wave9/readiness-score/history", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras9.listReadinessScoreHistory());
  }));

  // ============================================================
  // WAVE-10 — Sandbox Perfection Suite (14 modules)
  // ============================================================
  const extras10 = await import("./lib/pilot-readiness-extras-10");
  await extras10.autoSeedWave10();
  const wave10BaseUrl = () => `http://localhost:${process.env.PORT || 5000}`;

  // 1. OWASP API Top-10 deep scan
  app.post("/api/wave10/owasp-api/scan", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras10.runOwaspApiScan({ ranBy: u, baseUrl: wave10BaseUrl() }));
  }));
  app.get("/api/wave10/owasp-api/scans", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listOwaspApiScans());
  }));

  // 2. Endpoint fuzz harness
  app.post("/api/wave10/fuzz/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const cookies = req.headers.cookie || "";
    res.json(await extras10.runFuzzTest({ ranBy: u, baseUrl: wave10BaseUrl(), cookies }));
  }));
  app.get("/api/wave10/fuzz/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listFuzzTestRuns());
  }));

  // 3. Key rotation drill
  app.post("/api/wave10/key-rotation/drill", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = z.object({ keyType: z.enum(["hmac", "aes", "session"]).default("hmac") }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras10.runKeyRotationDrill({ ranBy: u, keyType: p.data.keyType }));
  }));
  app.get("/api/wave10/key-rotation/drills", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listKeyRotationDrills());
  }));

  // 4. Backup-restore integrity drill
  app.post("/api/wave10/backup-restore/drill", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras10.runBackupRestoreDrill({ ranBy: u }));
  }));
  app.get("/api/wave10/backup-restore/drills", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listBackupRestoreDrills());
  }));

  // 5. Model card / datasheet
  app.post("/api/wave10/model-cards", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      modelKey: z.string().min(2), modelName: z.string().min(2), modelVersion: z.string().min(1),
      modelType: z.string().min(1), vendor: z.string().min(1),
      purpose: z.string().min(10), trainingData: z.string().min(5),
      performanceMetricsJson: z.any().optional(), limitationsJson: z.any().optional(),
      ethicsConsiderationsJson: z.any().optional(), driftSignals: z.string().optional(),
      ownerEmail: z.string().email(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    res.json(await extras10.upsertModelCard(p.data));
  }));
  app.get("/api/wave10/model-cards", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listModelCards());
  }));
  app.get("/api/wave10/model-cards/:modelKey", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const card = await extras10.getModelCard(String(req.params.modelKey));
    if (!card) return res.status(404).json({ error: "not-found" });
    res.json(card);
  }));

  // 6. Bias / fairness audit
  app.post("/api/wave10/bias-audit/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      modelKey: z.string().min(2), protectedAttribute: z.string().min(2),
      sampleSize: z.number().int().min(50).max(100000).optional(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras10.runBiasAudit({ ...p.data, ranBy: u }));
  }));
  app.get("/api/wave10/bias-audit/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listBiasAudits());
  }));

  // 7. Model rollback drill
  app.post("/api/wave10/model-rollback/drill", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      modelKey: z.string().min(2), fromVersion: z.string().min(1), toVersion: z.string().min(1),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras10.runModelRollbackDrill({ ...p.data, ranBy: u }));
  }));
  app.get("/api/wave10/model-rollback/drills", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listModelRollbackDrills());
  }));

  // 8. Chaos engineering
  app.post("/api/wave10/chaos/run", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      scenario: z.enum(["network-latency-2s", "process-kill", "cpu-saturation", "websocket-partition", "database-stall-5s", "memory-pressure"]),
      durationSec: z.number().int().min(5).max(300).optional(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras10.runChaosRun({ ...p.data, ranBy: u }));
  }));
  app.get("/api/wave10/chaos/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listChaosRuns());
  }));

  // 9. Vendor / TPRM register
  app.post("/api/wave10/vendors", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      vendorKey: z.string().min(2), vendorName: z.string().min(2), category: z.string().min(2),
      contactEmail: z.string().email(),
      riskScore: z.number().int().min(0).max(100).optional(),
      riskTier: z.enum(["LOW", "MEDIUM", "HIGH", "CRITICAL"]).optional(),
      contractEndDate: z.coerce.date().optional(),
      lastReviewedAt: z.coerce.date().optional(),
      nextReviewDueAt: z.coerce.date().optional(),
      certificationsJson: z.array(z.string()).optional(),
      notes: z.string().optional(),
      active: z.number().int().optional(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    res.json(await extras10.upsertVendor(p.data));
  }));
  app.get("/api/wave10/vendors", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listVendors());
  }));
  app.post("/api/wave10/vendors/:vendorKey/deactivate", requireRole("admin"), asyncHandler(async (req, res) => {
    const r = await extras10.deactivateVendor(String(req.params.vendorKey));
    if (!r) return res.status(404).json({ error: "not-found" });
    res.json(r);
  }));

  // 10. KRI dashboard
  app.post("/api/wave10/kri/refresh", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    res.json(await extras10.refreshKriMetrics({ ranBy: u }));
  }));
  app.get("/api/wave10/kri/latest", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listLatestKris());
  }));
  app.get("/api/wave10/kri/history/:metricKey", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await extras10.getKriHistory(String(req.params.metricKey)));
  }));

  // 11. Customer consent ledger v2
  app.post("/api/wave10/consent/append", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      customerRef: z.string().min(2), consentType: z.string().min(2),
      action: z.enum(["GRANT", "REVOKE"]),
      scope: z.string().min(2), lawfulBasis: z.string().min(2),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras10.appendConsentEntry({ ...p.data, capturedBy: u }));
  }));
  app.get("/api/wave10/consent/customer/:customerRef", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await extras10.listCustomerConsent(String(req.params.customerRef)));
  }));
  app.get("/api/wave10/consent/all", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listAllConsentEntries());
  }));
  app.get("/api/wave10/consent/verify-chain", requireRole("admin", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.verifyConsentChain());
  }));

  // 12. PDF certificate exporter
  app.post("/api/wave10/pdf-cert/generate", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      certType: z.string().min(2),
      subject: z.string().min(2),
      issuedTo: z.string().min(2),
      bodyLines: z.array(z.string()).min(1).max(50),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    res.json(await extras10.generatePdfCertificate({ ...p.data, generatedBy: u }));
  }));
  app.get("/api/wave10/pdf-cert/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listPdfCertificates());
  }));
  app.get("/api/wave10/pdf-cert/download/:certRef", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const cert = await extras10.getPdfCertificate(String(req.params.certRef));
    if (!cert) return res.status(404).json({ error: "not-found" });
    const buf = Buffer.from(cert.pdfBase64, "base64");
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", `attachment; filename="${cert.certRef}.pdf"`);
    res.send(buf);
  }));

  // 13. Custom regulator reports
  // Write/run endpoints are admin/risk_manager only — auditor stays read-only (list).
  // Data-source enum mirrors lib's ALLOWED_DATA_SOURCES exactly (no kyt-transactions: table doesn't exist).
  app.post("/api/wave10/custom-reports", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      reportKey: z.string().min(2),
      reportName: z.string().min(2),
      description: z.string().optional(),
      dataSource: z.enum(["audit-logs", "threat-events", "users"]),
      fieldsJson: z.array(z.string()).min(1),
      filtersJson: z.any().optional(),
      scheduleCron: z.string().nullable().optional(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    try {
      res.json(await extras10.saveCustomReport({ ...p.data, createdBy: u }));
    } catch (e: any) { res.status(400).json({ error: e.message }); }
  }));
  app.get("/api/wave10/custom-reports", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listCustomReports());
  }));
  app.post("/api/wave10/custom-reports/:reportKey/run", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    try {
      res.json(await extras10.runCustomReport(String(req.params.reportKey)));
    } catch (e: any) { res.status(400).json({ error: e.message }); }
  }));

  // 14. Independent attestation portal
  app.post("/api/wave10/attestation/upload", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const p = z.object({
      attestationType: z.enum(["SOC2", "ISO27001", "PCI-DSS", "PEN-TEST", "OTHER"]),
      issuerName: z.string().min(2),
      scope: z.string().min(2),
      issuedAt: z.coerce.date(),
      expiresAt: z.coerce.date(),
      fileBase64: z.string().min(64),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const u = req.session?.user?.username || "system";
    try {
      res.json(await extras10.uploadAttestation({ ...p.data, uploadedBy: u }));
    } catch (e: any) { res.status(400).json({ error: e.message }); }
  }));
  app.get("/api/wave10/attestation/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras10.listAttestations());
  }));
  app.get("/api/wave10/attestation/download/:uploadRef", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const att = await extras10.getAttestation(String(req.params.uploadRef));
    if (!att) return res.status(404).json({ error: "not-found" });
    const buf = Buffer.from(att.fileBase64, "base64");
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", `attachment; filename="${att.uploadRef}-${att.attestationType}.pdf"`);
    res.send(buf);
  }));

  // ============================================================
  // WAVE-11 — Final Pilot-Readiness Suite (9 modules)
  // ============================================================
  const extras11 = await import("./lib/pilot-readiness-extras-11");
  const audit11 = async (req: any, action: string, resource: string, details?: any) => {
    try {
      await storage.createAuditLog({
        userId: req.session?.user?.id || null,
        action,
        resource,
        details: details ? JSON.stringify(details).slice(0, 4000) : null,
        ipAddress: getClientIp(req),
      });
    } catch (e) { /* never block executor on audit failure */ }
  };

  // 1. Nightly Canary Suite + 7-day rolling baseline
  app.post("/api/wave11/canary/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const z = (await import("zod")).z;
    const p = z.object({ trigger: z.enum(["scheduled", "manual"]).default("manual") }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await extras11.runCanary({ ranBy: u, trigger: p.data.trigger });
    await audit11(req, "WAVE11_CANARY_RUN", `canary_run:${r.runRef}`, { score: r.scoreOf100, grade: r.grade, trigger: p.data.trigger });
    res.json(r);
  }));
  app.get("/api/wave11/canary/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listCanaryRuns());
  }));
  app.get("/api/wave11/canary/summary", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.getCanarySummary());
  }));

  // 2. Forensic Evidence Bundle Export
  app.post("/api/wave11/forensic/bundle", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const z = (await import("zod")).z;
    const p = z.object({ threatEventId: z.string().min(1) }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await extras11.generateForensicBundle({ threatEventId: p.data.threatEventId, generatedBy: u });
    await audit11(req, "WAVE11_FORENSIC_BUNDLE_GENERATE", `forensic_bundle:${r.bundleRef}`, { threatEventId: p.data.threatEventId, sizeBytes: r.bundleSizeBytes, manifestHash: r.manifestHash });
    res.json(r);
  }));
  app.get("/api/wave11/forensic/bundles", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listForensicBundles());
  }));
  app.get("/api/wave11/forensic/download/:bundleRef", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const r = await extras11.getForensicBundleZip(req.params.bundleRef);
    if (!r) return res.status(404).json({ error: "not-found" });
    await audit11(req, "WAVE11_FORENSIC_BUNDLE_DOWNLOAD", `forensic_bundle:${req.params.bundleRef}`, { filename: r.filename, sizeBytes: r.zip.length });
    res.setHeader("Content-Type", "application/zip");
    res.setHeader("Content-Disposition", `attachment; filename="${r.filename}"`);
    res.send(r.zip);
  }));

  // 3. Closed-loop Production SLA Monitor
  app.post("/api/wave11/sla/seed", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const r = await extras11.seedSlaThresholds(u);
    await audit11(req, "WAVE11_SLA_SEED", "sla_thresholds", { inserted: r.inserted, total: r.total });
    res.json(r);
  }));
  app.get("/api/wave11/sla/thresholds", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listSlaThresholds());
  }));
  app.patch("/api/wave11/sla/thresholds/:metricKey", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const z = (await import("zod")).z;
    const p = z.object({
      thresholdMs: z.number().int().min(1).optional(),
      windowSeconds: z.number().int().min(10).max(86400).optional(),
      enabled: z.boolean().optional(),
      notifyOnBreach: z.boolean().optional(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await extras11.updateSlaThreshold({ metricKey: req.params.metricKey, ...p.data, updatedBy: u });
    if (!r) return res.status(404).json({ error: "not-found" });
    await audit11(req, "WAVE11_SLA_THRESHOLD_UPDATE", `sla_threshold:${req.params.metricKey}`, p.data);
    res.json(r);
  }));
  app.post("/api/wave11/sla/evaluate", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({ dryRun: z.boolean().default(false) }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await extras11.evaluateSla({ dryRun: p.data.dryRun });
    await audit11(req, "WAVE11_SLA_EVALUATE", "sla_monitor", { dryRun: p.data.dryRun, thresholds: r.thresholds, breaches: r.observations?.filter((o: any) => o.breach).length || 0 });
    res.json(r);
  }));
  app.get("/api/wave11/sla/breaches", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listSlaBreaches());
  }));
  app.post("/api/wave11/sla/breaches/:breachRef/resolve", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const r = await extras11.resolveSlaBreach(req.params.breachRef, u);
    if (!r) return res.status(404).json({ error: "not-found" });
    await audit11(req, "WAVE11_SLA_BREACH_RESOLVE", `sla_breach:${req.params.breachRef}`, { metricKey: r.metricKey });
    res.json(r);
  }));
  app.get("/api/wave11/sla/summary", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.getSlaSummary());
  }));

  // 4. Adversarial AI Prompt-Injection Harness
  app.post("/api/wave11/prompt-injection/seed", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const r = await extras11.seedPromptCorpus();
    await audit11(req, "WAVE11_PROMPT_INJECTION_SEED", "prompt_injection_corpus", r);
    res.json(r);
  }));
  app.get("/api/wave11/prompt-injection/corpus", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listPromptCorpus());
  }));
  app.post("/api/wave11/prompt-injection/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const r = await extras11.runPromptInjectionSuite({ ranBy: u });
    await audit11(req, "WAVE11_PROMPT_INJECTION_RUN", `prompt_injection_run:${r.runRef}`, { score: r.scoreOf100, grade: r.grade, defenseRatePct: r.defenseRatePct, bypassed: r.bypassedCount });
    res.json(r);
  }));
  app.get("/api/wave11/prompt-injection/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listPromptInjectionRuns());
  }));

  // 5. Data-Residency Monthly Attestation — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras11.generateResidencyAttestation / listResidencyAttestations were synthetic
  //   signed regulator-facing attestations (deleted). Table residency_attestations KEPT.

  // 6. DR Drill with Auto-Measured RPO/RTO — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras11.runDrDrill / listDrDrills were synthetic RTO/RPO generators (deleted).
  //   NOTE: the SEPARATE real DR module /api/dr-drill/* (extras8) is unaffected.

  // 7. PDPO 72-hour Breach-Notification Drill — REMOVED (Tier-1 cleanup 2026-06-30):
  //   extras11.runBreachNotificationDrill / listBreachNotificationDrills were synthetic (deleted).

  // 8. Production Traffic Shadow Runner
  app.post("/api/wave11/shadow/seed", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const r = await extras11.seedShadowCapturesIfEmpty();
    await audit11(req, "WAVE11_SHADOW_SEED", "traffic_shadow_captures", r);
    res.json(r);
  }));
  app.post("/api/wave11/shadow/capture", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const z = (await import("zod")).z;
    const p = z.object({
      method: z.string().min(1).max(8),
      pathTemplate: z.string().min(1).max(256),
      body: z.any().optional(),
      responseStatus: z.number().int().min(100).max(599),
      responseDurationMs: z.number().int().min(0).default(0),
      responseBody: z.any().optional(),
    }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await extras11.captureShadowSample(p.data);
    await audit11(req, "WAVE11_SHADOW_CAPTURE", `traffic_shadow_capture:${r.captureRef}`, { method: p.data.method, path: p.data.pathTemplate, status: p.data.responseStatus });
    res.json(r);
  }));
  app.get("/api/wave11/shadow/captures", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listShadowCaptures());
  }));
  app.post("/api/wave11/shadow/replay", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const z = (await import("zod")).z;
    const p = z.object({ sampleSize: z.number().int().min(1).max(200).optional() }).safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await extras11.runShadowReplay({ ranBy: u, sampleSize: p.data.sampleSize });
    await audit11(req, "WAVE11_SHADOW_REPLAY", `traffic_shadow_replay:${r.replayRef}`, { capturesReplayed: r.capturesReplayed, matchRatePct: r.matchRatePct, score: r.scoreOf100, grade: r.grade });
    res.json(r);
  }));
  app.get("/api/wave11/shadow/replays", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listShadowReplays());
  }));

  // 9. Cryptographic Key Inventory Dashboard
  app.post("/api/wave11/keys/seed", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const r = await extras11.seedKeyInventory(u);
    await audit11(req, "WAVE11_KEYS_SEED", "key_inventory", r);
    res.json(r);
  }));
  app.get("/api/wave11/keys/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.listKeyInventory());
  }));
  app.post("/api/wave11/keys/:keyId/rotate", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const r = await extras11.rotateKey({ keyId: req.params.keyId, rotatedBy: u });
    if (!r) return res.status(404).json({ error: "not-found" });
    // Audit the truth: this updates the inventory schedule only, no cryptographic rotation performed.
    await audit11(req, "WAVE11_KEY_ROTATE", `key_inventory:${req.params.keyId}`, { algorithm: r.algorithm, status: r.status, lastRotatedAt: r.lastRotatedAt, cryptographicRotation: false });
    res.json(r);
  }));
  app.get("/api/wave11/keys/summary", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.getKeyInventorySummary());
  }));

  // Wave-11 composite score
  app.get("/api/wave11/score", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await extras11.getWave11Score());
  }));

  // ============================================================
  // WAVE-12 — Regulator-Facing Finisher (master score, smoke runner, demo seeder)
  // ============================================================
  const wave12 = await import("./lib/wave12-regulator-finisher");
  const audit12 = async (req: any, action: string, resource: string, details?: any) => {
    try {
      await storage.createAuditLog({
        userId: req.session?.user?.id || null,
        action, resource,
        details: details ? JSON.stringify(details).slice(0, 4000) : null,
        ipAddress: getClientIp(req),
      });
    } catch (e) { /* never block on audit failure */ }
  };

  app.get("/api/pilot-readiness/master-score", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await wave12.getMasterScore());
  }));
  app.post("/api/pilot-readiness/master-score/persist", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const r = await wave12.persistMasterScore({ generatedBy: u });
    await audit12(req, "WAVE12_MASTER_SCORE_PERSIST", `pilot_master_score:${r.scoreRef}`, { score: r.compositeScore, grade: r.grade });
    res.json(r);
  }));
  app.get("/api/pilot-readiness/master-score/history", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await wave12.listMasterScores(50));
  }));
  // PDF generation persists a master_score row, so require admin/risk_manager
  // (auditors can read history via /master-score/history). Architect MED #6.
  app.get("/api/pilot-readiness/master-score.pdf", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const issuedTo = typeof req.query.issuedTo === "string" ? req.query.issuedTo : undefined;
    const pdf = await wave12.exportMasterScorePdf({ generatedBy: u, issuedTo });
    await audit12(req, "WAVE12_MASTER_SCORE_PDF_DOWNLOAD", "pilot_master_score:pdf", { issuedTo, sizeBytes: pdf.length });
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-master-pilot-readiness-${Date.now()}.pdf"`);
    res.send(pdf);
  }));

  app.post("/api/pilot-readiness/full-smoke", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const r = await wave12.runFullSmoke({ triggeredBy: u });
    await audit12(req, "WAVE12_FULL_SMOKE_RUN", `pilot_smoke_run:${r.runRef}`, { score: r.compositeScore, grade: r.grade, goNoGo: r.goNoGo, passed: r.passedCount, failed: r.failedCount });
    res.json(r);
  }));
  app.get("/api/pilot-readiness/full-smoke/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await wave12.listSmokeRuns(50));
  }));
  app.get("/api/pilot-readiness/full-smoke/latest", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await wave12.getLatestSmokeRun());
  }));

  // NOTE: POST /api/pilot-readiness/seed-demo removed (2026-07-01, demo-seeder-seam cleanup) — it was
  // a one-click path to fabricating up to 500 threat_events (the table Pass #2 scrubbed of 1550 fakes)
  // on a regulator-facing surface. The real threat-detection feed is untouched; the read-only status
  // (GET .../seed-demo/status → getDemoSeedStatus, a real threat count) is retained below.
  app.get("/api/pilot-readiness/seed-demo/status", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await wave12.getDemoSeedStatus());
  }));

  app.get("/api/pilot-readiness/regulator-day", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await wave12.getRegulatorDaySummary());
  }));

  // Public: lets a regulator independently re-verify any signed payload
  // (e.g. recompute the HMAC of a master_score row or a manifest from a
  // briefing pack). Read-only — no auth, no CSRF, no rate-limit blast risk.
  app.post("/api/pilot-readiness/verify-signature", asyncHandler(async (req, res) => {
    const z = (await import("zod")).z;
    const p = z.object({
      payload: z.string().max(64 * 1024).optional(),
      payloadHash: z.string().regex(/^[0-9a-fA-F]{64}$/).optional(),
      signatureHex: z.string().regex(/^[0-9a-fA-F]{64}$/),
    }).refine(d => d.payload || d.payloadHash, { message: "payload or payloadHash required" })
      .safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    res.json(wave12.verifySignature(p.data));
  }));

  app.get("/api/pilot-readiness/preflight", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await wave12.runPreflightCheck());
  }));

  app.get("/api/pilot-readiness/master-score/timeline", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const days = Math.max(1, Math.min(365, parseInt(req.query.days, 10) || 30));
    res.json(await wave12.getMasterScoreTimeline(days));
  }));

  // Briefing pack writes a master_score row, so admin/risk_manager only.
  app.get("/api/pilot-readiness/briefing-pack", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const u = req.session?.user?.username || "system";
    const issuedTo = typeof req.query.issuedTo === "string" ? req.query.issuedTo : undefined;
    const { zip, manifest } = await wave12.generateBriefingPack({ generatedBy: u, issuedTo });
    await audit12(req, "WAVE12_BRIEFING_PACK_DOWNLOAD", `pilot_briefing_pack:${manifest.packRef}`, { issuedTo, files: manifest.contents.length, sizeBytes: zip.length });
    res.setHeader("Content-Type", "application/zip");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-briefing-pack-${manifest.packRef}.zip"`);
    res.setHeader("X-Pack-Ref", manifest.packRef);
    res.setHeader("X-Manifest-Hash", manifest.manifestHash);
    res.setHeader("X-Manifest-Signature", manifest.manifestSignatureHex);
    res.send(zip);
  }));

  // AS/PLATFORM/2026/006 Layer 4 — one-click Audit-Readiness Pack. Bundles, for the SESSION tenant
  // (never from body), the latest persisted compliance run (every control + cited evidenceJson), the
  // signed attestation (runId + sourceDigest + signedHash), and the self-verifying audit-chain proof —
  // as a signed ZIP (PDF + JSON + audit-chain proof + HMAC manifest). The blended pilot-readiness
  // "master score" is DELIBERATELY EXCLUDED (real compliance evidence only). A regulator re-verifies the
  // manifest WITHOUT trusting the UI via the public POST /api/pilot-readiness/verify-signature.
  app.get("/api/compliance/audit-pack", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) {
      return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    }
    const generatedBy = (req.session as any)?.username || String(req.session?.userId ?? "system");
    const issuedTo = typeof req.query.issuedTo === "string" ? req.query.issuedTo : undefined;
    const { buildAuditPack } = await import("./lib/audit-pack");
    const { zip, manifest } = await buildAuditPack({ tenantId, generatedBy, issuedTo });
    await storage.createAuditLog({
      action: "COMPLIANCE_AUDIT_PACK_DOWNLOAD",
      resource: "Compliance Audit Pack",
      userId: req.session?.userId ?? null,
      details: `packRef=${manifest.packRef} runId=${manifest.runId ?? "none"} files=${manifest.contents.length} sizeBytes=${zip.length}`,
      ipAddress: getClientIp(req),
    });
    res.setHeader("Content-Type", "application/zip");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-audit-pack-${manifest.packRef}.zip"`);
    res.setHeader("X-Pack-Ref", manifest.packRef);
    res.setHeader("X-Manifest-Hash", manifest.manifestHash);
    res.setHeader("X-Manifest-Signature", manifest.manifestSignatureHex);
    res.send(zip);
  }));

  // Examiner-token read-only view of the regulator-day summary.
  // The token holder gets the same JSON as an authenticated auditor would.
  app.get("/api/examiner/regulator-day", requireExaminerToken("read:metrics"), asyncHandler(async (_req: any, res) => {
    res.json(await wave12.getRegulatorDaySummary());
  }));

  app.get("/api/compliance/dashboard", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await complianceDashboard.getDashboardStats((req as any).tenantId as string));
  }));

  app.get("/api/compliance/frameworks", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await complianceDashboard.getAllFrameworkStatuses((req as any).tenantId as string));
  }));

  app.get("/api/compliance/frameworks/:id", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const status = await complianceDashboard.getFrameworkStatus((req as any).tenantId as string, req.params.id as any);
    if (!status) {
      return res.status(404).json({ error: "Framework not found" });
    }
    res.json(status);
  }));

  app.get("/api/compliance/controls", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const { frameworkId, status, priority, category } = req.query;
    res.json(await complianceDashboard.getControls((req as any).tenantId as string, {
      frameworkId: frameworkId as any,
      status: status as any,
      priority: priority as any,
      category: category as string
    }));
  }));

  // AS/PLATFORM/2026/006 T004 — manual control-status override is no longer accepted.
  // Control status is DERIVED from real compliance-check runs; a hand-set status was an
  // asserted-without-checking fabrication vector. Trigger a real run instead.
  app.patch("/api/compliance/controls/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    return res.status(400).json({
      error: "Control status is derived from real compliance-check runs and cannot be set manually. Trigger POST /api/compliance/checks/run to (re)compute it.",
    });
  }));

  app.get("/api/compliance/gaps", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const { frameworkId, status, severity } = req.query;
    res.json(complianceDashboard.getGaps({
      frameworkId: frameworkId as any,
      status: status as any,
      severity: severity as any
    }));
  }));

  app.post("/api/compliance/gaps", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const gap = complianceDashboard.createGap(req.body);
    res.json(gap);
  }));

  app.patch("/api/compliance/gaps/:id/status", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { status } = req.body;
    const gap = complianceDashboard.updateGapStatus(String(req.params.id), status);
    if (!gap) {
      return res.status(404).json({ error: "Gap not found" });
    }
    res.json(gap);
  }));

  app.get("/api/compliance/events", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const { frameworkId, type, limit } = req.query;
    res.json(complianceDashboard.getAuditEvents({
      frameworkId: frameworkId as any,
      type: type as any,
      limit: limit ? parseInt(limit as string) : undefined
    }));
  }));

  app.post("/api/compliance/events", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const event = complianceDashboard.recordAuditEvent(req.body);
    res.json(event);
  }));

  // ========================================
  // PRIVILEGED ACCESS MANAGEMENT ENDPOINTS
  // ========================================

  app.get("/api/pam/accounts", requireRole("admin"), asyncHandler(async (req, res) => {
    const { type, privilegeLevel, status, needsRotation } = req.query;
    res.json(await privilegedAccess.getAccounts({
      type: type as any,
      privilegeLevel: privilegeLevel as any,
      status: status as any,
      needsRotation: needsRotation === "true"
    }, { tenantId: req.tenantId, res }));
  }));

  app.get("/api/pam/accounts/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const account = await privilegedAccess.getAccount(String(req.params.id), { tenantId: req.tenantId, res });
    if (!account) {
      return res.status(404).json({ error: "Account not found" });
    }
    res.json(account);
  }));

  app.post("/api/pam/accounts/:id/rotate", requireRole("admin"), asyncHandler(async (req, res) => {
    const result = await privilegedAccess.rotateCredentials(String(req.params.id), { tenantId: req.tenantId, res });
    if ("error" in result) {
      return res.status(404).json(result);
    }
    res.json(result);
  }));

  app.get("/api/pam/requests", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { status, accountId, requesterId, limit } = req.query;
    res.json(await privilegedAccess.getRequests({
      status: status as any,
      accountId: accountId as string,
      requesterId: requesterId as string,
      limit: limit ? parseInt(limit as string) : undefined
    }));
  }));

  app.post("/api/pam/requests", requireAuth, asyncHandler(async (req, res) => {
    // VF-A1 identity-binding: the requester identity is server-derived from the
    // authenticated session, never caller-supplied. Body is reduced to an
    // explicit allowlist of the only legitimately caller-supplied fields so no
    // requesterId/requesterName can leak through and forge another user's identity.
    const actor = await storage.getUser(req.session.userId!);
    const result = await privilegedAccess.createAccessRequest({
      accountId: req.body.accountId,
      justification: req.body.justification,
      requestedDuration: req.body.requestedDuration,
      requesterId: req.session.userId!,
      requesterName: actor?.fullName || actor?.username || "Unknown",
    }, { tenantId: req.tenantId, res });
    if ("error" in result) {
      return res.status(400).json(result);
    }
    res.json(result);
  }));

  app.post("/api/pam/requests/:id/review", requireRole("admin"), asyncHandler(async (req, res) => {
    const { decision, notes } = req.body;
    const result = await privilegedAccess.reviewRequest(
      String(req.params.id),
      req.session.userId!,
      decision,
      notes,
      { tenantId: req.tenantId, res },
    );
    if ("error" in result) {
      return res.status(400).json(result);
    }
    res.json(result);
  }));

  app.post("/api/pam/requests/:id/start-session", requireRole("admin"), asyncHandler(async (req, res) => {
    const result = await privilegedAccess.startSession(String(req.params.id), { tenantId: req.tenantId, res });
    if ("error" in result) {
      return res.status(400).json(result);
    }
    res.json(result);
  }));

  app.get("/api/pam/sessions", requireRole("admin"), asyncHandler(async (req, res) => {
    const { status, accountId, userId, limit } = req.query;
    res.json(await privilegedAccess.getSessions({
      status: status as any,
      accountId: accountId as string,
      userId: userId as string,
      limit: limit ? parseInt(limit as string) : undefined
    }));
  }));

  app.get("/api/pam/sessions/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const session = await privilegedAccess.getSession(String(req.params.id));
    if (!session) {
      return res.status(404).json({ error: "Session not found" });
    }
    res.json(session);
  }));

  app.post("/api/pam/sessions/:id/command", requireRole("admin"), asyncHandler(async (req, res) => {
    const { command } = req.body;
    const result = await privilegedAccess.recordCommand(String(req.params.id), command, { tenantId: req.tenantId, res });
    if ("error" in result) {
      return res.status(400).json(result);
    }
    res.json(result);
  }));

  app.post("/api/pam/sessions/:id/end", requireRole("admin"), asyncHandler(async (req, res) => {
    const { reason } = req.body;
    const result = await privilegedAccess.endSession(String(req.params.id), reason, { tenantId: req.tenantId, res });
    if ("error" in result) {
      return res.status(400).json(result);
    }
    res.json(result);
  }));

  app.get("/api/pam/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(await privilegedAccess.getStats({ tenantId: req.tenantId, res }));
  }));

  // ========================================
  // CORE BANKING SYSTEM (CBS) GATEWAY ENDPOINTS
  // ========================================

  // CBS Health Check
  app.get("/api/cbs/health", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(await coreBankingGateway.getAllCBSHealth());
  }));

  app.get("/api/cbs/health/:provider", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const health = await coreBankingGateway.checkCBSHealth(req.params.provider as any);
    res.json(health);
  }));

  // Kill-Switch Console
  app.get("/api/cbs/kill-switches", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { status, type, limit } = req.query;
    res.json(coreBankingGateway.getAllKillSwitches({
      status: status as any,
      type: type as any,
      limit: limit ? parseInt(limit as string) : undefined
    }));
  }));

  app.get("/api/cbs/kill-switches/active", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(coreBankingGateway.getActiveKillSwitches());
  }));

  app.post("/api/cbs/kill-switches/:id/release", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const _ksRelease = z.object({
      reason: z.string().optional(),
    }).safeParse(req.body);
    if (!_ksRelease.success) return res.status(400).json({ error: "Validation failed", details: _ksRelease.error.issues });
    const { reason } = _ksRelease.data;
    const userId = req.session.userId!;
    const result = await coreBankingGateway.releaseKillSwitch(String(req.params.id), userId, reason);
    
    if (result.success) {
      await storage.createAuditLog({
        action: "KILL_SWITCH_RELEASED",
        resource: "CBS Kill-Switch",
        userId,
        details: `Kill-switch ${req.params.id} released: ${reason || "No reason provided"}`,
        ipAddress: getClientIp(req),
      });
    }
    res.json(result);
  }));

  // Account Operations
  app.post("/api/cbs/accounts/freeze", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const _freeze = z.object({
      accountId: z.string().min(1),
      reason: z.string().min(1),
      provider: z.enum(["finacle", "flexcube", "t24", "generic"]).optional(),
    }).safeParse(req.body);
    if (!_freeze.success) return res.status(400).json({ error: "Validation failed", details: _freeze.error.issues });
    const { accountId, reason, provider } = _freeze.data;
    const result = await coreBankingGateway.freezeAccount(
      accountId,
      reason,
      req.session.userId!,
      provider
    );
    
    if (result.status === "SUCCESS") {
      await storage.createAuditLog({
        action: "ACCOUNT_FROZEN",
        resource: "Core Banking System",
        userId: req.session.userId!,
        details: `Account ${accountId} frozen via ${provider || "finacle"}: ${reason}`,
        ipAddress: getClientIp(req),
      });
    }
    res.json(result);
  }));

  app.post("/api/cbs/accounts/unfreeze", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const _unfreeze = z.object({
      accountId: z.string().min(1),
      reason: z.string().min(1),
      provider: z.enum(["finacle", "flexcube", "t24", "generic"]).optional(),
    }).safeParse(req.body);
    if (!_unfreeze.success) return res.status(400).json({ error: "Validation failed", details: _unfreeze.error.issues });
    const { accountId, reason, provider } = _unfreeze.data;
    const result = await coreBankingGateway.unfreezeAccount(
      accountId,
      reason,
      req.session.userId!,
      provider
    );
    
    if (result.status === "SUCCESS") {
      await storage.createAuditLog({
        action: "ACCOUNT_UNFROZEN",
        resource: "Core Banking System",
        userId: req.session.userId!,
        details: `Account ${accountId} unfrozen via ${provider || "finacle"}: ${reason}`,
        ipAddress: getClientIp(req),
      });
    }
    res.json(result);
  }));

  app.post("/api/cbs/accounts/pnd-hold", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const _pnd = z.object({
      accountId: z.string().min(1),
      reason: z.string().min(1),
      provider: z.enum(["finacle", "flexcube", "t24", "generic"]).optional(),
    }).safeParse(req.body);
    if (!_pnd.success) return res.status(400).json({ error: "Validation failed", details: _pnd.error.issues });
    const { accountId, reason, provider } = _pnd.data;
    const result = await coreBankingGateway.postNoDebitHold(
      accountId,
      reason,
      req.session.userId!,
      provider
    );
    res.json(result);
  }));

  // Transaction Operations
  app.post("/api/cbs/transactions/flag", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const _flag = z.object({
      transactionId: z.string().min(1),
      flag: z.enum(["REVIEW", "HOLD", "BLOCK", "RELEASE"]),
      reason: z.string().min(1),
      provider: z.enum(["finacle", "flexcube", "t24", "generic"]).optional(),
    }).safeParse(req.body);
    if (!_flag.success) return res.status(400).json({ error: "Validation failed", details: _flag.error.issues });
    const { transactionId, flag, reason, provider } = _flag.data;
    const result = await coreBankingGateway.flagTransaction(
      transactionId,
      flag,
      reason,
      req.session.userId!,
      provider
    );
    res.json(result);
  }));

  app.post("/api/cbs/transactions/reverse", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const _reverse = z.object({
      transactionId: z.string().min(1),
      reason: z.string().min(1),
      provider: z.enum(["finacle", "flexcube", "t24", "generic"]).optional(),
    }).safeParse(req.body);
    if (!_reverse.success) return res.status(400).json({ error: "Validation failed", details: _reverse.error.issues });
    const { transactionId, reason, provider } = _reverse.data;
    const result = await coreBankingGateway.reverseTransaction(
      transactionId,
      reason,
      req.session.userId!,
      provider
    );
    
    if (result.status === "SUCCESS") {
      await storage.createAuditLog({
        action: "TRANSACTION_REVERSED",
        resource: "Core Banking System",
        userId: req.session.userId!,
        details: `Transaction ${transactionId} reversed via ${provider || "finacle"}: ${reason}`,
        ipAddress: getClientIp(req),
      });
    }
    res.json(result);
  }));

  // Emergency Operations
  app.post("/api/cbs/emergency/freeze", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const _emergency = z.object({
      accountIds: z.array(z.string().min(1)).min(1),
      reason: z.string().min(1),
      provider: z.enum(["finacle", "flexcube", "t24", "generic"]).optional(),
    }).safeParse(req.body);
    if (!_emergency.success) return res.status(400).json({ error: "Validation failed", details: _emergency.error.issues });
    const { accountIds, reason, provider } = _emergency.data;
    const result = await coreBankingGateway.activateEmergencyFreeze(
      accountIds,
      reason,
      req.session.userId!,
      provider
    );
    
    await storage.createAuditLog({
      action: "EMERGENCY_FREEZE_EXECUTED",
      resource: "Core Banking System",
      userId: req.session.userId!,
      details: `Emergency freeze on ${accountIds.length} accounts: ${reason} (${result.success} successful, ${result.failed} failed)`,
      ipAddress: getClientIp(req),
    });
    
    res.json(result);
  }));

  // Transaction Logs
  app.get("/api/cbs/transaction-logs", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    res.json(coreBankingGateway.getRecentTransactionLogs(limit));
  }));

  app.get("/api/cbs/transaction-logs/:id", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const log = coreBankingGateway.getTransactionLog(String(req.params.id));
    if (!log) {
      return res.status(404).json({ error: "Transaction log not found" });
    }
    res.json(log);
  }));

  // CBS Stats
  app.get("/api/cbs/stats", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(coreBankingGateway.getStats());
  }));

  // ========================================
  // DEMO MODE ENDPOINTS
  // ========================================

  // Get demo mode state
  app.get("/api/demo/state", asyncHandler(async (req, res) => {
    res.json(demoMode.getState());
  }));

  // Get available demo scenarios
  app.get("/api/demo/scenarios", asyncHandler(async (req, res) => {
    res.json(demoMode.getScenarios());
  }));

  // Enable demo mode
  app.post("/api/demo/enable", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(demoMode.enableDemoMode());
  }));

  // Disable demo mode
  app.post("/api/demo/disable", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(demoMode.disableDemoMode());
  }));

  // Start a demo scenario
  app.post("/api/demo/start/:scenarioId", requireRole("admin"), asyncHandler(async (req, res) => {
    const result = demoMode.startScenario(String(req.params.scenarioId));
    if (!result.success) {
      return res.status(400).json(result);
    }
    res.json({ ...result, state: demoMode.getState() });
  }));

  // Trigger next demo step
  app.post("/api/demo/next-step", requireRole("admin"), asyncHandler(async (req, res) => {
    const result = demoMode.triggerNextStep();
    if (!result.success) {
      return res.status(400).json(result);
    }
    res.json({ ...result, state: demoMode.getState() });
  }));

  // Clear all threats (reset for repeat demo)
  app.post("/api/demo/clear-threats", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(demoMode.clearAllThreats());
  }));

  // Simulate CBS success response (for demo without real backend)
  app.post("/api/demo/simulate-cbs", requireRole("admin"), asyncHandler(async (req, res) => {
    const { operation } = req.body;
    res.json(demoMode.simulateCBSSuccess(operation || "freeze"));
  }));

  // Generate demo incident report
  app.get("/api/demo/incident-report", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(demoMode.generateDemoIncidentReport());
  }));

  // ========================================
  // UGANDA & EAST AFRICA COMPLIANCE ENDPOINTS
  // ========================================

  // Sovereignty Monitor
  app.get("/api/uganda/sovereignty/rules", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(sovereigntyMonitor.getRules());
  }));

  app.post("/api/uganda/sovereignty/check", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { dataType, sourceLocation, destinationLocation } = req.body;
    const result = sovereigntyMonitor.checkDataTransfer(dataType, sourceLocation, destinationLocation);
    res.json(result);
  }));

  app.get("/api/uganda/sovereignty/logs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 100;
    res.json(sovereigntyMonitor.getResidencyLogs(limit));
  }));

  app.get("/api/uganda/sovereignty/violations", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(sovereigntyMonitor.getViolations());
  }));

  // BoU Compliance Mapping
  app.get("/api/uganda/bou/controls", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string;
    const { category } = req.query;
    if (category) {
      res.json(await bouCompliance.getControlsByCategory(tenantId, category as string));
    } else {
      res.json(await bouCompliance.getControls(tenantId));
    }
  }));

  app.get("/api/uganda/bou/score", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await bouCompliance.getComplianceScore((req as any).tenantId as string));
  }));

  // ============ COMPLIANCE CHECK REGISTRY (AS/PLATFORM/2026/006) ============
  // Shared trigger: runs the narrow real-check registry once and PERSISTS one tenant-scoped
  // run (compliance_check_runs/_results under RLS). The regulator-facing modules (BoU mapping,
  // SovereignResilienceCertification, SOC2, dashboard) all DERIVE their status from the latest
  // persisted run — they never recompute on read. Tenant is session-derived (tenantMiddleware);
  // body/query tenantId is NEVER honoured. triggeredBy is server-derived from the session actor.
  app.post("/api/compliance/checks/run", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) {
      return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    }
    const triggeredBy = (req.session as any)?.username || String(req.session.userId ?? "system");
    const { runComplianceChecks } = await import("./lib/compliance-checks");
    const result = await runComplianceChecks({ tenantId, runType: "on_demand", triggeredBy });
    res.json({
      runId: result.runId,
      tenantId: result.tenantId,
      summary: result.summary,
      sourceDigest: result.sourceDigest,
      results: result.results,
    });
  }));

  // Read the LATEST PERSISTED compliance-check run (no recompute). Additive, read-only.
  // WHY THIS EXISTS: the operator UI must show the SAME run the audit-pack signs — the
  // pack (buildAuditPack) also reads getLatestRun, so surfacing that persisted run here
  // guarantees the on-screen result and the downloaded/signed pack cannot diverge. It
  // also lets an AUDITOR (who cannot POST /run) view the latest assessment read-only.
  // Shaped to MATCH the POST /run response so the client renders both identically.
  // Honest not-yet-run: no persisted run ⇒ { hasRun: false } (never a fabricated pack).
  app.get("/api/compliance/checks/latest", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) {
      return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    }
    const { getLatestRun } = await import("./lib/compliance-checks");
    const latest = await withTenantDbPhase(req, () => getLatestRun(tenantId));
    if (!latest) {
      return res.json({ hasRun: false });
    }
    const { run, results } = latest;
    const parseEvidence = (j: string | null): unknown => {
      if (!j) return undefined;
      try { return JSON.parse(j); } catch { return undefined; }
    };
    return res.json({
      hasRun: true,
      runId: run.id,
      tenantId: run.tenantId,
      runType: run.runType,
      triggeredBy: run.triggeredBy,
      ranAt: run.createdAt,
      sourceDigest: run.sourceDigest,
      // notAssessed is a first-class summary count — NEVER folded into pass.
      summary: {
        total: run.totalChecks,
        pass: run.passCount,
        fail: run.failCount,
        notAssessed: run.notAssessedCount,
      },
      results: results.map((r) => ({
        id: r.checkId,
        scope: r.scope,
        status: r.status, // PASS | FAIL | NOT_ASSESSED — surfaced verbatim
        detail: r.detail,
        evidence: parseEvidence(r.evidenceJson),
        checkedAt: r.checkedAt,
      })),
    });
  }));

  // USSD Security
  app.post("/api/uganda/ussd/session", requireRole("admin"), asyncHandler(async (req, res) => {
    const { msisdn, sessionCode, locationId } = req.body;
    const session = ussdSecurity.createSession(msisdn, sessionCode, locationId);
    res.json(session);
  }));

  app.post("/api/uganda/ussd/validate-pin", requireRole("admin"), asyncHandler(async (req, res) => {
    const { sessionId, pinEntrySpeed, currentLocationId } = req.body;
    try {
      const result = ussdSecurity.validatePinEntry(sessionId, pinEntrySpeed, currentLocationId);
      res.json(result);
    } catch (error: any) {
      res.status(400).json({ error: error.message });
    }
  }));

  app.get("/api/uganda/ussd/sessions", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(ussdSecurity.getActiveSessions());
  }));

  app.get("/api/uganda/ussd/sim-swap-alerts", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(ussdSecurity.getSimSwapAlerts());
  }));

  // A2A Payment Security (African-to-African)
  app.post("/api/uganda/a2a/transaction", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const {
      sourceCountry,
      destinationCountry,
      sourceCurrency,
      destinationCurrency,
      amount,
      exchangeRate,
      senderMsisdn,
      receiverMsisdn,
      paymentRail
    } = req.body;
    
    const result = a2aPaymentSecurity.processTransaction(
      sourceCountry,
      destinationCountry,
      sourceCurrency,
      destinationCurrency,
      amount,
      exchangeRate,
      senderMsisdn,
      receiverMsisdn,
      paymentRail
    );
    
    if (result.amlCheck.recommendation === "BLOCK") {
      await storage.createAuditLog({
        action: "A2A_TRANSACTION_BLOCKED",
        resource: "Cross-Border Payment",
        userId: req.session.userId!,
        details: `Transaction ${result.transaction.id} blocked. AML score: ${result.amlCheck.riskScore}. Flags: ${result.amlCheck.flags.join(", ")}`,
        ipAddress: getClientIp(req),
      });
    }
    
    res.json(result);
  }));

  app.get("/api/uganda/a2a/blocked", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(a2aPaymentSecurity.getBlockedTransactions());
  }));

  app.get("/api/uganda/a2a/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(a2aPaymentSecurity.getAMLStats());
  }));

  // Beera Ku Guard (Human-Centric Security)
  app.post("/api/uganda/beera-ku-guard/analyze", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { msisdn, message, channel } = req.body;
    const alert = bereaKuGuard.analyzeMessage(msisdn, message, channel);
    if (alert) {
      res.json({ detected: true, alert });
    } else {
      res.json({ detected: false, message: "No threats detected" });
    }
  }));

  app.get("/api/uganda/beera-ku-guard/alerts", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { resolved } = req.query;
    const resolvedFilter = resolved === "true" ? true : resolved === "false" ? false : undefined;
    res.json(bereaKuGuard.getAlerts(resolvedFilter));
  }));

  app.post("/api/uganda/beera-ku-guard/resolve/:alertId", requireRole("admin"), asyncHandler(async (req, res) => {
    const success = bereaKuGuard.resolveAlert(String(req.params.alertId));
    res.json({ success });
  }));

  app.get("/api/uganda/beera-ku-guard/tips", asyncHandler(async (req, res) => {
    res.json(bereaKuGuard.getEducationalTips());
  }));

  // ============ SOVEREIGN EDGE - STAGED-OFFLINE ARCHITECTURE ============
  
  app.get("/api/uganda/edge/nodes", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(sovereignEdge.getNodes());
  }));

  app.get("/api/uganda/edge/nodes/:nodeId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const node = sovereignEdge.getNode(String(req.params.nodeId));
    if (!node) {
      return res.status(404).json({ error: "Node not found" });
    }
    res.json(node);
  }));

  app.get("/api/uganda/edge/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(sovereignEdge.getStats());
  }));

  app.get("/api/uganda/edge/offline-transactions", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const nodeId = req.query.nodeId as string | undefined;
    res.json(sovereignEdge.getOfflineTransactions(nodeId));
  }));

  app.post("/api/uganda/edge/process-transaction", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { nodeId, transactionId, accountId, amount } = req.body;
    const result = sovereignEdge.processTransaction(nodeId, transactionId, accountId, amount);
    res.json(result);
  }));

  app.post("/api/uganda/edge/cache-trust-score", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { accountId, score, ttlMinutes } = req.body;
    sovereignEdge.cacheTrustScore(accountId, score, ttlMinutes || 60);
    res.json({ success: true, accountId, score, ttlMinutes: ttlMinutes || 60 });
  }));

  app.post("/api/uganda/edge/simulate-fiber-cut/:nodeId", requireRole("admin"), asyncHandler(async (req, res) => {
    const node = sovereignEdge.simulateFiberCut(String(req.params.nodeId));
    if (!node) {
      return res.status(400).json({ error: "Cannot simulate fiber cut on main brain or unknown node" });
    }
    res.json({ success: true, message: `Fiber cut simulated for ${node.name}`, node });
  }));

  app.post("/api/uganda/edge/restore-connection/:nodeId", requireRole("admin"), asyncHandler(async (req, res) => {
    const node = sovereignEdge.restoreConnection(String(req.params.nodeId));
    if (!node) {
      return res.status(404).json({ error: "Node not found" });
    }
    res.json({ success: true, message: `Connection restored for ${node.name}`, node });
  }));

  app.post("/api/uganda/edge/sync/:nodeId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const result = sovereignEdge.syncOfflineTransactions(String(req.params.nodeId));
    res.json({ success: true, ...result });
  }));

  // ============ TELCO GATEWAY - IMSI/SIM-SWAP PROTECTION ============

  app.get("/api/uganda/telco/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(telcoGateway.getStats());
  }));

  app.get("/api/uganda/telco/assessments", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(telcoGateway.getAssessments(limit));
  }));

  app.get("/api/uganda/telco/blocked", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(telcoGateway.getBlockedTransactions());
  }));

  app.post("/api/uganda/telco/assess-sim", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { msisdn, transactionAmountUGX } = req.body;
    const assessment = telcoGateway.assessSIMRisk(msisdn, transactionAmountUGX);
    res.json(assessment);
  }));

  app.get("/api/uganda/telco/sim/:msisdn", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const record = telcoGateway.getSIMRecord(String(req.params.msisdn));
    if (!record) {
      return res.status(404).json({ error: "SIM record not found" });
    }
    // Mask sensitive fields
    res.json({
      ...record,
      imsi: record.imsi.slice(0, 6) + "****",
      simSerialNumber: record.simSerialNumber.slice(0, 8) + "****"
    });
  }));

  app.post("/api/uganda/telco/bind-account", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { msisdn, accountId } = req.body;
    const success = telcoGateway.bindAccountToSIM(msisdn, accountId);
    res.json({ success, msisdn, accountId });
  }));

  // ============ SOVEREIGNTY LOCK - GEO-FENCED ROUTING ============

  app.get("/api/uganda/sovereignty-lock/nodes", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(sovereigntyLock.getNodes());
  }));

  app.get("/api/uganda/sovereignty-lock/map", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(sovereigntyLock.getNodesForMap());
  }));

  app.get("/api/uganda/sovereignty-lock/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(sovereigntyLock.getStats());
  }));

  app.get("/api/uganda/sovereignty-lock/routing", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(sovereigntyLock.getRoutingDecisions(limit));
  }));

  app.get("/api/uganda/sovereignty-lock/violations", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(sovereigntyLock.getViolations());
  }));

  app.post("/api/uganda/sovereignty-lock/route", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { dataType, sourceIP, destinationIP } = req.body;
    const decision = sovereigntyLock.routeData(dataType, sourceIP, destinationIP);
    res.json(decision);
  }));

  app.post("/api/uganda/sovereignty-lock/check-ip", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { ip } = req.body;
    const isUgandan = sovereigntyLock.isUgandanIP(ip);
    res.json({ ip, isUgandan, country: isUgandan ? "UG" : "FOREIGN" });
  }));

  // ============ OFFLINE SYNC PROTOCOL - MERKLE TREE DELTA-SYNC ============

  app.get("/api/uganda/sync/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(offlineSyncProtocol.getStats());
  }));

  app.get("/api/uganda/sync/shadow-ledger", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const nodeId = req.query.nodeId as string | undefined;
    const unreconciledOnly = req.query.unreconciled === "true";
    res.json(offlineSyncProtocol.getShadowLedger(nodeId, unreconciledOnly));
  }));

  app.get("/api/uganda/sync/batches", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const status = req.query.status as string | undefined;
    res.json(offlineSyncProtocol.getSyncBatches(status as any));
  }));

  app.post("/api/uganda/sync/add-to-ledger", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { nodeId, transactionId, trustScore } = req.body;
    const entry = offlineSyncProtocol.addToShadowLedger(nodeId, transactionId, trustScore);
    res.json(entry);
  }));

  app.post("/api/uganda/sync/create-batch", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { sourceNodeId, targetNodeId, transactions } = req.body;
    const batch = offlineSyncProtocol.createSyncBatch(sourceNodeId, targetNodeId, transactions);
    res.json(batch);
  }));

  app.post("/api/uganda/sync/validate-batch/:batchId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const result = offlineSyncProtocol.validateSyncBatch(String(req.params.batchId));
    res.json(result);
  }));

  app.post("/api/uganda/sync/resolve-conflict/:batchId", requireRole("admin"), asyncHandler(async (req, res) => {
    const { resolution } = req.body;
    const success = offlineSyncProtocol.resolveConflict(String(req.params.batchId), resolution);
    res.json({ success, batchId: req.params.batchId, resolution });
  }));

  app.get("/api/uganda/sync/merkle-root", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(offlineSyncProtocol.exportDailyMerkleRoot());
  }));

  // ============ CERTIFICATION OF SOVEREIGN RESILIENCE ============

  app.get("/api/uganda/certification", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await sovereignCertification.generateCertificate((req as any).tenantId as string));
  }));

  app.get("/api/uganda/certification/attestations", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string;
    const category = req.query.category as string | undefined;
    if (category) {
      res.json(await sovereignCertification.getAttestationsByCategory(tenantId, category));
    } else {
      res.json(await sovereignCertification.getAttestations(tenantId));
    }
  }));

  app.get("/api/uganda/certification/boardroom", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(sovereignCertification.generateBoardroomSummary());
  }));

  app.post("/api/uganda/certification/verify/:attestationId", requireRole("admin"), asyncHandler(async (req, res) => {
    // AS/PLATFORM/2026/006 (T002): the returned attestation's status is DERIVED from the latest
    // persisted compliance run for this tenant (read-only). verified=true only when the mapped
    // registry check PASSed in that run; unmapped/unassessed -> NOT_ASSESSED, verified=false.
    const attestation = await sovereignCertification.verifyAttestation((req as any).tenantId as string, String(req.params.attestationId));
    if (!attestation) {
      return res.status(404).json({ error: "Attestation not found" });
    }
    res.json({ verified: attestation.verified, attestation, disclaimer: UGANDA_CERT_DISCLAIMER });
  }));

  // ============ TIER-3 DATA CENTER ARCHITECTURE ============

  // ============ SD-WAN DUAL-PATH SIGNALING ============

  // ============ CYBER RECOVERY VAULT (AIR-GAPPED DR) ============

  // ============ CROSS-INDUSTRY: TELECOMMUNICATIONS & MOBILE MONEY ============

  // ============ CROSS-INDUSTRY: E-COMMERCE & LOGISTICS (AfCFTA) ============

  // ============ CROSS-INDUSTRY: GOVERNMENT / CIVIC-TECH ============

  // ============ CROSS-INDUSTRY: ENERGY / INDUSTRIAL IOT ============

  // ============ SAAS PLATFORM: METERING & BILLING (PUBLIC PRICING ONLY) ============
  // F-RP-04 (read-path-fix, 2026-06-20): the in-memory demo multi-tenant registry +
  // all-tenant metering routes were REMOVED. They served a fabricated 6-tenant demo
  // registry (saas-platform.ts MultiTenantIsolation/MeteringEngine — purely in-memory,
  // never persisted, gating nothing) reachable by ANY global-admin = a cross-tenant
  // disclosure surface over demo data. The real per-tenant SaaS surface is the
  // RLS-scoped DB path in wave-final-routes.ts (/api/saas/tenants/persisted, /persist,
  // /metering/persist). Only the PUBLIC pricing route is retained here.
  // Removed: GET /api/saas/tenants, /tenants/:tenantId, POST /tenants,
  // GET /tenants/industry/:industry, /tenants/tier/:tier, /tenants-stats,
  // POST /metering/log, GET /metering/usage/:tenantId, /metering/invoice/:tenantId/:periodId,
  // /metering/events, /metering/periods. See docs/regulatory/READPATH_SAAS_ASSESS.md.

  // ============ SAAS PLATFORM: SOVEREIGN PLAYBOOKS ============

  // ============ SAAS PLATFORM: MASTER GOVERNANCE ============

  // ============ SAAS PLATFORM: PRICING PAGE ============

  // ============ ENTERPRISE ALERTING: THRESHOLDS & RULES ============

  app.get("/api/alerting/thresholds", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(alertingThresholds.getThresholds());
  }));

  app.get("/api/alerting/rules", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(alertingThresholds.getRules());
  }));

  // On-demand evaluation of the REAL rules against current emitted metrics (error-rate,
  // p95 latency, uptime/restart). Planned k8s rules are skipped (never rendered "OK").
  // No scheduler — admin-triggered, mirrors the anomaly-sweep pattern.
  app.post("/api/alerting/evaluate", requireRole("admin"), asyncHandler(async (_req, res) => {
    const result = await alertingThresholds.evaluateRules();
    res.json(result);
  }));

  app.post("/api/alerting/trigger", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ruleId, currentValue, tenantId, metadata } = req.body;
    try {
      const alert = alertingThresholds.triggerAlert(ruleId, currentValue, tenantId, metadata);
      // Execute escalation
      const notifications = notificationPipeline.executeEscalation(alert);
      res.json({ success: true, alert, notificationsSent: notifications.length });
    } catch (error: any) {
      res.status(400).json({ error: error.message });
    }
  }));

  app.get("/api/alerting/active", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const severity = req.query.severity as string | undefined;
    res.json(alertingThresholds.getActiveAlerts(severity as any));
  }));

  app.get("/api/alerting/all", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(alertingThresholds.getAllAlerts());
  }));

  app.get("/api/alerting/tenant/:tenantId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    if (!(await assertTenantOwnership(req, res, String(req.params.tenantId)))) return;
    res.json(alertingThresholds.getAlertsByTenant(String(req.params.tenantId)));
  }));

  app.post("/api/alerting/acknowledge/:alertId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { acknowledgedBy } = req.body;
    const alert = alertingThresholds.acknowledgeAlert(String(req.params.alertId), acknowledgedBy);
    if (!alert) {
      return res.status(404).json({ error: "Alert not found" });
    }
    res.json({ success: true, alert });
  }));

  app.post("/api/alerting/resolve/:alertId", requireRole("admin"), asyncHandler(async (req, res) => {
    const alert = alertingThresholds.resolveAlert(String(req.params.alertId));
    if (!alert) {
      return res.status(404).json({ error: "Alert not found" });
    }
    res.json({ success: true, alert });
  }));

  // ============ ENTERPRISE ALERTING: NOTIFICATION PIPELINE ============

  app.get("/api/alerting/recipients", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(notificationPipeline.getRecipients());
  }));

  app.get("/api/alerting/escalation-policies", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(notificationPipeline.getPolicies());
  }));

  app.get("/api/alerting/notifications", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    res.json(notificationPipeline.getNotifications());
  }));

  app.get("/api/alerting/notifications/:alertId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(notificationPipeline.getNotificationsByAlert(String(req.params.alertId)));
  }));

  // ============ ENTERPRISE ALERTING: FINOPS ============

  app.get("/api/finops/costs", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(finOpsController.getPlatformCosts());
  }));

  app.get("/api/finops/pods", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(finOpsController.getPodCosts());
  }));

  app.get("/api/finops/budgets", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    res.json(finOpsController.getBudgets());
  }));

  app.get("/api/finops/budgets/:tenantId", requireRole("admin"), asyncHandler(async (req, res) => {
    if (!(await assertTenantOwnership(req, res, String(req.params.tenantId)))) return;
    const budget = finOpsController.getBudgetByTenant(String(req.params.tenantId));
    if (!budget) {
      return res.status(404).json({ error: "Budget not found for tenant" });
    }
    res.json(budget);
  }));

  app.get("/api/finops/recommendations", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json({
      recommendations: finOpsController.getRecommendations(),
      totalPotentialSavings: finOpsController.getTotalPotentialSavings()
    });
  }));

  // ============ ATTACK SIMULATION: MIDNIGHT MIRROR ============

  app.get("/api/simulation/status", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(midnightMirrorSimulation.getSimulation());
  }));

  app.post("/api/simulation/start", requireRole("admin"), asyncHandler(async (req, res) => {
    const simulation = midnightMirrorSimulation.startSimulation();
    res.json({ success: true, simulation });
  }));

  app.post("/api/simulation/stop", requireRole("admin"), asyncHandler(async (req, res) => {
    const simulation = midnightMirrorSimulation.stopSimulation();
    res.json({ success: true, simulation });
  }));

  app.post("/api/simulation/reset", requireRole("admin"), asyncHandler(async (req, res) => {
    const simulation = midnightMirrorSimulation.reset();
    res.json({ success: true, simulation });
  }));

  app.post("/api/simulation/fast-forward/:phase", requireRole("admin"), asyncHandler(async (req, res) => {
    const simulation = midnightMirrorSimulation.fastForward(req.params.phase as any);
    res.json({ success: true, simulation });
  }));

  app.get("/api/simulation/logs", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : undefined;
    res.json(midnightMirrorSimulation.getLogs(limit));
  }));

  app.get("/api/simulation/metrics", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    res.json(midnightMirrorSimulation.getMetrics());
  }));

  // ============ KYC (KNOW YOUR CUSTOMER) ============
  // Section renamed 2026-07-19: was "AGENTIC KYC". These routes are deterministic
  // sanctions/OFAC screening with human adjudication + operator-attested identity — NOT
  // agentic. Agentic KYC is roadmap-not-implemented (ENGINEERING_ROADMAP_2026.md Feature 5).

  // DB-primary KYC: these routes read/write the real `kyc_customers` store via IStorage
  // (tenant-scoped, encrypted PII, durable + fail-loud). The fake in-memory demo engine has
  // been retired. Verification is performed through the provider-abstracted identity adapter;
  // with no provider configured it returns an explicit non-pass state and NEVER APPROVED.

  // Require a resolved tenant context (set by tenant middleware from session/api-key/default,
  // never from a request header). Fail loud rather than silently defaulting.
  const requireKycTenant = (req: Request, res: Response): string | null => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) {
      res.status(400).json({
        error: "TENANT_CONTEXT_MISSING",
        message: "No tenant context resolved for this request.",
      });
      return null;
    }
    return tenantId;
  };

  // Map a persisted kyc_customers row to the dashboard DTO. Decrypted scalar PII is returned
  // as-is; dates are ISO strings; agentDecisions/lifeEvents are empty arrays in Feature 1
  // (per-decision/per-event persistence is a later feature — no synthetic rows are fabricated).
  const kycCustomerToDto = (c: KycCustomer) => ({
    id: c.id,
    nationalId: c.nationalId,
    fullName: c.fullName,
    dateOfBirth: c.dateOfBirth,
    phoneNumber: c.phoneNumber,
    email: c.email ?? undefined,
    address: c.address ?? undefined,
    status: c.status,
    riskTier: c.riskTier,
    onboardedAt: c.onboardedAt ? c.onboardedAt.toISOString() : null,
    lastVerifiedAt: c.lastVerifiedAt ? c.lastVerifiedAt.toISOString() : null,
    // agentDecisions dropped with KYCAgentDecision (2026-07-16) — it was hardcoded [] because the
    // 4-agent AI workforce it recorded decisions for never existed. tsc could NOT catch this one:
    // it is an untyped res.json literal, so the field simply became an extra property nobody checks.
    // Removed by the whole-path sweep, not by the compiler.
    lifeEvents: [] as never[],
  });

  app.get("/api/kyc/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const customers = await storage.listKycCustomers(tenantId);
    const countBy = (pred: (c: KycCustomer) => boolean) => customers.filter(pred).length;
    // Honest stats only: counts derived from real DB rows. Operational metrics that are not
    // measured (cost-per-verification, average-onboarding-time, agents-online) are deliberately
    // omitted rather than fabricated (Standing Rule 5).
    res.json({
      totalCustomers: customers.length,
      approved: countBy((c) => c.status === "APPROVED"),
      pending: countBy((c) => c.status === "PENDING" || c.status === "IN_PROGRESS"),
      rejected: countBy((c) => c.status === "REJECTED"),
      reviewRequired: countBy((c) => c.status === "REVIEW_REQUIRED" || c.status === "ESCALATED"),
      // pepCount is gated on the PEP screener's OWN configured state (the OFAC move — ask the
      // adapter, not the env). riskTier becomes "PEP" only when deriveRiskTier sees
      // isScreeningMatch(signals.pep), and signals.pep comes from the PEP adapter — which resolves
      // NOT_CONFIGURED when KYC_PEP_PROVIDER is unset (NoProviderPepAdapter, structurally incapable
      // of a match). So with no screener, no customer can EVER be tiered PEP, and a raw count of 0
      // renders "PEP: 0" on a bank's KYC footer — read as "screened, none found" when the truth is
      // nobody looked. null = NOT SCREENED (no provider); distinct from a real 0 (screener wired,
      // none found). Contrast highRiskCount below: its SANCTIONS tier comes from the WIRED OFAC
      // screen, so it is a genuinely reachable count that is honestly 0 today — left as-is.
      pepCount: getPepScreeningAdapter().isConfigured() ? countBy((c) => c.riskTier === "PEP") : null,
      highRiskCount: countBy((c) => c.riskTier === "HIGH" || c.riskTier === "SANCTIONS"),
    });
  }));

  // ── Sanctions screening list admin (OFAC SDN Increment 1) ──────────────────
  // Status: latest ingested list version + fresh/stale verdict. Read-only, role-gated.
  app.get("/api/kyc/sanctions/status", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const { getOfacSdnStatus } = await import("./lib/kyc/ofac-sdn-ingestion");
    const { getSanctionsScreeningAdapter } = await import("./lib/kyc/sanctions-screening-adapter");
    res.json({ activeProvider: getSanctionsScreeningAdapter().id, ...(await getOfacSdnStatus()) });
  }));

  // Refresh: pull + ingest the real OFAC SDN list. Admin-only, audit-logged. Throws (and
  // leaves the prior list untouched) on any fetch/parse failure — never seeds synthetic data.
  app.post("/api/kyc/sanctions/refresh", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ingestOfacSdn } = await import("./lib/kyc/ofac-sdn-ingestion");
    const result = await ingestOfacSdn();
    await storage.createAuditLog({
      userId: req.session?.userId ?? null,
      action: "SANCTIONS_LIST_REFRESH",
      resource: `sanctions:${result.source}`,
      details: `OFAC SDN list refreshed: ${result.primaryCount} primary + ${result.aliasCount} aliases (${result.entryCount} entries), version ${result.versionHash.slice(0, 12)}, fetched ${result.fetchedAt}.`,
    });
    res.json({ success: true, ...result });
  }));

  app.get("/api/kyc/agents", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    // No live KYC agent workforce exists in this build. Return empty rather than a static
    // "IDLE roster", which would imply deployed-but-idle agents that do not exist (Rule 5).
    res.json([]);
  }));

  // ── Periodic re-screen (list-update sweep) — evidence + hits (OFAC_RESCREEN_SCOPE.md) ──
  // Runs: GLOBAL no-PII sweep evidence (which list version, coverage, new hits, and the
  // fail-closed `unscreened` count). Auditor-readable — this is the examiner's answer to
  // "what happens when the list updates?".
  app.get("/api/kyc/sanctions/rescreen/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const { listRescreenRuns } = await import("./lib/kyc/sanctions-rescreen");
    res.json(await listRescreenRuns(50));
  }));

  // Hits: tenant-scoped SANCTIONS_HIT life events (signal records — entity ids + scores, no
  // raw PII; the sweep never decides, these are the flags awaiting human adjudication).
  app.get("/api/kyc/sanctions/rescreen/hits", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const { listRescreenHits } = await import("./lib/kyc/sanctions-rescreen");
    res.json(await listRescreenHits(tenantId, 100));
  }));

  app.get("/api/kyc/customers", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const rows = await storage.listKycCustomers(tenantId);
    res.json(rows.map(kycCustomerToDto));
  }));

  app.get("/api/kyc/customers/:id", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const row = await storage.getKycCustomerById(String(req.params.id), tenantId);
    if (!row) {
      return res.status(404).json({ error: "Customer not found" });
    }
    res.json(kycCustomerToDto(row));
  }));

  // KYC refined-C surfacing (2026-07-09): READ-ONLY latest sanctions screening SIGNAL for a
  // customer, so the primary KYC dashboard can show that a real OFAC screen ran and what it
  // returned — surfacing an under-representation where a genuine POTENTIAL_MATCH otherwise reads
  // as PENDING/LOW on the surface a bank looks at. This route does NOT re-screen on read (that
  // would turn a page-load into an expensive 39k-entry fuzzy match + an audit write on every
  // poll) and does NOT change customer state (records-never-decides): it reads the persisted
  // audit trail only. It returns the STATUS + timestamp — never a score (the score is not
  // persisted; the dashboard shows it solely via an explicit live re-screen). Tenant-gated: we
  // confirm the customer belongs to the caller's tenant BEFORE reading the (global) audit_logs
  // table, so no cross-tenant screening can be read by guessing a customer id.
  app.get("/api/kyc/customers/:id/screening", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const customerId = String(req.params.id);
    const customer = await storage.getKycCustomerById(customerId, tenantId);
    if (!customer) {
      return res.status(404).json({ error: "Customer not found" });
    }
    const latest = await storage.getLatestKycScreening(customerId, tenantId);
    // A: also return the CURRENT list version so the client can render honest STALENESS — if the
    // persisted screen ran against an older list than the one loaded now, the panel says so rather
    // than silently asserting currency it doesn't have. Global read; independent of the customer.
    const ofac = await getOfacSdnStatus();
    res.json({
      customerId,
      latest, // { source, sanctionsStatus, screenedAt, score, listVersionHash, listFetchedAt, matchedEntNum/Program/Name } | null
      currentList: { versionHash: ofac.versionHash, fetchedAt: ofac.fetchedAt, fresh: ofac.fresh },
    });
  }));

  // Minimal customer-onboarding primitive (KYC v1 Feature 1 — functional-close enabler).
  // Admin-only, tenant-scoped, DB-primary via storage.createKycCustomer (encrypted PII +
  // HMAC lookup, durable + fail-loud). The SERVER assigns the id — clients never control the
  // primary key. `status` is forwarded UNCHANGED to storage (NOT special-cased here) so that
  // assertNotApprovedWrite is the single structural guard refusing "APPROVED" on create: a
  // customer can never be onboarded as APPROVED — approval is a separate, gated decision.
  app.post("/api/kyc/customers", requireRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;

    const createSchema = z.object({
      nationalId: z.string().trim().min(1),
      fullName: z.string().trim().min(1),
      dateOfBirth: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "dateOfBirth must be YYYY-MM-DD"),
      phoneNumber: z.string().trim().min(1),
      email: z.string().trim().min(1).optional(),
      address: z.string().trim().min(1).optional(),
      photoUrl: z.string().trim().min(1).optional(),
      status: z
        .enum(["PENDING", "IN_PROGRESS", "APPROVED", "REJECTED", "ESCALATED", "REVIEW_REQUIRED"])
        .optional(),
      riskTier: z.enum(["LOW", "MEDIUM", "HIGH", "PEP", "SANCTIONS"]).optional(),
    });
    const parsed = createSchema.safeParse(req.body ?? {});
    if (!parsed.success) {
      return res.status(400).json({
        error: "VALIDATION_ERROR",
        message: "Invalid KYC customer payload.",
        details: parsed.error.flatten(),
      });
    }

    // Fail-loud: storage THROWS on APPROVED (assertNotApprovedWrite) and on a duplicate
    // national_id (unique HMAC index). Errors propagate via asyncHandler — never swallowed.
    const created = await storage.createKycCustomer({ id: randomUUID(), ...parsed.data }, tenantId);

    // Durable, fail-loud audit (audit_logs + hash chain), mirroring the verify route's pattern.
    await storage.createAuditLog({
      userId: (req.session as any)?.userId ?? null,
      action: "KYC_CUSTOMER_CREATE",
      resource: `kyc_customers/${created.id}`,
      details: `KYC customer onboarded via /api/kyc/customers (status ${created.status}, riskTier ${created.riskTier}).`,
      ipAddress: req.ip ?? null,
    });

    res.status(201).json(kycCustomerToDto(created));
  }));

  app.get("/api/kyc/logs", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    // No live agent activity stream in Feature 1. Returns empty rather than fabricated entries.
    res.json([]);
  }));

  app.get("/api/kyc/simulation", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    // The random demo simulation has been retired. Honest static state: nothing is running.
    res.json({ isRunning: false, activeCustomerId: null, agentStatuses: [] });
  }));

  app.post("/api/kyc/verify/:customerId", requireRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const customerId = String(req.params.customerId);

    const customer = await storage.getKycCustomerById(customerId, tenantId);
    if (!customer) {
      return res.status(404).json({ error: "Customer not found" });
    }

    const adapter = getIdentityVerificationAdapter();
    const correlationId = `kyc-verify-${customerId}-${Date.now()}`;
    const result = await adapter.verifyIdentity({
      tenantId,
      customerId,
      nationalId: customer.nationalId,
      fullName: customer.fullName,
      dateOfBirth: customer.dateOfBirth,
      phoneNumber: customer.phoneNumber ?? undefined,
      correlationId,
    });

    // Verification alone NEVER approves. A confirmed identity advances the customer to
    // IN_PROGRESS (decisioning/EDD/approval is a separate, gated step). Every other adapter
    // outcome — including "no provider configured" — routes to human REVIEW_REQUIRED.
    // APPROVED is unreachable here, and updateKycCustomerStatusAndRisk also refuses it structurally.
    const nextStatus: KYCStatus = result.status === "VERIFIED" ? "IN_PROGRESS" : "REVIEW_REQUIRED";

    const updated = await storage.updateKycCustomerStatusAndRisk(customerId, tenantId, {
      status: nextStatus,
      lastVerifiedAt: new Date(),
    });

    // Durable, fail-loud audit (audit_logs + hash chain). Not routed through auditDb directly:
    // kyc_customers is a tenant table and stays on the request tenant transaction.
    await storage.createAuditLog({
      userId: (req.session as any)?.userId ?? null,
      action: "KYC_IDENTITY_VERIFY",
      resource: `kyc_customers/${customerId}`,
      details:
        `Identity verification via adapter '${adapter.id}' (configured=${adapter.isConfigured()}): ` +
        `result=${result.status} verified=${result.verified} ` +
        `confidence=${result.confidence ?? "n/a"} → KYC status ${nextStatus}. ${result.evidenceSummary}`,
      ipAddress: req.ip ?? null,
    });

    res.json({
      success: true,
      customerId,
      adapter: { id: adapter.id, displayName: adapter.displayName, configured: adapter.isConfigured() },
      verification: {
        status: result.status,
        verified: result.verified,
        confidence: result.confidence ?? null,
        providerReference: result.providerReference ?? null,
        evidenceSummary: result.evidenceSummary,
        checkedAt: result.checkedAt,
      },
      customerStatus: updated?.status ?? nextStatus,
    });
  }));

  // KYC v1 Feature 2 — PEP + sanctions screening. Two INDEPENDENT adapter seams (a deployment may
  // have one feed wired and not the other). Distinct from /verify: screening is a separate operation.
  // BINDING DISCIPLINE (both directions): with no provider configured each seam returns NOT_CONFIGURED
  // — never a fabricated hit AND never a fabricated "clear" (a fabricated clear is the dangerous one:
  // it would silently wave a real sanctioned/PEP subject through). The screening-types invariant
  // enforces this structurally; this route re-asserts each result before recording. Feature 2 RECORDS
  // signals only — it changes NO customer state (no status, no risk_tier). Decisioning and the
  // "high-risk/PEP can never be auto-approved" guardrail are Feature 3, separately gated.
  app.post("/api/kyc/screen/:customerId", requireRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const customerId = String(req.params.customerId);

    const customer = await storage.getKycCustomerById(customerId, tenantId);
    if (!customer) {
      return res.status(404).json({ error: "Customer not found" });
    }

    const pepAdapter = getPepScreeningAdapter();
    const sanctionsAdapter = getSanctionsScreeningAdapter();
    const correlationId = `kyc-screen-${customerId}-${Date.now()}`;
    const input = {
      tenantId,
      customerId,
      fullName: customer.fullName,
      dateOfBirth: customer.dateOfBirth,
      nationalId: customer.nationalId,
      correlationId,
    };

    const pep = assertScreeningResultInvariant(await pepAdapter.screenPep(input));
    const sanctions = assertScreeningResultInvariant(await sanctionsAdapter.screenSanctions(input));

    // Safe aggregates. NO generic "passed" boolean is exposed. "allClear" requires BOTH seams to be
    // determinate AND CLEAR; if either is indeterminate (NOT_CONFIGURED / PROVIDER_ERROR) the
    // aggregate is NOT clear — indeterminate is never collapsed into clear.
    const screeningDeterminate = pep.screened && sanctions.screened;
    const allClear = screeningDeterminate && pep.status === "CLEAR" && sanctions.status === "CLEAR";
    const hasPotentialOrConfirmedMatch = [pep, sanctions].some(
      (r) => r.status === "POTENTIAL_MATCH" || r.status === "CONFIRMED_MATCH",
    );
    const indeterminateReasons: string[] = [];
    if (!pep.screened) indeterminateReasons.push(`PEP:${pep.status}`);
    if (!sanctions.screened) indeterminateReasons.push(`SANCTIONS:${sanctions.status}`);

    // Durable, fail-loud audit_logs write (mirroring the verify route): the audit_logs INSERT is
    // awaited and propagates on failure (asyncHandler), so a failed audit fails the request — it is
    // never silently dropped. The hash-chain leg inside storage.createAuditLog is best-effort BY
    // DESIGN (a chain-write failure is logged but does not break the audit_logs write); on the
    // normal path the entry IS chained (functionally verified). kyc_customers is a tenant table, so
    // this stays on the request tenant transaction (NOT auditDb directly). No PII (national id /
    // DOB) is written to the audit detail.
    await storage.createAuditLog({
      userId: (req.session as any)?.userId ?? null,
      action: "KYC_SCREENING",
      resource: `kyc_customers/${customerId}`,
      // ⚠ PARSED BY GET /api/kyc/customers/:id/screening (storage.getLatestKycScreening regexes
      // `sanctions=<STATUS>` out of this string) to render the KYC-dashboard screening panel. Do NOT
      // reword the `sanctions=${...}` token without updating that parser — a drift degrades the panel
      // to "result unavailable" (fails SAFE, never to CLEAR). The durable fix is structured columns
      // (kyc_screening_results, the recorded end-state) which remove this freetext coupling entirely.
      details:
        `PEP+sanctions screening via adapters ` +
        `pep='${pep.providerId}'(configured=${pepAdapter.isConfigured()}) ` +
        `sanctions='${sanctions.providerId}'(configured=${sanctionsAdapter.isConfigured()}): ` +
        `pep=${pep.status} sanctions=${sanctions.status} ` +
        `screeningDeterminate=${screeningDeterminate} allClear=${allClear} ` +
        `matches(pep=${pep.matches.length},sanctions=${sanctions.matches.length}). ` +
        `No customer state changed (signals recorded only). correlationId=${correlationId}`,
      ipAddress: req.ip ?? null,
    });

    // A (kyc_screening_results) — persist the durable per-screen history the platform used to
    // forget: status + score + list VERSION + matched-entry SNAPSHOT, one row per screen_type.
    // FAIL-OPEN ON RECORDING (never on screening): the screen already succeeded and its result is
    // returned below regardless; a history-write failure is logged loudly and the dashboard panel
    // simply falls back to the legacy/no-row path. AWAITED inside a bounded withTenantDbPhase so the
    // tenant GUC is set (RLS WITH CHECK) and the COMMIT lands before we respond — NEVER void-fired
    // (fire-and-forget is precisely the pattern that forked the audit chain across a restart).
    // records-never-decides: this writes history only; customer status/risk_tier are untouched.
    try {
      const ofac = await getOfacSdnStatus(); // list VERSION the sanctions screen ran against (global read)
      // Snapshot the HIGHEST-SCORE sanctions hit coherently — score + ent_num + program + name all
      // from the SAME match (matches empty for CLEAR / indeterminate → all null).
      const topSanctions = sanctions.matches.length
        ? sanctions.matches.reduce((a, b) => ((b.score ?? 0) > (a.score ?? 0) ? b : a))
        : undefined;
      const historyRows: InsertKycScreeningResult[] = [
        {
          tenantId, customerId, screenType: "SANCTIONS",
          status: sanctions.status, providerId: sanctions.providerId,
          score: topSanctions?.score != null ? String(topSanctions.score) : null,
          listSource: sanctions.screened ? OFAC_SDN_SOURCE : null,
          listVersionHash: sanctions.screened ? ofac.versionHash : null,
          listFetchedAt: sanctions.screened && ofac.fetchedAt ? new Date(ofac.fetchedAt) : null,
          matchedEntNum: topSanctions?.entNum ?? null,
          matchedProgram: topSanctions?.program ?? null,
          matchedName: topSanctions?.matchedName ?? null,
          evidenceSummary: sanctions.evidenceSummary,
          screenedAt: new Date(sanctions.checkedAt),
        },
        {
          // PEP row records exactly what the provider returned — including a genuine NOT_CONFIGURED
          // ("did you check? no, and here's why"). NEVER a fabricated result; no list stamp when unscreened.
          tenantId, customerId, screenType: "PEP",
          status: pep.status, providerId: pep.providerId,
          score: null, listSource: null, listVersionHash: null, listFetchedAt: null,
          matchedEntNum: null, matchedProgram: null, matchedName: null,
          evidenceSummary: pep.evidenceSummary,
          screenedAt: new Date(pep.checkedAt),
        },
      ];
      await withTenantDbPhase(req, () => storage.recordKycScreening(historyRows));
    } catch (recErr) {
      // FAIL-OPEN on recording (the screen result already returned to the caller; a history-write
      // failure must NEVER fail the screen). PII-safe log via the shared redactedError helper: a
      // drizzle error's .message + .stack embed the INSERT params incl. evidence_summary (the
      // customer's cleartext name), so we log ONLY the pg SQLSTATE + a param-free message + the app
      // call frames — never the raw error. Same helper the global error handler uses (one place to
      // get the extraction right). Verified PII-absent via the REVOKE-INSERT harness.
      apiLogger.error("KYC screening-history persist failed (screen result returned to caller; panel falls back to legacy/no-row)", {
        metadata: { customerId, correlationId, ...redactedError(recErr) },
      });
    }

    res.json({
      success: true,
      customerId,
      screening: {
        pep: {
          kind: pep.kind,
          status: pep.status,
          screened: pep.screened,
          providerId: pep.providerId,
          configured: pepAdapter.isConfigured(),
          matchCount: pep.matches.length,
          matches: pep.matches, // listName + real confidence score + note — for human adjudication
          evidenceSummary: pep.evidenceSummary,
          checkedAt: pep.checkedAt,
        },
        sanctions: {
          kind: sanctions.kind,
          status: sanctions.status,
          screened: sanctions.screened,
          providerId: sanctions.providerId,
          configured: sanctionsAdapter.isConfigured(),
          matchCount: sanctions.matches.length,
          matches: sanctions.matches, // listName + real confidence score + note — for human adjudication
          evidenceSummary: sanctions.evidenceSummary,
          checkedAt: sanctions.checkedAt,
        },
        aggregate: {
          screeningDeterminate,
          allClear,
          hasPotentialOrConfirmedMatch,
          indeterminateReasons,
        },
      },
      // Feature 2 records signals only — no customer state is changed here (Feature 3 decides).
      customerStatusUnchanged: customer.status,
    });
  }));

  // ── KYC v1 Feature 3 — Decision engine (spec AS/KYC/2026/002) ───────────────
  // Two routes with a hard separation of duties:
  //  (1) POST /decide  — proposes a deterministic disposition from FRESH F1/F2
  //      signals (collected NOW, never browser-supplied) and records a decision
  //      outcome. It NEVER sets a customer APPROVED: the customer moves to
  //      REJECTED / ESCALATED / REVIEW_REQUIRED, and an APPROVE is parked as
  //      PENDING_SENIOR_APPROVAL awaiting two-eyes sign-off.
  //  (2) POST /decisions/:id/approve — records a senior (risk_manager/admin)
  //      sign-off and is the SOLE path that finalizes a customer to APPROVED,
  //      and only through the locked-door storage guard (re-collects fresh
  //      signals, re-decides, re-checks the signals hash, and enforces
  //      decider ≠ approver). A high-risk/PEP subject can never be auto-approved.
  app.post("/api/kyc/decide/:customerId", requireRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const customerId = String(req.params.customerId);
    const userId = req.session.userId;
    const userRole = req.session.userRole;
    if (!userId || !userRole) {
      return res.status(401).json({ error: "AUTH_REQUIRED", message: "Authenticated decider required." });
    }

    const customer = await storage.getKycCustomerById(customerId, tenantId);
    if (!customer) {
      return res.status(404).json({ error: "Customer not found" });
    }

    // Collect FRESH signals NOW (never browser-supplied), derive risk, decide.
    const correlationId = `kyc-decide-${customerId}-${Date.now()}`;
    const existingRiskTier = coerceRiskTier(customer.riskTier);
    const subject: KycSubjectForDecision = {
      id: customer.id,
      tenantId,
      nationalId: customer.nationalId,
      fullName: customer.fullName,
      dateOfBirth: customer.dateOfBirth,
      phoneNumber: customer.phoneNumber ?? null,
      riskTier: existingRiskTier,
    };
    const signals = await collectFreshSignals(subject, correlationId);
    const derivedRiskTier = deriveRiskTier(existingRiskTier, signals);
    const plan = decide(signals, derivedRiskTier);
    const snapshot = buildSignalsSnapshot(tenantId, customerId, existingRiskTier, derivedRiskTier, signals);
    const signalsHash = computeSignalsHash(snapshot);

    // Persist the decision outcome. NEVER sets the customer APPROVED here.
    const outcome = await storage.createKycDecisionOutcome(
      {
        customerId,
        disposition: plan.disposition,
        strFlag: plan.strFlag,
        strReason: plan.strReason,
        state: plan.state,
        requiresSeniorApproval: plan.requiresSeniorApproval,
        riskTier: derivedRiskTier,
        signalsSnapshot: JSON.stringify(snapshot),
        signalsHash,
        explanation: `${plan.ruleId}: ${plan.explanation}`,
        decidedByUserId: userId,
        decidedByRole: userRole,
      },
      tenantId,
    );

    const updatedCustomer = await storage.updateKycCustomerStatusAndRisk(customerId, tenantId, {
      status: plan.nextCustomerStatus,
      riskTier: derivedRiskTier,
    });

    // Durable, fail-loud audit (no PII). KYC tables stay on the request tenant tx.
    await storage.createAuditLog({
      userId,
      action: "KYC_DECISION",
      resource: `kyc_decision_outcomes/${outcome.id}`,
      details:
        `Decision ${plan.disposition} (rule ${plan.ruleId}, state ${plan.state}) for customer ${customerId}: ` +
        `derivedRiskTier=${derivedRiskTier} requiresSeniorApproval=${plan.requiresSeniorApproval} ` +
        `str=${plan.strFlag}${plan.strReason ? ` (${plan.strReason})` : ""} → customer status ${plan.nextCustomerStatus}. ` +
        `NO customer APPROVED on decide. signalsHash=${signalsHash.slice(0, 16)}… correlationId=${correlationId}`,
      ipAddress: req.ip ?? null,
    });

    res.status(201).json({
      success: true,
      decision: {
        id: outcome.id,
        disposition: plan.disposition,
        state: plan.state,
        requiresSeniorApproval: plan.requiresSeniorApproval,
        riskTier: derivedRiskTier,
        strFlag: plan.strFlag,
        strReason: plan.strReason,
        ruleId: plan.ruleId,
        explanation: plan.explanation,
        signalsHash,
      },
      customerStatus: updatedCustomer?.status ?? plan.nextCustomerStatus,
      snapshot,
    });
  }));

  app.post("/api/kyc/decisions/:id/approve", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const decisionId = String(req.params.id);
    const approverUserId = req.session.userId;
    const approverRole = req.session.userRole;
    if (!approverUserId || !approverRole) {
      return res.status(401).json({ error: "AUTH_REQUIRED", message: "Authenticated approver required." });
    }

    // No signals in the body — they are re-collected fresh inside the finalizer.
    const bodySchema = z.object({ reason: z.string().trim().min(1).max(500).optional() });
    const parsed = bodySchema.safeParse(req.body ?? {});
    if (!parsed.success) {
      return res.status(400).json({ error: "VALIDATION_ERROR", message: "Invalid approval payload.", details: parsed.error.flatten() });
    }

    const correlationId = `kyc-approve-${decisionId}-${Date.now()}`;
    try {
      const result = await storage.recordApprovalAndFinalize({
        decisionId,
        tenantId,
        approverUserId,
        approverRole,
        reason: parsed.data.reason ?? null,
        correlationId,
      });

      // Durable, fail-loud audit (no PII). Same request tenant tx as the finalize:
      // an audit failure rolls the finalize back too (atomic).
      await storage.createAuditLog({
        userId: approverUserId,
        action: "KYC_DECISION_APPROVE",
        resource: `kyc_decision_outcomes/${decisionId}`,
        details:
          `Senior two-eyes approval recorded (approver role ${approverRole}) for decision ${decisionId}: ` +
          `customer ${result.customer.id} finalized APPROVED (riskTier ${result.customer.riskTier}); ` +
          `outcome state ${result.outcome.state}; approvalId=${result.approval.id}. correlationId=${correlationId}`,
        ipAddress: req.ip ?? null,
      });

      res.json({
        success: true,
        decisionId,
        outcomeState: result.outcome.state,
        customerStatus: result.customer.status,
        approval: {
          id: result.approval.id,
          approverRole: result.approval.approverRole,
          approvalType: result.approval.approvalType,
        },
      });
    } catch (err) {
      if (err instanceof FinalizeGuardError) {
        const status = err.code === "NOT_FOUND" ? 404 : 409;
        return res.status(status).json({ error: "FINALIZE_GUARD", code: err.code, message: err.message });
      }
      throw err; // unexpected → 500 → per-request tx rollback (atomic)
    }
  }));

  // MANUAL IDENTITY ATTESTATION (Build B: manual-identity path). A compliance officer records
  // a real document-review determination; the ManualAttestationIdentityAdapter reads the latest
  // per customer as the identity signal. HONEST-FLOOR: this is a HUMAN attestation — the adapter
  // stamps method=MANUAL_ATTESTATION so no surface renders it as automated (NIRA) verification.
  // Privileged write: admin/risk_manager, CSRF (global), audit-chained (same discipline as decide/approve).
  app.post("/api/kyc/identity/attest/:customerId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const customerId = String(req.params.customerId);
    const userId = req.session.userId;
    const userRole = (req.session as any).userRole as string | undefined;
    if (!userId || !userRole) {
      return res.status(401).json({ error: "AUTH_REQUIRED", message: "Authenticated attester required." });
    }
    const parsed = z
      .object({
        status: z.enum(["VERIFIED", "NOT_VERIFIED", "REVIEW_REQUIRED"]),
        evidenceRef: z.string().trim().min(1).max(256).optional(),
        notes: z.string().trim().min(1).max(1000).optional(),
      })
      .strict()
      .safeParse(req.body ?? {});
    if (!parsed.success) {
      return res.status(400).json({ error: "VALIDATION_ERROR", message: "Invalid attestation payload.", details: parsed.error.flatten() });
    }
    const customer = await storage.getKycCustomerById(customerId, tenantId);
    if (!customer) {
      return res.status(404).json({ error: "Customer not found" });
    }
    const attestation = await storage.createKycIdentityAttestation({
      tenantId,
      customerId,
      status: parsed.data.status,
      evidenceRef: parsed.data.evidenceRef ?? null,
      notes: parsed.data.notes ?? null,
      attestedByUserId: userId,
      attestedByRole: userRole,
    });
    // Audit-chain the privileged write (no raw PII in the detail).
    await storage.createAuditLog({
      userId,
      action: "KYC_IDENTITY_ATTEST",
      resource: `kyc_customers/${customerId}`,
      details:
        `Manual identity attestation recorded: status=${parsed.data.status} by role ${userRole} ` +
        `(HUMAN document review, method=MANUAL_ATTESTATION — NOT an automated NIRA register match). ` +
        `attestationId=${attestation.id}`,
      ipAddress: getClientIp(req),
    });
    return res.status(201).json({
      success: true,
      attestation: {
        id: attestation.id,
        customerId: attestation.customerId,
        status: attestation.status,
        method: attestation.status === "VERIFIED" ? "MANUAL_ATTESTATION" : null,
        attestedByRole: attestation.attestedByRole,
        attestedAt: attestation.attestedAt,
      },
    });
  }));

  // Read the latest manual identity attestation for a customer (for the operator UI).
  app.get("/api/kyc/identity/attestation/:customerId", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = requireKycTenant(req, res);
    if (!tenantId) return;
    const customerId = String(req.params.customerId);
    const latest = await storage.getLatestKycIdentityAttestation(tenantId, customerId);
    if (!latest) {
      return res.json({ hasAttestation: false });
    }
    return res.json({
      hasAttestation: true,
      id: latest.id,
      customerId: latest.customerId,
      status: latest.status,
      // Provenance is structural — a VERIFIED attestation is human-attested, never automated.
      method: latest.status === "VERIFIED" ? "MANUAL_ATTESTATION" : null,
      evidenceRef: latest.evidenceRef,
      notes: latest.notes,
      attestedByRole: latest.attestedByRole,
      attestedAt: latest.attestedAt,
    });
  }));

  app.post("/api/kyc/life-event", requireRole("admin"), asyncHandler(async (req, res) => {
    // Perpetual-monitoring life events are a later KYC feature. Honest-disabled rather than
    // generating synthetic events.
    res.status(501).json({
      error: "NOT_IMPLEMENTED",
      message: "KYC life-event capture is not enabled in this build. No synthetic life events are generated.",
    });
  }));

  // ============ SERIES A READY: SAFETY RAILS (KILL SWITCH) ============

  app.get("/api/safety/state", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(safetyRails.getSafetyRailState());
  }));

  app.get("/api/safety/config", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(safetyRails.getSafetyConfig());
  }));

  app.get("/api/safety/violations", requireRole("admin"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    res.json(safetyRails.getViolations(limit));
  }));

  app.get("/api/safety/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(safetyRails.getViolationStats());
  }));

  app.get("/api/safety/keys", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(safetyRails.getAgentKeys());
  }));

  app.post("/api/safety/lockdown", requireRole("admin"), asyncHandler(async (req, res) => {
    const { reason } = req.body;
    const result = safetyRails.triggerFullLockdown(reason || "Manual lockdown triggered");
    res.json(result);
  }));

  app.post("/api/safety/reset", requireRole("admin"), asyncHandler(async (req, res) => {
    const { authorizationCode } = req.body;
    const result = safetyRails.resetLockdown(authorizationCode);
    res.json(result);
  }));

  // ============ #50 P2: TRANSACTION-ANOMALY DETECTION ============
  // Real statistical detector over kyt_results (not "zero-day" — that engine was
  // fabricated + deleted in 40abe2d). On-demand sweep (no boot loop). Tenant-scoped
  // via RLS. Honest three-state empty-state (NOT_YET_SWEPT / CLEAN / DETECTIONS).
  app.post("/api/transaction-anomaly/sweep", requireRole("admin"), asyncHandler(async (_req, res) => {
    const { runSweep } = await import("./lib/transaction-anomaly/sweep");
    const summary = await runSweep();
    res.json(summary);
  }));

  app.get("/api/transaction-anomaly/detections", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const { getAnomalyView } = await import("./lib/transaction-anomaly/store");
    const view = await withTenantDbPhase(req as { tenantId?: string }, () => getAnomalyView(db));
    res.json(view);
  }));

  // ============ SERIES A READY: HSM INTEGRATION ============

  app.get("/api/hsm/state", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(hsmIntegration.getHSMState());
  }));

  app.get("/api/hsm/config", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(hsmIntegration.getHSMConfig());
  }));

  app.get("/api/hsm/keys", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(hsmIntegration.getKeys());
  }));

  app.get("/api/hsm/operations", requireRole("admin"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    res.json(hsmIntegration.getOperations(limit));
  }));

  app.get("/api/hsm/health", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(hsmIntegration.healthCheck());
  }));

  app.post("/api/hsm/sign", requireRole("admin"), asyncHandler(async (req, res) => {
    const { keyId, data } = req.body;
    const result = hsmIntegration.signWithHSM(keyId, data);
    res.json(result);
  }));

  // ============ SERIES A READY: GULU MESH NETWORK ============

  // ============ SERIES A READY: REGULATOR GATEWAY ============

  app.get("/api/regulator/state", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(regulatorGateway.getRegulatoryState());
  }));

  app.get("/api/regulator/sars", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const status = req.query.status as any;
    res.json(await regulatorGateway.getSARs(status));
  }));

  app.get("/api/regulator/sars/:id", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const sar = await regulatorGateway.getSAR(String(req.params.id));
    if (!sar) {
      return res.status(404).json({ error: "SAR not found" });
    }
    res.json(sar);
  }));

  app.get("/api/regulator/explanations", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    res.json(regulatorGateway.getExplanations(limit));
  }));

  app.get("/api/regulator/explanations/:id", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const explanation = regulatorGateway.getExplanation(String(req.params.id));
    if (!explanation) {
      return res.status(404).json({ error: "Explanation dossier not found" });
    }
    res.json(explanation);
  }));

  app.get("/api/regulator/sessions", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(regulatorGateway.getRegulatorSessions());
  }));

  app.get("/api/regulator/sandboxes", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(regulatorGateway.getSandboxes());
  }));

  app.post("/api/regulator/session", requireRole("admin"), asyncHandler(async (req, res) => {
    const { regulatorId, regulatorName, organization, accessLevel, durationHours } = req.body;
    const session = await regulatorGateway.createRegulatorSession({
      regulatorId,
      regulatorName,
      organization,
      accessLevel: accessLevel || "READ_ONLY",
      ipAddress: req.ip || "unknown",
      durationHours
    });
    res.json(session);
  }));

  app.get("/api/regulator/dashboard/:sessionId", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const result = regulatorGateway.getRegulatorDashboard(String(req.params.sessionId));
    if (!result.authorized) {
      return res.status(403).json({ error: result.error });
    }
    res.json(result.data);
  }));

  // ============ AI BILL OF MATERIALS (A-BOM) ============

  app.get("/api/abom/summary", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    res.json(aiBom.getSummary());
  }));

  app.get("/api/abom/components", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    res.json(aiBom.getComponents());
  }));

  app.get("/api/abom/data-sources", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    res.json(aiBom.getDataSources());
  }));

  app.get("/api/abom/export", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(aiBom.exportSBOM());
  }));

  // POST /api/abom/scan REMOVED (2026-07-16) with aiBom.runSecurityScan. It returned a
  // manufactured all-clear — "Scanned N components. Found 0 vulnerabilities (0 critical)" — from a
  // function that stamped a timestamp and counted an array nothing writes. No CVE lookup, no
  // scanner. NOTE: extras8.runSecurityScan (routes.ts:7244) is a DIFFERENT, REAL function (HTTP
  // header scanning against a target URL) and is untouched — the two shared a name.

  // ============ MULTI-DIALECT NLP (Social Engineering Filter) ============

  // ============ TENANT BILLING — REMOVED 2026-07-03 (sovereign-per-bank/single-tenant) ============
  // Per-tenant SaaS billing (tenants/usage/invoices/pricing tiers) for a multi-tenant-SaaS business
  // the platform does not operate. tenant-billing.ts backing module deleted; routes removed chain-complete.

  // ============ CLOUD EXIT SWITCH (Sovereign Cloud) ============

  // ============ SOVEREIGN READINESS (Exit Drills, Dead-Man's Switch, Multi-Vendor) ============

  // Exit Drills (Chaos Monkey)
  app.get("/api/sovereign/drills", requireRole("admin"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 20;
    res.json(sovereignReadiness.getDrills(limit));
  }));

  app.get("/api/sovereign/drills/schedule", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(sovereignReadiness.getDrillSchedule());
  }));

  app.get("/api/sovereign/drills/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const drill = sovereignReadiness.getDrill(String(req.params.id));
    if (!drill) {
      return res.status(404).json({ error: "Drill not found" });
    }
    res.json(drill);
  }));

  app.post("/api/sovereign/drills", requireRole("admin"), asyncHandler(async (req, res) => {
    const { type, name, scheduledAt, sourceVendor, targetVendor } = req.body;
    const drill = sovereignReadiness.scheduleDrill({
      type,
      name,
      scheduledAt: new Date(scheduledAt),
      sourceVendor,
      targetVendor,
      scheduledBy: (req.session as any)?.user?.username || req.session?.userId || "system"
    });
    res.json(drill);
  }));

  app.post("/api/sovereign/drills/:id/execute", requireRole("admin"), asyncHandler(async (req, res) => {
    // NOT_ASSESSED (fabrication cleanup CF-1b 2026-07-02): executeDrill previously ran
    // simulateDrillExecution — Math.random pass/fail per check, Math.random transactionsProcessed/Lost,
    // latencies and RTO/RPO, then auto-generated a "Central Bank" drill report over those fake numbers.
    // No real cloud-exit DR migration harness is wired, so a drill cannot produce measured metrics.
    // Report NOT_ASSESSED instead of fabricating a drill result. (No client renders this endpoint.)
    const drill = sovereignReadiness.getDrill(String(req.params.id));
    if (!drill) {
      return res.status(404).json({ error: "Drill not found" });
    }
    res.json({
      status: "NOT_ASSESSED",
      drillId: drill.id,
      note: "Exit-drill execution is not wired to a real DR-migration harness — no drill metrics are measured or reported.",
    });
  }));

  app.get("/api/sovereign/reports", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    res.json(sovereignReadiness.getReports());
  }));

  app.get("/api/sovereign/reports/:id", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const report = sovereignReadiness.getReport(String(req.params.id));
    if (!report) {
      return res.status(404).json({ error: "Report not found" });
    }
    res.json(report);
  }));

  // Dead-Man's Switch (Exfiltration Detection)
  app.get("/api/sovereign/lockdown", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(sovereignReadiness.getLockdownStatus());
  }));

  app.get("/api/sovereign/exfiltration/events", requireRole("admin"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    res.json(sovereignReadiness.getExfiltrationEvents(limit));
  }));

  app.get("/api/sovereign/exfiltration/threshold", requireRole("admin"), asyncHandler(async (req, res) => {
    res.json(sovereignReadiness.getExfiltrationThreshold());
  }));

  app.post("/api/sovereign/exfiltration/detect", requireRole("admin"), asyncHandler(async (req, res) => {
    const { sourceIp, sourceUser, targetEndpoint, dataVolume, recordCount, dataTypes } = req.body;
    const event = sovereignReadiness.detectExfiltration({
      sourceIp,
      sourceUser,
      targetEndpoint,
      dataVolume,
      recordCount,
      dataTypes: dataTypes || []
    });
    res.json(event);
  }));

  app.post("/api/sovereign/lockdown/trigger", requireRole("admin"), asyncHandler(async (req, res) => {
    const status = sovereignReadiness.triggerLocalLockdown();
    res.json(status);
  }));

  app.post("/api/sovereign/lockdown/release", requireRole("admin"), asyncHandler(async (req, res) => {
    const username = (req.session as any)?.user?.username || req.session?.userId || "system";
    const status = sovereignReadiness.releaseLockdown(username);
    res.json(status);
  }));

  // Multi-Vendor Failover
  app.get("/api/sovereign/vendors", requireRole("admin"), asyncHandler(async (req, res) => {
    // Strip the static hardcoded healthScore/lastHealthCheck/replicationLag (fabrication cleanup, Tier-3
    // 2026-07-05): no live multi-cloud health monitor is wired, so vendor health is NOT measured. Serve
    // the vendors' static config (identity/capabilities/sla/cost) with health flagged NOT_ASSESSED —
    // matching the sibling /api/sovereign/vendors/health treatment (CF-1b).
    const vendors = sovereignReadiness.getVendors().map((v) => ({
      vendor: v.vendor, name: v.name, region: v.region, isActive: v.isActive, isPrimary: v.isPrimary,
      capabilities: v.capabilities, sla: v.sla, costPerHour: v.costPerHour,
      healthStatus: "NOT_ASSESSED",
      healthNote: "No live multi-cloud health monitor is wired — vendor health/replication-lag are not measured.",
    }));
    res.json(vendors);
  }));

  app.get("/api/sovereign/vendors/health", requireRole("admin"), asyncHandler(async (req, res) => {
    // NOT_ASSESSED (fabrication cleanup CF-1b): checkVendorHealth() previously overwrote each vendor's
    // healthScore (Math.random 85-100) and replicationLag (Math.random 0-5s) on every call — synthetic
    // multi-cloud health with no real monitor wired. Return the vendors' static config WITHOUT the
    // fabricated live-health fields, and flag health as not measured. (No client renders this endpoint.)
    const vendors = sovereignReadiness.getVendors().map((v) => ({
      vendor: v.vendor, name: v.name, region: v.region, isActive: v.isActive, isPrimary: v.isPrimary,
      capabilities: v.capabilities, sla: v.sla,
      healthStatus: "NOT_ASSESSED", healthNote: "No live multi-cloud health monitor is wired — vendor health/replication-lag are not measured.",
    }));
    res.json(vendors);
  }));

  app.get("/api/sovereign/failovers", requireRole("admin"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 20;
    res.json(sovereignReadiness.getFailoverEvents(limit));
  }));

  app.post("/api/sovereign/failover", requireRole("admin"), asyncHandler(async (req, res) => {
    // NOT_ASSESSED (fabrication cleanup CF-1b): executeVendorFailover previously fabricated the failover
    // duration (Math.random 10-40s) and transactionsAffected (Math.random 0-50) and recorded a "SUCCESS"
    // event — there is no real multi-vendor failover mechanism wired. Report NOT_ASSESSED rather than
    // fabricate a failover result. (No client renders this endpoint.)
    res.json({
      status: "NOT_ASSESSED",
      note: "Multi-vendor failover is not wired to a real mechanism — no failover is executed and no metrics are measured.",
    });
  }));

  // ==========================================
  // SUPPLY CHAIN SHIELD (Continuous Dependency Shield)
  // ==========================================

  // ==========================================
  // OBSERVER AGENT (Agentic Collision & Drift Monitoring)
  // ==========================================

  // ==========================================
  // ZERO-KNOWLEDGE THREAT EXCHANGE
  // ==========================================

  // ==========================================
  // DIGITAL TWIN WAR ROOM (3D Visualization)
  // ==========================================

  // ==========================================
  // GHOST CORE (Autonomous Operational Resilience)
  // ==========================================

  // ==========================================
  // VENDOR DNA SHIELD (Deep Supply Chain Integrity)
  // ==========================================

  // ==========================================
  // PERPETUAL KYC (pKYC - Real-Time Identity)
  // ==========================================

  // ==========================================
  // FIDO2/PASSKEY AUTHENTICATION (Zero Trust Identity)
  // ==========================================
  registerFIDO2Routes(app, requireAuth, requireRole);

  // ==========================================
  // JUST-IN-TIME (JIT) ACCESS MANAGEMENT
  // ==========================================
  registerJITAccessRoutes(app, requireAuth, requireRole);

  // ==========================================
  // MACHINE IDENTITY INVENTORY (Non-Human Identities)
  // ==========================================
  registerMachineIdentityRoutes(app, requireAuth, requireRole);

  // ==========================================
  // SERVICENOW INTEGRATION (Priority 2)
  // ==========================================
  registerServiceNowRoutes(app, requireRole, asyncHandler);

  // ==========================================
  // PAGERDUTY INTEGRATION (Priority 2)
  // ==========================================
  registerPagerDutyRoutes(app, requireRole, asyncHandler);

  // ==========================================
  // SCIM 2.0 USER PROVISIONING (Priority 2)
  // ==========================================
  registerScimRoutes(app);
  registerScimAdminRoutes(app, requireRole, asyncHandler);

  // ==========================================
  // DSAR WORKFLOW ENGINE (Priority 3)
  // ==========================================
  registerDsarRoutes(app, requireRole, requireAuth, asyncHandler);

  // ==========================================
  // WAVE 5: Persistence + New Features (~60 endpoints)
  // ==========================================
  registerWave5Routes(app, requireRole, requireAuth, asyncHandler);

  // ==========================================
  // FINAL WAVE: 13 Persistence Modules + Live Compliance (~55 endpoints)
  // ==========================================
  registerFinalRoutes(app, requireRole, requireAuth, asyncHandler);

  // ==========================================
  // THREAT FORECAST ENGINE (CVE + Dark Web + SPC + ATT&CK)
  // ==========================================
  registerThreatForecastRoutes(app, requireRole, requireAuth, asyncHandler);
  registerRbacRoutes(app, requireRole, requireAuth, asyncHandler, requireStepUp);

  // ==========================================
  // THREAT INTEL SYNC HISTORY (Priority 3)
  // ==========================================
  app.get("/api/threat-intel/sync-history", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const feedId = req.query.feedId as string | undefined;
    const limit = Number(req.query.limit) || 50;
    res.json(await getSyncHistory(feedId, limit));
  }));

  // ==========================================
  // SOVEREIGN FAILOVER MESH (Ghost Core + Cloud Core) — ROUTES REMOVED 2026-07-27
  // ==========================================
  // The edge<->cloud failover HTTP routes (/api/cloud/*, /api/edge/*, and the root /heartbeat + /sync
  // aliases) were REMOVED 2026-07-27. Reason: they implement a CENTRAL-CLOUD topology that production
  // (standalone-per-bank) does not have; their only consumer was the sovereign-edge UI (also removed);
  // and /api/cloud/sync + /sync were UNAUTHENTICATED accept-all forged-write endpoints. The engine code
  // (cloudCore.ts, heartbeatMonitor.ts) is RETAINED + shelve-labeled — chaosEngine (partition test)
  // still drives it via getHeartbeatMonitor(). If wired for a real topology, rebuild routes with real
  // auth + real PQC verify (not accept-all). See project memory 2026-07-27.

  // ============================================
  // PQC Engine Routes (Post-Quantum Cryptography)
  // ============================================
  
  // Get PQC status and algorithm info
  app.get("/api/pqc/status", requireAuth, asyncHandler(async (req, res) => {
    const pqcEngine = getPQCEngine();

    res.json({
      algorithm: pqcEngine.getAlgorithmInfo(),
      implementation: {
        keyEncapsulation: "real — NIST FIPS 203 ML-KEM-768, KAT-verified (@noble/post-quantum)",
        handshakeRoute: "demo/orchestration — KEM primitive is real, but this route does not return ciphertext to a terminal and uses a mock public key when none is supplied",
      },
      fingerprint: pqcEngine.getFingerprint(),
      sessions: pqcEngine.getSessionStatus()
    });
  }));
  
  // Perform PQC handshake with a terminal
  app.post("/api/pqc/handshake", requireAuth, asyncHandler(async (req, res) => {
    const { terminalId, terminalPublicKey } = req.body;
    
    if (!terminalId) {
      return res.status(400).json({ error: "terminalId required" });
    }
    
    // Use a mock public key if not provided (for demo)
    const pubKey = terminalPublicKey 
      ? Buffer.from(terminalPublicKey, 'hex')
      : Buffer.alloc(1184, 0); // ML-KEM-768 public key size
    
    const result = performPQCHandshake(terminalId, pubKey);
    
    res.json({
      sessionId: result.session.sessionId,
      terminalId: result.session.nodeId,
      establishedAt: result.session.establishedAt,
      expiresAt: result.session.expiresAt,
      edgePublicKeyFingerprint: getPQCEngine().getFingerprint()
    });
  }));
  
  // Get all active PQC sessions
  app.get("/api/pqc/sessions", requireAuth, asyncHandler(async (req, res) => {
    const pqcEngine = getPQCEngine();
    res.json(pqcEngine.getSessionStatus());
  }));
  
  // Clean up expired sessions
  app.post("/api/pqc/cleanup", requireRole("admin"), asyncHandler(async (req, res) => {
    const pqcEngine = getPQCEngine();
    const removed = pqcEngine.cleanupExpiredSessions();
    res.json({ removedSessions: removed });
  }));

  // ============================================
  // Chaos Engineering Routes (Production Hardening)
  // ============================================
  
  // Get chaos engine status
  app.get("/api/chaos/status", requireRole("admin"), asyncHandler(async (req, res) => {
    const chaos = getChaosEngine();
    res.json({
      activeExperiments: chaos.getActiveExperiments(),
      report: chaos.generateReport()
    });
  }));
  
  // Run network partition simulation
  app.post("/api/chaos/partition", requireRole("admin"), asyncHandler(async (req, res) => {
    const chaos = getChaosEngine();
    const { durationMs, intensity, autoRecover } = req.body;
    
    const result = await chaos.simulateNetworkPartition({
      durationMs: durationMs || 30000,
      intensity: intensity || 100,
      autoRecover: autoRecover !== false
    });
    
    res.json(result);
  }));
  
  // Run latency injection
  app.post("/api/chaos/latency", requireRole("admin"), asyncHandler(async (req, res) => {
    const chaos = getChaosEngine();
    const { latencyMs, durationMs } = req.body;
    
    const result = await chaos.simulateLatency(
      latencyMs || 200,
      durationMs || 10000
    );
    
    res.json(result);
  }));
  
  // Run clock drift simulation
  app.post("/api/chaos/clock-drift", requireRole("admin"), asyncHandler(async (req, res) => {
    const chaos = getChaosEngine();
    const { driftMs, durationMs } = req.body;
    
    const result = await chaos.simulateClockDrift(
      driftMs || 500,
      durationMs || 10000
    );
    
    res.json(result);
  }));
  
  // Get experiment history
  app.get("/api/chaos/history", requireRole("admin"), asyncHandler(async (req, res) => {
    const chaos = getChaosEngine();
    res.json(chaos.getExperimentHistory());
  }));
  
  // Run load test
  app.post("/api/chaos/load-test", requireRole("admin"), asyncHandler(async (req, res) => {
    const loadTester = getLoadTester();
    const { targetTPS, durationSeconds, rampUpSeconds } = req.body;
    
    const result = await loadTester.runLoadTest({
      targetTPS: targetTPS || 100,
      durationSeconds: durationSeconds || 30,
      rampUpSeconds: rampUpSeconds || 5,
      transactionTypes: ['payment', 'balance', 'transfer']
    });
    
    res.json(result);
  }));
  
  // Run security audit
  app.post("/api/chaos/security-audit", requireRole("admin"), asyncHandler(async (req, res) => {
    const auditor = getSecurityAuditor();
    const results = await auditor.runAudit();
    res.json({ results, passed: results.filter(r => r.passed).length, total: results.length });
  }));

  // ============================================
  // Gulu Mesh Network Routes (Multi-Node P2P)
  // ============================================
  
  // ============================================================
  // COMMERCIAL HARDENING ENDPOINTS (2026 Tier-1 Bank Standards)
  // ============================================================

  // --- HSM Enclave Endpoints ---
  
  // Initialize HSM enclave
  app.post("/api/hsm/initialize", requireAuth, requireRole("admin"), asyncHandler(async (req, res) => {
    const hsm = initializeGlobalHSM(req.body.config);
    const success = await hsm.initialize();
    res.json({ success, enclaveId: hsm.getConfig().enclaveId });
  }));

  // Get HSM status and metrics
  app.get("/api/hsm/status", requireAuth, asyncHandler(async (req, res) => {
    const hsm = getGlobalHSM();
    res.json({
      initialized: hsm.isInitialized(),
      config: hsm.getConfig(),
      metrics: hsm.getMetrics()
    });
  }));

  // Open HSM session
  app.post("/api/hsm/session/open", requireAuth, asyncHandler(async (req, res) => {
    const hsm = getGlobalHSM();
    const session = hsm.openSession(req.body.userType || 'USER');
    res.json({ session });
  }));

  // Authenticate HSM session
  app.post("/api/hsm/session/authenticate", requireAuth, asyncHandler(async (req, res) => {
    const hsm = getGlobalHSM();
    const { sessionId, pin } = req.body;
    const success = hsm.authenticateSession(sessionId, pin);
    res.json({ success });
  }));

  // Generate PQC key in HSM
  app.post("/api/hsm/key/generate", requireAuth, asyncHandler(async (req, res) => {
    const hsm = getGlobalHSM();
    const { sessionId, keyLabel } = req.body;
    const handle = hsm.generatePQCKey(sessionId, keyLabel || 'default');
    res.json({ keyHandle: handle });
  }));

  // Get HSM attestation
  app.get("/api/hsm/attestation", requireAuth, asyncHandler(async (req, res) => {
    const hsm = getGlobalHSM();
    const nonce = req.query.nonce as string || Date.now().toString();
    const attestation = hsm.getAttestation(nonce);
    res.json(attestation);
  }));

  // HSM tamper check
  app.get("/api/hsm/tamper-check", requireAuth, requireRole("admin"), asyncHandler(async (req, res) => {
    const hsm = getGlobalHSM();
    const result = hsm.tamperCheck();
    res.json(result);
  }));

  // --- SLA Monitor Endpoints ---

  // Get SLA metrics
  app.get("/api/sla/metrics", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    res.json(slaMonitor.getMetrics());
  }));

  // Get SLA thresholds
  app.get("/api/sla/thresholds", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    res.json(slaMonitor.getThresholds());
  }));

  // Get SLA violations
  app.get("/api/sla/violations", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    const active = req.query.active === 'true';
    res.json(active ? slaMonitor.getActiveViolations() : slaMonitor.getViolations());
  }));

  // Get resilience dashboard data
  app.get("/api/sla/dashboard", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    res.json(slaMonitor.getResilienceDashboard());
  }));

  // Generate SLA report
  app.get("/api/sla/report", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    const periodDays = parseInt(req.query.days as string) || 30;
    const periodEnd = new Date();
    const periodStart = new Date(Date.now() - periodDays * 24 * 60 * 60 * 1000);
    const report = slaMonitor.generateReport(periodStart, periodEnd);
    res.json(report);
  }));

  // Record WAN restore (for RTO tracking)
  app.post("/api/sla/wan-restore", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    slaMonitor.recordWANRestore();
    res.json({ success: true, message: 'WAN restore recorded - RTO timer started' });
  }));

  // Record Delta-Sync start
  app.post("/api/sla/delta-sync-start", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    slaMonitor.recordDeltaSyncStart();
    res.json({ 
      success: true, 
      rtoMs: slaMonitor.getMetrics().deltaSyncRTOMs,
      message: 'Delta-Sync initiated'
    });
  }));

  // --- Differential Privacy Endpoints ---

  // Get DP budget status
  app.get("/api/dp/budget", requireAuth, asyncHandler(async (req, res) => {
    const dpEngine = getGlobalDPEngine();
    res.json(dpEngine.getBudgetStatus());
  }));

  // Get DP configuration
  app.get("/api/dp/config", requireAuth, asyncHandler(async (req, res) => {
    const dpEngine = getGlobalDPEngine();
    res.json(dpEngine.getConfig());
  }));

  // Generate private aggregate for a region
  app.post("/api/dp/aggregate", requireAuth, asyncHandler(async (req, res) => {
    const dpEngine = getGlobalDPEngine();
    const { region, transactions } = req.body;
    const result = dpEngine.generatePrivateAggregate(region, transactions);
    if (!result) {
      res.status(400).json({ error: 'Insufficient data or budget exhausted' });
      return;
    }
    // Don't expose trueValue in response
    res.json({
      region: result.region,
      metric: result.metric,
      noisyValue: result.noisyValue,
      epsilon: result.epsilon,
      recordCount: result.recordCount,
      timestamp: result.timestamp,
      privacyGuarantee: result.privacyGuarantee
    });
  }));

  // Reset DP budget (admin only)
  app.post("/api/dp/reset-budget", requireAuth, requireRole("admin"), asyncHandler(async (req, res) => {
    const dpEngine = getGlobalDPEngine();
    dpEngine.resetBudget();
    res.json({ success: true, budget: dpEngine.getBudgetStatus() });
  }));

  // Get DP query history
  app.get("/api/dp/history", requireAuth, asyncHandler(async (req, res) => {
    const dpEngine = getGlobalDPEngine();
    res.json(dpEngine.getQueryHistory());
  }));

  // --- Resilience Dashboard (Combined endpoint) ---
  
  app.get("/api/resilience/dashboard", requireAuth, asyncHandler(async (req, res) => {
    const slaMonitor = getGlobalSLAMonitor();
    const dpEngine = getGlobalDPEngine();
    const hsm = getGlobalHSM();

    res.json({
      sla: slaMonitor.getResilienceDashboard(),
      privacy: dpEngine.getBudgetStatus(),
      hsm: {
        initialized: hsm.isInitialized(),
        metrics: hsm.getMetrics()
      },
      violations: slaMonitor.getActiveViolations().length
    });
  }));

  // Register Ghost API honeypot endpoints (must be before 404 handler)
  const { registerGhostEndpoints, ghostApiMiddleware } = await import("./lib/ghost-api");
  app.use(ghostApiMiddleware);
  registerGhostEndpoints(app);

  // ========================================
  // WEBHOOK DELIVERY ENGINE
  // ========================================
  
  app.post("/api/webhooks/deliver", requireRole("admin"), asyncHandler(async (req, res) => {
    const { webhookDelivery } = await import("./lib/webhook-delivery");
    const { eventType, payload } = req.body;
    const results = await webhookDelivery.processEvent(eventType, payload);
    res.json({ success: true, deliveries: results });
  }));

  app.get("/api/webhooks/delivery-stats", requireRole("admin"), asyncHandler(async (req, res) => {
    const { webhookDelivery } = await import("./lib/webhook-delivery");
    res.json(webhookDelivery.getDeliveryStats());
  }));

  // ========================================
  // NOTIFICATION SERVICE
  // ========================================

  app.post("/api/notifications/send", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { notificationService } = await import("./lib/notification-service");
    const { z } = await import("zod");
    // Validate against notification-service's REAL contract — the five channels its switch handles.
    // Closes the silent-no-op defect: an unknown channel previously logged a warning and delivered
    // NOTHING while the request still appeared to succeed (200), which the caller could not detect.
    // NB: no `priority` (that belonged to the shadowed notification-gateway handler, removed
    // 2026-07-24); `body` may be empty (the client requires channel/recipient/subject, not body).
    const schema = z.object({
      channel: z.enum(["email", "slack", "webhook", "in_app", "sms"]),
      recipient: z.string().min(1),
      subject: z.string().min(1),
      body: z.string(),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) {
      return res.status(400).json({ error: "Invalid notification payload", details: parsed.error.flatten() });
    }
    const { channel, recipient, subject, body } = parsed.data;
    const tenantId = (req as any).tenantId;
    const result = await notificationService.sendNotification(channel, recipient, subject, body, tenantId);
    res.json(result);
  }));

  app.get("/api/notifications/history", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { notificationService } = await import("./lib/notification-service");
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    const channel = req.query.channel as any;
    const history = await notificationService.getNotificationHistory(limit, channel);
    res.json(history);
  }));

  app.get("/api/notifications/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { notificationService } = await import("./lib/notification-service");
    const stats = await notificationService.getStats();
    res.json(stats);
  }));

  // ========================================
  // EXPORT SERVICE
  // ========================================

  app.post("/api/exports/create", requireAuth, asyncHandler(async (req, res) => {
    const { exportService } = await import("./lib/export-service");
    const { exportType, format, filters } = req.body;
    const tenantId = (req as any).tenantId;
    const result = await exportService.createExport(exportType, format, filters || {}, req.session.userId!, tenantId);
    res.json(result);
  }));

  app.get("/api/exports/jobs", requireAuth, asyncHandler(async (req, res) => {
    const { exportService } = await import("./lib/export-service");
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    const jobs = await exportService.getExportJobs(limit);
    res.json(jobs);
  }));

  app.get("/api/exports/download/:jobId", requireAuth, asyncHandler(async (req, res) => {
    const { exportService } = await import("./lib/export-service");
    const file = await exportService.getExportFile(String(req.params.jobId));
    if (!file) {
      return res.status(404).json({ error: "Export not found or not ready" });
    }
    res.setHeader("Content-Type", file.mimeType);
    res.setHeader("Content-Disposition", `attachment; filename="${file.fileName}"`);
    res.send(file.content);
  }));

  app.get("/api/exports/stats", requireAuth, asyncHandler(async (req, res) => {
    const { exportService } = await import("./lib/export-service");
    const stats = await exportService.getStats();
    res.json(stats);
  }));

  // ========================================
  // API KEY MANAGEMENT
  // ========================================

  // api_keys.permissions is a JSON-string text column (written via JSON.stringify in the
  // POST handler below). Parse it on READ so the API honours its declared string[] contract
  // and the client can render it — mirrors how the posture/scorecard routes parse their
  // JSON-text columns. Defensive: tolerates null / malformed without throwing.
  const parseApiKeyPerms = (raw: string | null | undefined): string[] => {
    if (!raw) return [];
    try { const v = JSON.parse(raw); return Array.isArray(v) ? v.map(String) : []; } catch { return []; }
  };
  app.get("/api/api-keys", requireRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = req.query.tenantId as string | undefined;
    const keys = await storage.getApiKeys(tenantId);
    res.json(keys.map(k => ({ ...k, keyHash: undefined, permissions: parseApiKeyPerms(k.permissions) })));
  }));

  app.post("/api/api-keys", requireRole("admin"), asyncHandler(async (req, res) => {
    const { generateApiKey, hashApiKey } = await import("./lib/api-key-auth");
    // FU-053 Deliverable 7 (TII-06): tenantId removed from body destructure.
    // Caller-supplied body.tenantId is a Track II sink (T002.5 audit finding).
    // Source of truth is req.tenantId (set by tenantMiddleware from the
    // authenticated session's DB-derived tenant). The "default" fallback covers
    // the API-key-creates-API-key edge case where req.tenantId may be absent.
    const { name, permissions, rateLimit, expiresAt } = req.body;
    const { key, keyHash, keyPrefix } = generateApiKey();
    // REVOCATION-RACE CLASS FIX (Shelf-Sweep AS/PLATFORM/2026/003, architect Rule-9
    // reviewed): the request-tx `db` proxy commits at res.finish — AFTER the response
    // is flushed — so a key returned here was NOT durably committed when the caller
    // received it, racing an immediate validate. api_keys is an RLS (T) table managed
    // cross-tenant by admins; the D-B=B-3 directive (rls-init.ts) routes api_keys
    // admin DML through withBypassRls, which COMMITs before returning. Bypass register
    // entry: APIKEY-ADMIN (db.ts register). Mirrors LOGIN-UTR.
    const apiKey = await withBypassRls(async (bypassDb) => {
      const [row] = await bypassDb
        .insert(apiKeys)
        .values({
          name,
          keyHash,
          keyPrefix,
          tenantId: (req as any).tenantId || "default",
          permissions: JSON.stringify(permissions || ["read"]),
          rateLimit: rateLimit || 1000,
          isActive: true,
          expiresAt: expiresAt ? new Date(expiresAt) : null,
          createdBy: req.session.userId!,
        })
        .returning();
      return row;
    });
    res.json({ ...apiKey, permissions: parseApiKeyPerms(apiKey.permissions), plainKey: key, keyHash: undefined });
  }));

  app.delete("/api/api-keys/:id", requireRole("admin"), requireStepUp, asyncHandler(async (req, res) => {
    // REVOCATION-RACE CLASS FIX (see POST above): deactivation must durably COMMIT
    // before the 200 — otherwise the revoked key keeps validating until res.finish
    // (fail-OPEN on an authentication surface). withBypassRls commits before return
    // and is the D-B=B-3-correct primitive for cross-tenant api_keys admin DML.
    await withBypassRls(async (bypassDb) => {
      await bypassDb
        .update(apiKeys)
        .set({ isActive: false })
        .where(eq(apiKeys.id, String(req.params.id)));
    });
    res.json({ success: true });
  }));

  // ========================================
  // TENANT MANAGEMENT
  // ========================================

  app.get("/api/tenants", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const tenants = await storage.getTenants();
    res.json(tenants);
  }));

  app.post("/api/tenants", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const tenant = await storage.createTenant(req.body);
    res.json(tenant);
  }));

  app.get("/api/tenants/:id", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const tenant = await storage.getTenantById(String(req.params.id));
    if (!tenant) return res.status(404).json({ error: "Tenant not found" });
    res.json(tenant);
  }));

  app.patch("/api/tenants/:id", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const tenant = await storage.updateTenant(String(req.params.id), req.body);
    if (!tenant) return res.status(404).json({ error: "Tenant not found" });
    res.json(tenant);
  }));

  // ========================================
  // SSO CONFIGURATION
  // ========================================

  app.get("/api/sso/configs", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ssoService } = await import("./lib/sso-service");
    const tenantId = req.query.tenantId as string | undefined;
    res.json(await ssoService.getSsoConfigs(tenantId));
  }));

  app.post("/api/sso/configs", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ssoService } = await import("./lib/sso-service");
    res.json(await ssoService.createSsoConfig(req.body));
  }));

  app.patch("/api/sso/configs/:id", requireRole("admin"), requireStepUp, asyncHandler(async (req, res) => {
    const { ssoService } = await import("./lib/sso-service");
    res.json(await ssoService.updateSsoConfig(String(req.params.id), req.body));
  }));

  app.get("/api/sso/providers", requireAuth, asyncHandler(async (req, res) => {
    const { ssoService } = await import("./lib/sso-service");
    res.json(ssoService.getSupportedProviders());
  }));

  // Public (pre-auth): the login page needs to know whether SSO is configured so it can render an
  // honest "Sign in with SSO" button vs an honest "not configured" state — never a button that
  // fails. Returns id + provider ONLY (the id is already public via /api/sso/login/:id); never the
  // issuer, client id, or secret. RLS-scoped table read via bypass (no tenant context pre-auth).
  app.get("/api/sso/available", asyncHandler(async (_req, res) => {
    const configs = await withBypassRls((bypassDb) =>
      bypassDb
        .select({ id: ssoConfigs.id, provider: ssoConfigs.provider })
        .from(ssoConfigs)
        .where(eq(ssoConfigs.isActive, true)),
    );
    res.json({ configs });
  }));

  app.post("/api/sso/login/:configId", asyncHandler(async (req, res) => {
    const { ssoService } = await import("./lib/sso-service");
    const result = await ssoService.initiateLogin(String(req.params.configId));
    res.json(result);
  }));

  // SSO callback — the IdP redirects the BROWSER here (GET ?code&state). This is an auth path:
  // it establishes a session via the SAME establishAuthenticatedSession() the password path uses
  // (session regeneration, fail-closed tenant binding, concurrent-session cap, audit LOGIN), so
  // an SSO session is byte-for-byte identical to a password session and cannot drift.
  //
  // Identity binding — trust-on-first-use → sub-pin (OIDC Core §5.7: sub+iss is the only stable
  // key; preferred_username is barred as a key and used ONCE, for first-login association):
  //   • verified sub matches users.oidc_subject                 -> authenticate (already bound)
  //   • no sub match; preferred_username matches a user whose
  //     oidc_subject is NULL                                    -> bind the sub once, authenticate
  //   • username matches but oidc_subject is a DIFFERENT sub     -> REJECT (reassigned username does
  //                                                                 not inherit the prior account)
  //   • unknown username / no username claim                     -> REJECT (SCIM stays the authority)
  async function resolveSsoIdentity(
    identity: { sub: string; issuer: string; preferredUsername?: string },
  ): Promise<
    | { outcome: "ok"; user: typeof users.$inferSelect; bound: boolean }
    | { outcome: "reject"; reason: string }
  > {
    // users is not RLS-scoped (no tenant_id); the app-pool db (no GUC) reads it pre-auth exactly
    // as storage.getUserByUsername does at password-login time.
    const [bySub] = await db.select().from(users).where(eq(users.oidcSubject, identity.sub)).limit(1);
    if (bySub) return { outcome: "ok", user: bySub, bound: false };

    if (!identity.preferredUsername) {
      return { outcome: "reject", reason: "no preferred_username claim to associate a local account" };
    }
    const [byName] = await db.select().from(users).where(eq(users.username, identity.preferredUsername)).limit(1);
    if (!byName) {
      return { outcome: "reject", reason: `no local user provisioned for '${identity.preferredUsername}' — provision via SCIM (reject-unknown)` };
    }
    if (byName.oidcSubject && byName.oidcSubject !== identity.sub) {
      return { outcome: "reject", reason: `username '${identity.preferredUsername}' is already bound to a different identity — refusing to inherit (possible reassignment)` };
    }
    if (byName.oidcSubject === identity.sub) {
      return { outcome: "ok", user: byName, bound: false };
    }
    // First login: bind the sub atomically, only while still NULL (guards a concurrent bind).
    const bound = await db
      .update(users)
      .set({ oidcSubject: identity.sub })
      .where(and(eq(users.id, byName.id), isNull(users.oidcSubject)))
      .returning({ id: users.id });
    if (bound.length === 0) {
      const [reread] = await db.select().from(users).where(eq(users.id, byName.id)).limit(1);
      if (!reread || reread.oidcSubject !== identity.sub) {
        return { outcome: "reject", reason: "concurrent binding to a different identity — refusing" };
      }
      return { outcome: "ok", user: reread, bound: false };
    }
    return { outcome: "ok", user: byName, bound: true };
  }

  app.get("/api/sso/callback/:configId", asyncHandler(async (req, res) => {
    const traceId = (req as any).traceId;
    const clientIp = getClientIp(req);
    const userAgent = String(req.headers["user-agent"] ?? "unknown");
    const configId = String(req.params.configId);
    const { ssoService } = await import("./lib/sso-service");
    const { recordLogin } = await import("./lib/login-anomaly");

    // 1) Exchange + VERIFY the IdP tokens. Any failure (bad signature, wrong iss/aud/nonce,
    //    expired, replayed/unknown state) throws — no session is established.
    let identity: { sub: string; issuer: string; preferredUsername?: string };
    try {
      const currentUrl = new URL(req.originalUrl, `${req.protocol}://${req.get("host")}`);
      identity = await ssoService.handleCallback(configId, currentUrl);
    } catch (err) {
      authLogger.warn("SSO callback verification failed", { traceId, metadata: { configId, error: String((err as Error)?.message ?? err) } });
      await storage.createAuditLog({ action: "SSO_LOGIN_REJECTED", resource: "Authentication System", details: `SSO token verification failed: ${String((err as Error)?.message ?? err)}`, ipAddress: clientIp });
      return res.redirect("/?sso_error=verification_failed");
    }

    // 2) Resolve the local user (trust-on-first-use -> sub-pin). Reject-unknown; SCIM provisions.
    const resolved = await resolveSsoIdentity(identity);
    if (resolved.outcome === "reject") {
      authLogger.warn("SSO login rejected", { traceId, metadata: { configId, issuer: identity.issuer, reason: resolved.reason } });
      await storage.createAuditLog({ action: "SSO_LOGIN_REJECTED", resource: "Authentication System", details: `SSO login rejected (${resolved.reason}); issuer=${identity.issuer}`, ipAddress: clientIp });
      return res.redirect("/?sso_error=access_denied");
    }
    const user = resolved.user;

    // 3) First-login binding is its own auditable event — an external identity permanently
    //    associated with a local account, distinct from LOGIN.
    if (resolved.bound) {
      await storage.createAuditLog({ userId: user.id, action: "SSO_IDENTITY_BOUND", resource: "Authentication System", details: `SSO identity bound to user ${user.username} (issuer=${identity.issuer}) on first login`, ipAddress: clientIp });
      authLogger.info("SSO identity bound", { traceId, metadata: { userId: user.id, issuer: identity.issuer } });
    }

    // 4) Feed the behavioural baseline explicitly — a login path that skips recordLogin
    //    half-blinds the detector. (Consolidation into the helper is a documented follow-up.)
    await recordLogin(user.id, user.username, clientIp, userAgent, true);

    // 5) Establish the session via the SAME tail as password login (regenerate, fail-closed
    //    tenant binding, concurrent-session cap, audit LOGIN, session-manager). A non-ok result
    //    is a 403-equivalent (no tenant assignment) — no session, redirect with the reason.
    const established = await establishAuthenticatedSession(req, { id: user.id, role: user.role, username: user.username }, clientIp, traceId);
    if (!established.ok) {
      return res.redirect("/?sso_error=no_tenant");
    }
    return res.redirect("/");
  }));

  app.get("/api/sso/status", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ssoService } = await import("./lib/sso-service");
    res.json(await ssoService.getStatus());
  }));

  // ========================================
  // ENCRYPTION SERVICE
  // ========================================

  app.get("/api/encryption/status", requireRole("admin"), asyncHandler(async (_req, res) => {
    const { getEncryptionStats } = await import("./lib/field-encryption");
    res.json(getEncryptionStats());
  }));

  app.post("/api/encryption/encrypt", requireRole("admin"), asyncHandler(async (req, res) => {
    const { z } = await import("zod");
    const schema = z.object({ plaintext: z.string().min(1) });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload" });
    const { encryptField } = await import("./lib/field-encryption");
    res.json({ encrypted: encryptField(parsed.data.plaintext) });
  }));

  app.post("/api/encryption/decrypt", requireRole("admin"), asyncHandler(async (req, res) => {
    const { z } = await import("zod");
    const schema = z.object({ ciphertext: z.string().min(1) });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload" });
    const { decryptField } = await import("./lib/field-encryption");
    try {
      res.json({ decrypted: decryptField(parsed.data.ciphertext) });
    } catch {
      res.status(400).json({ error: "Decryption failed - invalid ciphertext" });
    }
  }));

  // ========================================
  // BACKUP & DISASTER RECOVERY
  // ========================================

  app.get("/api/backups", requireRole("admin"), asyncHandler(async (req, res) => {
    const { backupService } = await import("./lib/backup-service");
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    const backups = await backupService.listBackups(limit);
    res.json(backups);
  }));

  app.post("/api/backups/create", requireRole("admin"), asyncHandler(async (req, res) => {
    const { backupService } = await import("./lib/backup-service");
    const { type } = req.body;
    const result = await backupService.createBackup(type || "full", req.session.userId!);
    res.json(result);
  }));

  app.post("/api/backups/:id/verify", requireRole("admin"), asyncHandler(async (req, res) => {
    const { backupService } = await import("./lib/backup-service");
    const result = await backupService.verifyBackup(String(req.params.id));
    res.json(result);
  }));

  app.get("/api/backups/recovery-plan", requireRole("admin"), asyncHandler(async (req, res) => {
    const { backupService } = await import("./lib/backup-service");
    res.json(await backupService.getRecoveryPlan());
  }));

  app.get("/api/backups/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    const { backupService } = await import("./lib/backup-service");
    res.json(await backupService.getStats());
  }));

  // Retention status — non-destructive view of the per-record retention policy:
  // which completed backups are still live vs past their retentionDays window,
  // next expiry date, and what a prune would reclaim.
  app.get("/api/backups/retention", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const { backupService } = await import("./lib/backup-service");
    res.json(await backupService.getRetentionStatus());
  }));

  // Enforce retention now — deletes the .sql file for completed backups past their
  // retentionDays and marks the record 'expired' (record kept for audit). Admin-only,
  // destructive; the within-retention set is never touched.
  app.post("/api/backups/prune", requireRole("admin"), requireStepUp, asyncHandler(async (req, res) => {
    const { backupService } = await import("./lib/backup-service");
    res.json(await backupService.pruneExpiredBackups(req.session.userId ?? null));
  }));

  // ========================================
  // AI THREAT SCORING
  // ========================================
  // REMOVED (2026-06-30, zero-drop fabrication excision): the inline
  // `POST /api/ai-scoring/analyze` + `GET /api/ai-scoring/scores` pair.
  // `analyze` fabricated `confidence` + four factors (temporalAnomaly /
  // velocityDeviation / geoBehavioral / peerGroupDeviation) via Math.random,
  // stamped a fake `modelVersion: "aegis-sentinel-v2.1"`, and persisted the
  // synthetic rows via `storage.createAiThreatScore`; `scores` read those
  // fabricated rows back. This was a fake "AI model" presented as real output.
  // The REAL AI-threat path is the Anthropic-backed engine in
  // `server/lib/ai-threat-scoring.ts`, surfaced via the `/api/ai-scoring/stats`
  // `/history` `/transactions` `/threat` `/transaction` routes below — KEPT.
  // The `ai_threat_scores` table + `storage.createAiThreatScore` are KEPT
  // (zero schema drop); only the fabricating route + its read route are gone.

  // ========================================
  // GHOST CORE PERSISTENCE
  // ========================================

  app.get("/api/ghost-core/events", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    const tenantId = req.query.tenantId as string | undefined;
    const events = await storage.getGhostCoreEvents(limit, tenantId);
    res.json(events);
  }));

  app.post("/api/ghost-core/events", requireRole("admin"), asyncHandler(async (req, res) => {
    const event = await storage.createGhostCoreEvent(req.body);
    res.json(event);
  }));

  // ========================================
  // SOAR EXECUTION PERSISTENCE
  // ========================================
  // GET /api/soar/executions/history moved UP to register before /executions/:id (2026-07-26,
  // param-shadow fix) — it was shadowed here by the earlier :id route. Handler unchanged.

  // ========================================
  // OBSERVER LOG PERSISTENCE
  // ========================================

  app.get("/api/observer/logs/history", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const limit = req.query.limit ? parseInt(req.query.limit as string) : 50;
    const logs = await storage.getObserverLogs(limit);
    res.json(logs);
  }));

  // ========================================
  // I18N TRANSLATIONS (tenant overrides)
  // ========================================

  app.get("/api/i18n/overrides/:locale", asyncHandler(async (req, res) => {
    const locale = String(req.params.locale);
    const tenantId = req.query.tenantId as string || "default";
    // Pre-auth (login-page localization): resolve cross-tenant via the bypass path, else the
    // 'default'-GUC scoped read silently hides a real tenant's overrides (false-green). See storage.
    const overrides = await storage.getI18nOverridesUnscoped(locale, tenantId);
    res.json(overrides);
  }));

  app.post("/api/i18n/overrides", requireRole("admin"), asyncHandler(async (req, res) => {
    const override = await storage.createI18nOverride(req.body);
    res.json(override);
  }));

  // ============ DATA EXPORT ENDPOINTS ============

  app.get("/api/export/audit-logs", requireAuth, requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const { exportAuditLogsCsv } = await import("./lib/data-export");
    const csv = await exportAuditLogsCsv();
    const timestamp = new Date().toISOString().split("T")[0];
    res.setHeader("Content-Type", "text/csv");
    res.setHeader("Content-Disposition", `attachment; filename="aegis_audit_logs_${timestamp}.csv"`);
    await storage.createAuditLog({
      userId: req.session.userId!,
      action: "REPORT_EXPORTED",
      resource: "Audit Logs CSV Export",
      details: `Exported audit logs to CSV`,
      ipAddress: getClientIp(req),
    });
    res.send(csv);
  }));

  app.get("/api/export/threats", requireAuth, requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { exportThreatsCsv } = await import("./lib/data-export");
    const csv = await exportThreatsCsv();
    const timestamp = new Date().toISOString().split("T")[0];
    res.setHeader("Content-Type", "text/csv");
    res.setHeader("Content-Disposition", `attachment; filename="aegis_threats_${timestamp}.csv"`);
    await storage.createAuditLog({
      userId: req.session.userId!,
      action: "REPORT_EXPORTED",
      resource: "Threats CSV Export",
      details: `Exported threat events to CSV`,
      ipAddress: getClientIp(req),
    });
    res.send(csv);
  }));

  app.get("/api/export/metrics", requireAuth, asyncHandler(async (req, res) => {
    const { exportSystemMetricsCsv } = await import("./lib/data-export");
    const csv = await exportSystemMetricsCsv();
    const timestamp = new Date().toISOString().split("T")[0];
    res.setHeader("Content-Type", "text/csv");
    res.setHeader("Content-Disposition", `attachment; filename="aegis_metrics_${timestamp}.csv"`);
    res.send(csv);
  }));

  // ============ OPENAPI DOCUMENTATION ============

  app.get("/api/docs", asyncHandler(async (req, res) => {
    const { getOpenAPISpec } = await import("./lib/openapi-spec");
    res.json(getOpenAPISpec());
  }));

  // ============ ACTIVE SESSION MANAGEMENT ============

  app.get("/api/sessions/active", requireRole("admin"), asyncHandler(async (req, res) => {
    const { sessionManager } = await import("./lib/session-manager");
    const sessions = await sessionManager.getAllSessions();
    res.json(sessions);
  }));

  app.get("/api/sessions/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    const { sessionManager } = await import("./lib/session-manager");
    const stats = await sessionManager.getSessionStats();
    res.json(stats);
  }));

  app.post("/api/sessions/:id/revoke", requireRole("admin"), asyncHandler(async (req, res) => {
    const { sessionManager } = await import("./lib/session-manager");
    const userId = (req as any).session?.userId;
    const revoked = await sessionManager.revokeSession(String(req.params.id), userId);
    if (!revoked) return res.status(404).json({ error: "Session not found" });
    await storage.createAuditLog({
      userId,
      action: "SESSION_REVOKED",
      resource: `Session ${req.params.id}`,
      details: `Admin revoked session ${req.params.id}`,
      ipAddress: getClientIp(req),
    });
    res.json({ success: true, session: revoked });
  }));

  app.post("/api/sessions/revoke-all/:userId", requireRole("admin"), asyncHandler(async (req, res) => {
    const { sessionManager } = await import("./lib/session-manager");
    const adminId = (req as any).session?.userId;
    await sessionManager.revokeAllUserSessions(String(req.params.userId), adminId);
    await storage.createAuditLog({
      userId: adminId,
      action: "ALL_SESSIONS_REVOKED",
      resource: `User ${req.params.userId}`,
      details: `Admin revoked all sessions for user ${req.params.userId}`,
      ipAddress: getClientIp(req),
    });
    res.json({ success: true });
  }));

  // ============ IP ALLOWLIST / BLOCKLIST ============

  app.get("/api/ip-policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ipPolicyManager } = await import("./lib/ip-policy-manager");
    const tenantId = (req as any).session?.tenantId || "default";
    const policies = await ipPolicyManager.getPolicies(tenantId);
    res.json(policies);
  }));

  app.get("/api/ip-policies/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ipPolicyManager } = await import("./lib/ip-policy-manager");
    const stats = await ipPolicyManager.getStats();
    res.json(stats);
  }));

  app.post("/api/ip-policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { policyType, ipAddress, cidrRange, description, expiresAt } = req.body;
    if (!policyType || !ipAddress) return res.status(400).json({ error: "policyType and ipAddress required" });
    const { ipPolicyManager } = await import("./lib/ip-policy-manager");
    const userId = (req as any).session?.userId;
    const policy = await ipPolicyManager.createPolicy({
      policyType, ipAddress, cidrRange, description, createdBy: userId,
      expiresAt: expiresAt ? new Date(expiresAt) : undefined,
    });
    await storage.createAuditLog({
      userId,
      action: "IP_POLICY_CREATED",
      resource: `IP Policy ${policy.id}`,
      details: `Created ${policyType} policy for ${cidrRange || ipAddress}`,
      ipAddress: getClientIp(req),
    });
    res.json(policy);
  }));

  app.patch("/api/ip-policies/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ipPolicyManager } = await import("./lib/ip-policy-manager");
    const updated = await ipPolicyManager.updatePolicy(String(req.params.id), req.body);
    if (!updated) return res.status(404).json({ error: "Policy not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "IP_POLICY_UPDATED",
      resource: `IP Policy ${req.params.id}`,
      details: `Updated IP policy: ${JSON.stringify(req.body)}`,
      ipAddress: getClientIp(req),
    });
    res.json(updated);
  }));

  app.delete("/api/ip-policies/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ipPolicyManager } = await import("./lib/ip-policy-manager");
    await ipPolicyManager.deletePolicy(String(req.params.id));
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "IP_POLICY_DELETED",
      resource: `IP Policy ${req.params.id}`,
      details: `Deleted IP policy ${req.params.id}`,
      ipAddress: getClientIp(req),
    });
    res.json({ success: true });
  }));

  app.post("/api/ip-policies/check", requireRole("admin"), asyncHandler(async (req, res) => {
    const { ip } = req.body;
    if (!ip) return res.status(400).json({ error: "IP address required" });
    const { ipPolicyManager } = await import("./lib/ip-policy-manager");
    const tenantId = (req as any).session?.tenantId || "default";
    const result = await ipPolicyManager.checkIp(ip, tenantId);
    res.json(result);
  }));

  // ============ API USAGE ANALYTICS ============

  app.get("/api/analytics/usage", requireRole("admin"), asyncHandler(async (req, res) => {
    const { apiAnalytics } = await import("./lib/api-analytics");
    const hours = parseInt(req.query.hours?.toString() || "24");
    const stats = await apiAnalytics.getUsageStats(hours);
    res.json(stats);
  }));

  app.get("/api/analytics/errors", requireRole("admin"), asyncHandler(async (req, res) => {
    const { apiAnalytics } = await import("./lib/api-analytics");
    const errors = await apiAnalytics.getRecentErrors();
    res.json(errors);
  }));

  // ============ COMPLIANCE REPORT GENERATOR ============

  app.get("/api/compliance-reports", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { complianceReporter } = await import("./lib/compliance-reporter");
    const reports = await complianceReporter.getReports(tenantId);
    res.json(reports);
  }));

  app.get("/api/compliance-reports/overview", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { complianceReporter } = await import("./lib/compliance-reporter");
    const overview = await complianceReporter.getComplianceOverview(tenantId);
    res.json(overview);
  }));

  app.post("/api/compliance-reports/generate", requireRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { reportType } = req.body;
    if (!reportType) return res.status(400).json({ error: "reportType required (PDPO, PCI_DSS, SOC2)" });
    const { complianceReporter } = await import("./lib/compliance-reporter");
    const userId = (req as any).session?.userId;
    const result = await complianceReporter.generateReport(reportType, userId, tenantId);
    await storage.createAuditLog({
      userId,
      action: "COMPLIANCE_REPORT_GENERATED",
      resource: `Compliance Report ${result.report.id}`,
      details: `Generated ${reportType} compliance report`,
      ipAddress: getClientIp(req),
    });
    res.json(result);
  }));

  app.get("/api/compliance-reports/:id", requireRole("admin", "auditor"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { complianceReporter } = await import("./lib/compliance-reporter");
    const report = await complianceReporter.getReport(tenantId, String(req.params.id));
    if (!report) return res.status(404).json({ error: "Report not found" });
    res.json(report);
  }));

  // ============ PLATFORM HEALTH & SLO MONITORING ============

  app.get("/api/platform/health", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { platformHealth } = await import("./lib/platform-health");
    const health = await platformHealth.runHealthChecks();
    res.json(health);
  }));

  app.get("/api/platform/summary", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { platformHealth } = await import("./lib/platform-health");
    const summary = await platformHealth.getPlatformSummary();
    res.json(summary);
  }));

  app.get("/api/platform/slo", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { platformHealth } = await import("./lib/platform-health");
    const slos = await platformHealth.getSLOTargets();
    res.json(slos);
  }));

  app.post("/api/platform/slo/init", requirePlatformRole("admin"), asyncHandler(async (req, res) => {
    const { platformHealth } = await import("./lib/platform-health");
    const slos = await platformHealth.initSLODefaults();
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "SLO_TARGETS_INITIALIZED",
      resource: "Platform SLO",
      details: `Initialized ${slos.length} SLO targets`,
      ipAddress: getClientIp(req),
    });
    res.json(slos);
  }));

  app.get("/api/platform/health/history", requirePlatformRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { platformHealth } = await import("./lib/platform-health");
    const history = await platformHealth.getHealthHistory();
    res.json(history);
  }));

  // ============ INCIDENT SLA TRACKING ============

  app.get("/api/incidents", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { incidentSlaTracker } = await import("./lib/incident-sla");
    const incidents = await incidentSlaTracker.getIncidents();
    res.json(incidents);
  }));

  app.get("/api/incidents/metrics", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { incidentSlaTracker } = await import("./lib/incident-sla");
    const metrics = await incidentSlaTracker.getMetrics();
    res.json(metrics);
  }));

  app.post("/api/incidents", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { severity, title, description, assignedTo } = req.body;
    if (!severity || !title) return res.status(400).json({ error: "severity and title required" });
    // Pass the request tenant so the inserted row's tenant_id matches current_tenant_id() — without
    // it the row is tenant_id=null and RLS (incident_slas_tenant_isolation WITH CHECK) rejects the
    // insert (pre-existing create-path bug surfaced by the incident-page audit's both-directions verify).
    const tenantId = (req as any).tenantId as string | undefined;
    const { incidentSlaTracker } = await import("./lib/incident-sla");
    const incident = await incidentSlaTracker.createIncident({ severity, title, description, assignedTo, tenantId });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "INCIDENT_CREATED",
      resource: `Incident ${incident.incidentId}`,
      details: `Created ${severity} incident: ${title}`,
      ipAddress: getClientIp(req),
    });
    res.json(incident);
  }));

  app.post("/api/incidents/:id/acknowledge", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { incidentSlaTracker } = await import("./lib/incident-sla");
    const incident = await incidentSlaTracker.acknowledgeIncident(String(req.params.id));
    if (!incident) return res.status(404).json({ error: "Incident not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "INCIDENT_ACKNOWLEDGED",
      resource: `Incident ${incident.incidentId}`,
      details: `Acknowledged ${incident.severity} incident: ${incident.title}`,
      ipAddress: getClientIp(req),
    });
    res.json(incident);
  }));

  app.patch("/api/incidents/:id/status", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { status, rootCause, resolution } = req.body;
    if (!status) return res.status(400).json({ error: "status required" });
    const { incidentSlaTracker } = await import("./lib/incident-sla");
    const incident = await incidentSlaTracker.updateStatus(String(req.params.id), status, { rootCause, resolution });
    if (!incident) return res.status(404).json({ error: "Incident not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "INCIDENT_STATUS_UPDATED",
      resource: `Incident ${incident.incidentId}`,
      details: `Status changed to ${status}`,
      ipAddress: getClientIp(req),
    });
    res.json(incident);
  }));

  app.post("/api/incidents/:id/escalate", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { incidentSlaTracker } = await import("./lib/incident-sla");
    const incident = await incidentSlaTracker.escalateIncident(String(req.params.id));
    if (!incident) return res.status(404).json({ error: "Incident not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "INCIDENT_ESCALATED",
      resource: `Incident ${incident.incidentId}`,
      details: `Escalated to level ${incident.escalationLevel}`,
      ipAddress: getClientIp(req),
    });
    res.json(incident);
  }));

  // NOTE: POST /api/incidents/seed removed (2026-07-01, incident-page audit) — it was a
  // one-click demo-injection seam that inserted hardcoded fabricated incidents into the REAL
  // incident_slas table (rendering as real, no demo label) on a trusted board/SLA surface.
  // The real operator path (POST /api/incidents create + ack/escalate) is untouched.

  // ============ RATE LIMITING & QUOTA GOVERNANCE ============

  app.get("/api/rate-limits/policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
    const policies = await rateLimitGovernance.getPolicies();
    res.json(policies);
  }));

  app.get("/api/rate-limits/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
    const stats = await rateLimitGovernance.getStats();
    res.json(stats);
  }));

  app.get("/api/rate-limits/events", requireRole("admin"), asyncHandler(async (req, res) => {
    const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
    const events = await rateLimitGovernance.getEvents();
    res.json(events);
  }));

  app.post("/api/rate-limits/policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
    // tenant_id from request ctx (RLS), never trust the client body for it.
    const policy = await rateLimitGovernance.createPolicy({ ...req.body, tenantId: (req as any).tenantId });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "RATE_LIMIT_POLICY_CREATED",
      resource: `Rate Limit Policy ${policy.id}`,
      details: `Created rate limit policy: ${policy.name}`,
      ipAddress: getClientIp(req),
    });
    res.json(policy);
  }));

  app.patch("/api/rate-limits/policies/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
    const updated = await rateLimitGovernance.updatePolicy(String(req.params.id), req.body);
    if (!updated) return res.status(404).json({ error: "Policy not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "RATE_LIMIT_POLICY_UPDATED",
      resource: `Rate Limit Policy ${req.params.id}`,
      details: `Updated rate limit policy`,
      ipAddress: getClientIp(req),
    });
    res.json(updated);
  }));

  app.delete("/api/rate-limits/policies/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
    await rateLimitGovernance.deletePolicy(String(req.params.id));
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "RATE_LIMIT_POLICY_DELETED",
      resource: `Rate Limit Policy ${req.params.id}`,
      details: `Deleted rate limit policy`,
      ipAddress: getClientIp(req),
    });
    res.json({ success: true });
  }));

  app.post("/api/rate-limits/seed", requireRole("admin"), asyncHandler(async (req, res) => {
    const { rateLimitGovernance } = await import("./lib/rate-limit-governance");
    await rateLimitGovernance.seedDefaults((req as any).tenantId);
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "RATE_LIMIT_DEFAULTS_SEEDED",
      resource: "Rate Limit Policies",
      details: "Seeded default rate limit policies",
      ipAddress: getClientIp(req),
    });
    res.json({ success: true });
  }));

  // ============ DLP & PII SCANNER ============

  app.get("/api/dlp/findings", requireRole("admin"), asyncHandler(async (req, res) => {
    const { dlpScanner } = await import("./lib/dlp-scanner");
    const status = req.query.status?.toString();
    const findings = await dlpScanner.getFindings(status);
    res.json(findings);
  }));

  app.get("/api/dlp/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    const { dlpScanner } = await import("./lib/dlp-scanner");
    const stats = await dlpScanner.getFindingStats();
    res.json(stats);
  }));

  app.get("/api/dlp/policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { dlpScanner } = await import("./lib/dlp-scanner");
    const policies = await dlpScanner.getPolicies();
    res.json(policies);
  }));

  app.post("/api/dlp/policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { dlpScanner } = await import("./lib/dlp-scanner");
    const policy = await dlpScanner.createPolicy(req.body);
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "DLP_POLICY_CREATED",
      resource: `DLP Policy ${policy.id}`,
      details: `Created DLP policy: ${policy.name}`,
      ipAddress: getClientIp(req),
    });
    res.json(policy);
  }));

  app.post("/api/dlp/scan", requireRole("admin"), asyncHandler(async (req, res) => {
    const { content, source } = req.body;
    if (!content || !source) return res.status(400).json({ error: "content and source required" });
    const { dlpScanner } = await import("./lib/dlp-scanner");
    const results = await dlpScanner.scanContent(content, source, req.body.endpoint);
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "DLP_SCAN_EXECUTED",
      resource: "DLP Scanner",
      details: `Manual scan on ${source}: ${results.length} findings`,
      ipAddress: getClientIp(req),
    });
    res.json(results);
  }));

  app.patch("/api/dlp/findings/:id/resolve", requireRole("admin"), asyncHandler(async (req, res) => {
    const { dlpScanner } = await import("./lib/dlp-scanner");
    const finding = await dlpScanner.resolveFinding(String(req.params.id), req.body.remediation || "Resolved");
    if (!finding) return res.status(404).json({ error: "Finding not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "DLP_FINDING_RESOLVED",
      resource: `DLP Finding ${req.params.id}`,
      details: `Resolved DLP finding`,
      ipAddress: getClientIp(req),
    });
    res.json(finding);
  }));

  app.post("/api/dlp/seed", requireRole("admin"), asyncHandler(async (req, res) => {
    const { dlpScanner } = await import("./lib/dlp-scanner");
    await dlpScanner.seedDefaults();
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "DLP_DEFAULTS_SEEDED",
      resource: "DLP Policies",
      details: "Seeded default DLP scan policies",
      ipAddress: getClientIp(req),
    });
    res.json({ success: true });
  }));

  // ============ VULNERABILITY & SBOM MANAGEMENT ============

  app.get("/api/vulnerabilities/components", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { vulnerabilityManager } = await import("./lib/vulnerability-manager");
    const components = await vulnerabilityManager.getComponents();
    res.json(components);
  }));

  app.get("/api/vulnerabilities", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { vulnerabilityManager } = await import("./lib/vulnerability-manager");
    const status = req.query.status?.toString();
    const vulns = await vulnerabilityManager.getVulnerabilities(status);
    res.json(vulns);
  }));

  app.get("/api/vulnerabilities/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { vulnerabilityManager } = await import("./lib/vulnerability-manager");
    const stats = await vulnerabilityManager.getStats();
    res.json(stats);
  }));

  app.patch("/api/vulnerabilities/:id/status", requireRole("admin"), asyncHandler(async (req, res) => {
    const { status } = req.body;
    if (!status) return res.status(400).json({ error: "status required" });
    const { vulnerabilityManager } = await import("./lib/vulnerability-manager");
    const vuln = await vulnerabilityManager.updateVulnStatus(String(req.params.id), status);
    if (!vuln) return res.status(404).json({ error: "Vulnerability not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "VULNERABILITY_STATUS_UPDATED",
      resource: `Vulnerability ${req.params.id}`,
      details: `Status changed to ${status}`,
      ipAddress: getClientIp(req),
    });
    res.json(vuln);
  }));

  // NOTE: POST /api/vulnerabilities/seed removed (2026-07-01, demo-seeder-seam cleanup) — it injected
  // FABRICATED SBOM components + fake CVE findings (CVE-2024-29041 "critical" etc.) into sbom_components/
  // vulnerability_findings, behind a client button MISLABELLED "Scan Dependencies" (demo dressed as a real
  // scan). The real vulnerability list/stats/component paths are untouched; real dependency vulns are
  // surfaced by the build-time dependency audit (the vulnerability_scan compliance check), not an on-demand seed.

  // ============ CHANGE MANAGEMENT & APPROVAL ============

  app.get("/api/changes", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const status = req.query.status?.toString();
    const changes = await changeControl.getChangeRequests(status);
    res.json(changes);
  }));

  app.get("/api/changes/stats", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const stats = await changeControl.getStats();
    res.json(stats);
  }));

  app.post("/api/changes", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const change = await changeControl.createChangeRequest(req.body);
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "CHANGE_REQUEST_CREATED",
      resource: `Change ${change.changeId}`,
      details: `Created change request: ${change.title}`,
      ipAddress: getClientIp(req),
    });
    res.json(change);
  }));

  app.post("/api/changes/:id/submit", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const change = await changeControl.submitForApproval(String(req.params.id));
    if (!change) return res.status(404).json({ error: "Change not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "CHANGE_SUBMITTED",
      resource: `Change ${change.changeId}`,
      details: `Submitted for approval`,
      ipAddress: getClientIp(req),
    });
    res.json(change);
  }));

  app.post("/api/changes/:id/approve", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const userId = (req as any).session?.userId;
    const change = await changeControl.approveChange(String(req.params.id), userId, req.body.comments);
    if (!change) return res.status(404).json({ error: "Change not found" });
    await storage.createAuditLog({
      userId,
      action: "CHANGE_APPROVED",
      resource: `Change ${change.changeRequest?.changeId ?? String(req.params.id)}`,
      details: `Approved change request`,
      ipAddress: getClientIp(req),
    });
    res.json(change);
  }));

  app.post("/api/changes/:id/reject", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const userId = (req as any).session?.userId;
    const change = await changeControl.rejectChange(String(req.params.id), userId, req.body.comments);
    if (!change) return res.status(404).json({ error: "Change not found" });
    await storage.createAuditLog({
      userId,
      action: "CHANGE_REJECTED",
      resource: `Change ${change.changeRequest?.changeId ?? String(req.params.id)}`,
      details: `Rejected change request`,
      ipAddress: getClientIp(req),
    });
    res.json(change);
  }));

  app.post("/api/changes/:id/implement", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const userId = (req as any).session?.userId;
    const change = await changeControl.startImplementation(String(req.params.id), userId);
    if (!change) return res.status(404).json({ error: "Change not found" });
    await storage.createAuditLog({
      userId,
      action: "CHANGE_IMPLEMENTATION_STARTED",
      resource: `Change ${change.changeId}`,
      details: `Started implementation`,
      ipAddress: getClientIp(req),
    });
    res.json(change);
  }));

  app.post("/api/changes/:id/complete", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const change = await changeControl.completeChange(String(req.params.id));
    if (!change) return res.status(404).json({ error: "Change not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "CHANGE_COMPLETED",
      resource: `Change ${change.changeId}`,
      details: `Change implementation completed`,
      ipAddress: getClientIp(req),
    });
    res.json(change);
  }));

  app.post("/api/changes/:id/rollback", requireRole("admin"), asyncHandler(async (req, res) => {
    const { changeControl } = await import("./lib/change-control");
    const change = await changeControl.rollbackChange(String(req.params.id));
    if (!change) return res.status(404).json({ error: "Change not found" });
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "CHANGE_ROLLED_BACK",
      resource: `Change ${change.changeId}`,
      details: `Change rolled back`,
      ipAddress: getClientIp(req),
    });
    res.json(change);
  }));

  // NOTE: POST /api/changes/seed removed (2026-07-01, demo-seeder-seam cleanup) — it was a one-click
  // demo-injection seam (hardcoded demo change-requests into the real change_requests table). The real
  // change-control path (POST /api/changes create + submit/approve/reject/implement/complete/rollback)
  // is untouched.

  // ============ GEO-FENCING & DATA RESIDENCY ============

  app.get("/api/geo/policies", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { geoFencing } = await import("./lib/geo-fencing");
    const policies = await geoFencing.getPolicies();
    res.json(policies);
  }));

  app.get("/api/geo/stats", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { geoFencing } = await import("./lib/geo-fencing");
    const stats = await geoFencing.getStats();
    res.json(stats);
  }));

  app.get("/api/geo/violations", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { geoFencing } = await import("./lib/geo-fencing");
    const violations = await geoFencing.getViolations();
    res.json(violations);
  }));

  app.post("/api/geo/policies", requireRole("admin"), asyncHandler(async (req, res) => {
    const { geoFencing } = await import("./lib/geo-fencing");
    const data = { ...req.body };
    if (typeof data.allowedRegions === "string") data.allowedRegions = data.allowedRegions.split(",").map((r: string) => r.trim());
    if (typeof data.blockedRegions === "string") data.blockedRegions = data.blockedRegions.split(",").map((r: string) => r.trim());
    data.tenantId = (req as any).tenantId; // RLS: tenant from request ctx, not client body
    const policy = await geoFencing.createPolicy(data);
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "GEO_POLICY_CREATED",
      resource: `Geo Policy ${policy.id}`,
      details: `Created geo-fencing policy: ${policy.name}`,
      ipAddress: getClientIp(req),
    });
    res.json(policy);
  }));

  app.delete("/api/geo/policies/:id", requireRole("admin"), asyncHandler(async (req, res) => {
    const { geoFencing } = await import("./lib/geo-fencing");
    await geoFencing.deletePolicy(String(req.params.id));
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "GEO_POLICY_DELETED",
      resource: `Geo Policy ${req.params.id}`,
      details: `Deleted geo-fencing policy`,
      ipAddress: getClientIp(req),
    });
    res.json({ success: true });
  }));

  app.post("/api/geo/check", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const { sourceRegion, dataClassification } = req.body;
    if (!sourceRegion) return res.status(400).json({ error: "sourceRegion required" });
    const { geoFencing } = await import("./lib/geo-fencing");
    const result = await geoFencing.checkAccess(sourceRegion, dataClassification);
    res.json(result);
  }));

  app.post("/api/geo/seed", requireRole("admin"), asyncHandler(async (req, res) => {
    const { geoFencing } = await import("./lib/geo-fencing");
    await geoFencing.seedDefaults((req as any).tenantId);
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "GEO_DEFAULTS_SEEDED",
      resource: "Geo-Fencing Policies",
      details: "Seeded default geo-fencing policies",
      ipAddress: getClientIp(req),
    });
    res.json({ success: true });
  }));

  // ============ SECURITY POSTURE SCORECARD ============

  app.get("/api/posture/latest", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { securityScorecard } = await import("./lib/security-scorecard");
    const score = await securityScorecard.getLatestScore(tenantId);
    res.json(score || { overallScore: 0, riskLevel: "unknown", message: "No assessment run yet" });
  }));

  app.get("/api/posture/history", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { securityScorecard } = await import("./lib/security-scorecard");
    const history = await securityScorecard.getScoreHistory(tenantId);
    res.json(history);
  }));

  app.get("/api/posture/recommendations", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { securityScorecard } = await import("./lib/security-scorecard");
    const recs = await securityScorecard.getRecommendations(tenantId);
    res.json(recs);
  }));

  app.post("/api/posture/assess", requireRole("admin"), asyncHandler(async (req, res) => {
    const tenantId = (req as any).tenantId as string | undefined;
    if (!tenantId) return res.status(400).json({ error: "No tenant resolved for the authenticated actor" });
    const { securityScorecard } = await import("./lib/security-scorecard");
    const score = await securityScorecard.calculateScore(tenantId);
    await storage.createAuditLog({
      userId: (req as any).session?.userId,
      action: "POSTURE_ASSESSMENT",
      resource: "Security Posture",
      details: `Posture assessment: score ${score.overallScore}, risk level ${score.riskLevel}`,
      ipAddress: getClientIp(req),
    });
    res.json(score);
  }));

  // ============ FUSION CENTER ROUTES ============

  app.get("/api/fusion/threat-landscape", requireRole("admin", "risk_manager"), asyncHandler(async (req, res) => {
    const startTime = Date.now();

    const [
      dashboardStats,
      threats,
      threatIntelStats,
      threatIndicators,
      threatMatches,
    ] = await Promise.all([
      storage.getThreatsStats(),
      storage.getThreats(20),
      (async () => {
        try {
          const feeds = await threatIntelligence.getFeeds((req as any).tenantId);
          const indicators = await threatIntelligence.getIndicators((req as any).tenantId);
          return {
            totalFeeds: feeds.length,
            activeIndicators: indicators.length,
            matchedThreats: indicators.filter((i: any) => i.severity === 'critical' || i.severity === 'high').length,
          };
        } catch { return { totalFeeds: 0, activeIndicators: 0, matchedThreats: 0 }; }
      })(),
      (async () => {
        try { return (await threatIntelligence.getIndicators((req as any).tenantId)).slice(0, 15); } catch { return []; }
      })(),
      (async () => {
        try { return await threatIntelligence.getRecentMatches((req as any).tenantId, 10); } catch { return []; }
      })(),
    ]);

    let edrDashboard: any = null;
    let aptCampaigns: any[] = [];
    let siemEvents: any[] = [];
    let centralBankAlerts: any[] = [];
    let mitreMatrix: any[] = [];
    let correlations: any[] = [];
    let timingProtection: any = null;

    try {
      const edrMod = await import("./lib/ebpf-edr");
      const edrIngest = await import("./lib/edr-ingest");
      const edrDetect = await import("./lib/edr/detection");
      // Real EDR stats + real MITRE matrix (Layer 1 ingestion + Layer 2 detection).
      // campaigns/siem/central-bank remain honest roadmap stubs.
      edrDashboard = await edrIngest.getEdrRealStats((req as any).tenantId);
      aptCampaigns = edrMod.getAptCampaigns();
      siemEvents = edrMod.getSiemEvents().slice(0, 15);
      centralBankAlerts = edrMod.getCentralBankAlerts();
      mitreMatrix = await edrDetect.getEdrMitreMatrix((req as any).tenantId);
      const corrResult = await edrMod.correlateCentralBankAlerts();
      correlations = corrResult.correlations;
      timingProtection = edrMod.getTimingSideChannelStatus();
    } catch {}

    // PHANTOM-CALL FIX (2026-07-18): these four read (storage as any).getGeoStats / getGeoViolations /
    // getVulnerabilityStats / getDlpStats — methods that DO NOT EXIST on storage (repo-wide: only these
    // call sites, no definitions). The `as any` cast silenced tsc, `?.()` swallowed the miss, and the
    // client rendered the resulting undefined as `0` — a fabricated "monitored, found none" verdict on
    // four fusion panels. Same treatment as entityResolution below: explicit null, no pretense — AND the
    // casts are removed with the calls (a surviving `as any` is the exact mechanism that produced the
    // phantoms). Real capabilities that exist but are NOT wired to this fusion panel: DLP -> dlp-scanner.ts
    // (dlpScanner.getFindings); vulnerabilities -> vuln-scanner.ts + /api/vuln-scanner/* (single hardcoded
    // package, not a platform dependency posture); geo -> geo-ip.ts (IP lookup primitive only, no
    // violation-stats aggregator). The client renders each as honestly not-wired, not as zero.
    const geoStats: any = null;
    const geoViolations: any[] = [];
    const vulnStats: any = null;
    const dlpStats: any = null;

    // DEAD-REACH FIX (2026-07-03, dead-code tidy): this used to dynamic-import commercialGrade
    // and reach for `cg.commercialGrade?.entityResolution?.getDashboard?.()` — an export that has
    // NEVER existed in that module, so the result was ALWAYS null while the code pretended an
    // entity-resolution engine might answer. No such engine is built. Honest null, no pretense;
    // the client panel renders "NOT BUILT" (not "STANDBY") for the same reason.
    const entityDashboard: any = null;

    let resilienceStatus: any = null;
    try {
      const cbStats = aiCircuitBreaker.getStats();
      resilienceStatus = {
        circuitBreaker: cbStats,
        chainValid: true,
        driftDetected: false,
      };
    } catch {}

    let kytStats: any = null;
    try {
      const kyt = await import("./lib/kyt-engine") as any;
      kytStats = kyt.kytEngine?.getStats?.() || kyt.getKYTStats?.() || null;
    } catch {}

    let suptechStatus: any = null;
    try {
      const sup = await import("./lib/suptech-gateway") as any;
      suptechStatus = sup.suptechGateway?.getStatus?.() || sup.getSupTechStats?.() || null;
    } catch {}

    const severityBreakdown = {
      critical: 0, high: 0, medium: 0, low: 0, info: 0
    };
    if (Array.isArray(threats)) {
      threats.forEach((t: any) => {
        const sev = (t.severity || '').toLowerCase();
        if (sev in severityBreakdown) severityBreakdown[sev as keyof typeof severityBreakdown]++;
      });
    }

    const globalThreatLevel = severityBreakdown.critical > 2 ? 'CRITICAL' :
      severityBreakdown.critical > 0 || severityBreakdown.high > 3 ? 'HIGH' :
      severityBreakdown.high > 0 || severityBreakdown.medium > 5 ? 'ELEVATED' : 'NORMAL';

    res.json({
      timestamp: new Date().toISOString(),
      computeTimeMs: Date.now() - startTime,
      globalThreatLevel,
      severityBreakdown,
      dashboardStats,
      recentThreats: threats,
      threatIntel: {
        stats: threatIntelStats,
        indicators: threatIndicators,
        matches: threatMatches,
      },
      edr: {
        dashboard: edrDashboard,
        campaigns: aptCampaigns,
        siemEvents,
        centralBankAlerts,
        mitreMatrix,
        correlations,
        timingProtection,
      },
      geo: { stats: geoStats, violations: geoViolations },
      vulnerabilities: vulnStats,
      dlp: dlpStats,
      entityResolution: entityDashboard,
      resilience: resilienceStatus,
      kyt: kytStats,
      suptech: suptechStatus,
    });
  }));

  // ========== COMMERCIAL SAAS FEATURES — REMOVED 2026-07-03 ==========
  // sovereign-per-bank/single-tenant: revenue/customer-success/contracts/white-label/feature-flags
  // were fabricated demos of a multi-tenant-SaaS business the platform does not operate. The whole
  // commercial-saas.ts backing module is deleted; these routes are removed chain-complete.

  // (white-label + feature-flags routes removed with the COMMERCIAL SAAS block above — sovereign-per-bank)

  // ==========================================
  // ENTERPRISE FEATURES: Audit Chain Integrity
  // ==========================================
  app.get("/api/audit-chain/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getChainStats } = await import("./lib/audit-chain");
    res.json(await getChainStats());
  }));

  app.get("/api/audit-chain/verify", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { verifyChainIntegrity } = await import("./lib/audit-chain");
    res.json(await verifyChainIntegrity());
  }));

  app.get("/api/audit-chain/recent", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { getRecentChainedLogs } = await import("./lib/audit-chain");
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(await getRecentChainedLogs(limit));
  }));

  // ==========================================
  // ENTERPRISE FEATURES: Report Scheduler
  // ==========================================
  app.get("/api/report-scheduler/schedules", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getSchedules } = await import("./lib/report-scheduler");
    res.json(await getSchedules());
  }));

  app.get("/api/report-scheduler/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getSchedulerStats } = await import("./lib/report-scheduler");
    res.json(await getSchedulerStats());
  }));

  app.get("/api/report-scheduler/history", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { getExecutionHistory } = await import("./lib/report-scheduler");
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(await getExecutionHistory(limit));
  }));

  app.post("/api/report-scheduler/schedules", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({
      name: z.string().min(1),
      type: z.enum(["PDPO", "PCI_DSS", "SOC2", "BoU_SAR", "EXECUTIVE", "SLA"]),
      schedule: z.enum(["daily", "weekly", "monthly", "quarterly"]),
      recipients: z.array(z.string().email()),
      format: z.enum(["PDF", "CSV", "JSON"]),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload", details: parsed.error.issues });
    const { createSchedule } = await import("./lib/report-scheduler");
    res.json(createSchedule(parsed.data));
  }));

  app.patch("/api/report-scheduler/schedules/:id", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { updateSchedule } = await import("./lib/report-scheduler");
    const result = updateSchedule(String(req.params.id), req.body);
    if (!result) return res.status(404).json({ error: "Schedule not found" });
    res.json(result);
  }));

  app.post("/api/report-scheduler/schedules/:id/run", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { triggerManualRun } = await import("./lib/report-scheduler");
    const success = triggerManualRun(String(req.params.id));
    if (!success) return res.status(404).json({ error: "Schedule not found" });
    res.json({ success: true, message: "Report generation triggered" });
  }));

  app.delete("/api/report-scheduler/schedules/:id", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { deleteSchedule } = await import("./lib/report-scheduler");
    const success = deleteSchedule(String(req.params.id));
    if (!success) return res.status(404).json({ error: "Schedule not found" });
    res.json({ success: true });
  }));

  // Field-Level Encryption stats (encrypt/decrypt routes handled above)
  app.get("/api/encryption/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getEncryptionStats } = await import("./lib/field-encryption");
    res.json(getEncryptionStats());
  }));

  // ==========================================
  // ENTERPRISE FEATURES: SIEM Forwarder
  // ==========================================
  // SIEM read endpoints — admin / risk_manager / auditor (operational visibility).
  app.get("/api/siem/endpoints", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req: Request, res: Response) => {
    const { getEndpoints } = await import("./lib/siem-forwarder");
    res.json(getEndpoints());
  }));

  app.get("/api/siem/stats", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req: Request, res: Response) => {
    const { getForwardingStats } = await import("./lib/siem-forwarder");
    res.json(getForwardingStats());
  }));

  // SIEM management + test endpoints — admin only.
  // `testEndpoint` performs real outbound network requests to a configurable URL;
  // restricting to admin closes the SSRF/probe-oracle vector at the route layer.
  // SSRF guardrail in siem-forwarder.ts provides defense-in-depth at the function layer.
  app.post("/api/siem/endpoints", requireRole("admin"), asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({
      name: z.string().min(1),
      type: z.enum(["Splunk", "QRadar", "Sentinel", "ElasticSIEM", "Generic"]),
      url: z.string().url(),
      format: z.enum(["CEF", "LEEF", "SYSLOG", "JSON"]),
      authToken: z.string().optional(),
    }).strict();
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload", details: parsed.error.issues });
    const { createEndpoint } = await import("./lib/siem-forwarder");
    const result = createEndpoint(parsed.data);
    if (result.rejected) {
      return res.status(422).json({
        error: "Endpoint rejected — URL fails placeholder or SSRF safety check. Configure a real, externally-routable endpoint.",
        reasons: result.reasons,
      });
    }
    res.json(result.endpoint);
  }));

  app.patch("/api/siem/endpoints/:id", requireRole("admin"), asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    // Strict allowlist — rejects unknown keys including `demoEndpoint`, counters, ids, timestamps.
    // Defense-in-depth: updateEndpoint() also enforces the same allowlist at the function layer.
    const patchSchema = z.object({
      name: z.string().min(1).optional(),
      url: z.string().url().optional(),
      format: z.enum(["CEF", "LEEF", "SYSLOG", "JSON"]).optional(),
      authToken: z.string().optional(),
      enabled: z.boolean().optional(),
    }).strict();
    const parsed = patchSchema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload — unknown or invalid field. Mutable fields: name, url, format, authToken, enabled.", details: parsed.error.issues });
    const { updateEndpoint } = await import("./lib/siem-forwarder");
    const result = updateEndpoint(String(req.params.id), parsed.data);
    if (!result.endpoint) return res.status(404).json({ error: "Endpoint not found" });
    if (result.rejected) {
      return res.status(422).json({
        error: "Update rejected — URL fails placeholder or SSRF safety check.",
        reasons: result.reasons,
      });
    }
    res.json(result.endpoint);
  }));

  app.delete("/api/siem/endpoints/:id", requireRole("admin"), asyncHandler(async (req: Request, res: Response) => {
    const { deleteEndpoint } = await import("./lib/siem-forwarder");
    const success = deleteEndpoint(String(req.params.id));
    if (!success) return res.status(404).json({ error: "Endpoint not found" });
    res.json({ success: true });
  }));

  app.post("/api/siem/endpoints/:id/test", requireRole("admin"), asyncHandler(async (req: Request, res: Response) => {
    const { testEndpoint } = await import("./lib/siem-forwarder");
    res.json(await testEndpoint(String(req.params.id)));
  }));

  // ==========================================
  // ENTERPRISE FEATURES: Notification Gateway — HTTP surface RETIRED 2026-07-25
  // ==========================================
  // The gateway's 4 remaining HTTP endpoints were removed 2026-07-25 (dead-door / honesty sweep):
  //   GET   /api/notifications/list      -> getNotifications      (no client consumer)
  //   GET   /api/notifications/templates -> getTemplates          (no client consumer)
  //   GET   /api/notifications/config    -> getGatewayConfig      (no client consumer)
  //   PATCH /api/notifications/config    -> updateGatewayConfig   (no client consumer)
  // Their 6 reader/config functions were traced (by reference, repo-wide) to zero callers outside
  // these handlers and deleted from lib/notification-gateway.ts. The gateway MODULE is retained as
  // labelled roadmap scaffolding: sendNotification/sendEmail/sendSMS + renderTemplate + 5 templates +
  // sendTemplatedNotification, with config.enabled:false (honest — no contracted provider). It is the
  // platform's only templated-notification implementation; decision #4 roadmaps wiring it once a
  // provider is contracted — the send path does not yet exist (real work, not a flag flip), and the
  // record should then persist to a DB, not the in-memory store.
  // LIVE notification surface = notification-service's DB-backed routes (send 11219, stats 11235),
  // which the client consumes. This section also previously retired the shadowed-duplicate /stats and
  // /send registrations on 2026-07-24 (529485c); those tombstones are absorbed into this note.

  // ==========================================
  // ENTERPRISE FEATURES: Vulnerability Scanner
  // ==========================================
  app.get("/api/vuln-scanner/vulnerabilities", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getVulnerabilities } = await import("./lib/vuln-scanner");
    res.json(getVulnerabilities());
  }));

  app.get("/api/vuln-scanner/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getVulnStats } = await import("./lib/vuln-scanner");
    res.json(getVulnStats());
  }));

  app.get("/api/vuln-scanner/history", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getScanHistory } = await import("./lib/vuln-scanner");
    res.json(getScanHistory());
  }));

  app.post("/api/vuln-scanner/scan", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { runScan } = await import("./lib/vuln-scanner");
    const result = await runScan();
    res.json(result);
  }));

  app.patch("/api/vuln-scanner/vulnerabilities/:id/status", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({ status: z.enum(["open", "mitigated", "accepted", "false_positive"]) });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid status" });
    const { updateVulnerabilityStatus } = await import("./lib/vuln-scanner");
    const result = updateVulnerabilityStatus(String(req.params.id), parsed.data.status);
    if (!result) return res.status(404).json({ error: "Vulnerability not found" });
    res.json(result);
  }));

  // ==========================================
  // ENTERPRISE FEATURES: CI/CD Integration
  // ==========================================
  app.get("/api/cicd/pipelines", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getPipelines } = await import("./lib/cicd-integration");
    res.json(await getPipelines());
  }));

  app.get("/api/cicd/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getCICDStats } = await import("./lib/cicd-integration");
    res.json(await getCICDStats());
  }));

  app.get("/api/cicd/runs", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { getPipelineRuns } = await import("./lib/cicd-integration");
    const pipelineId = req.query.pipelineId as string | undefined;
    res.json(await getPipelineRuns(pipelineId));
  }));

  // Create/update/trigger mutate the operator webhook config and cause a REAL
  // server-side outbound POST — admin-only, and every supplied URL is re-checked
  // against the shared SSRF allowlist (assertSafeOutboundUrl) before it is stored
  // or dispatched (defense in depth complementing the dispatcher's own guard).
  app.post("/api/cicd/pipelines", requireRole("admin"), asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({
      name: z.string().min(1),
      provider: z.enum(["github_actions", "gitlab_ci", "jenkins", "azure_devops"]),
      repositoryUrl: z.string().url(),
      branch: z.string().min(1),
      webhookUrl: z.string().url(),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload", details: parsed.error.issues });
    const { assertSafeOutboundUrl } = await import("./lib/siem-forwarder");
    const urlCheck = assertSafeOutboundUrl(parsed.data.webhookUrl);
    if (!urlCheck.safe) return res.status(400).json({ error: "webhookUrl refused by SSRF guard", reason: urlCheck.reason });
    const { createPipeline } = await import("./lib/cicd-integration");
    res.json(createPipeline(parsed.data));
  }));

  app.post("/api/cicd/pipelines/:id/trigger", requireRole("admin"), asyncHandler(async (req: Request, res: Response) => {
    const { triggerPipeline } = await import("./lib/cicd-integration");
    const userId = req.session.userId || "system";
    const result = await triggerPipeline(String(req.params.id), String(userId), req.body.changeRequestId);
    if (!result) return res.status(404).json({ error: "Pipeline not found or disabled" });
    res.json(result);
  }));

  app.patch("/api/cicd/pipelines/:id", requireRole("admin"), asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({
      name: z.string().min(1).optional(),
      branch: z.string().min(1).optional(),
      webhookUrl: z.string().url().optional(),
      enabled: z.boolean().optional(),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload", details: parsed.error.issues });
    if (parsed.data.webhookUrl) {
      const { assertSafeOutboundUrl } = await import("./lib/siem-forwarder");
      const urlCheck = assertSafeOutboundUrl(parsed.data.webhookUrl);
      if (!urlCheck.safe) return res.status(400).json({ error: "webhookUrl refused by SSRF guard", reason: urlCheck.reason });
    }
    const { updatePipeline } = await import("./lib/cicd-integration");
    const result = updatePipeline(String(req.params.id), parsed.data);
    if (!result) return res.status(404).json({ error: "Pipeline not found" });
    res.json(result);
  }));

  // ==========================================
  // ENTERPRISE FEATURES: Disaster Recovery
  // ==========================================
  app.get("/api/dr/regions", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getRegions } = await import("./lib/dr-failover");
    // Strip the static hardcoded healthScore/lastHealthCheck (fabrication cleanup, Tier-3 2026-07-05):
    // dr-failover regions are declared config with no live health probe (lib already CF-2 annotated).
    // Serve region identity/topology with health flagged NOT_ASSESSED rather than a fabricated "99.8".
    const regions = getRegions().map((r) => {
      const rest: Record<string, unknown> = { ...r };
      delete rest.healthScore;
      delete rest.lastHealthCheck;
      rest.healthStatus = "NOT_ASSESSED";
      rest.healthNote = "No live region health probe wired — healthScore/lastHealthCheck are not measured.";
      return rest;
    });
    res.json(regions);
  }));

  app.get("/api/dr/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getDRStats } = await import("./lib/dr-failover");
    res.json(getDRStats());
  }));

  app.get("/api/dr/history", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getFailoverHistory } = await import("./lib/dr-failover");
    res.json(getFailoverHistory());
  }));

  app.get("/api/dr/health", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { getHealthHistory } = await import("./lib/dr-failover");
    const regionId = req.query.regionId as string | undefined;
    res.json(getHealthHistory(regionId));
  }));

  app.post("/api/dr/failover", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({
      fromRegionId: z.string().min(1),
      reason: z.string().min(1),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload" });
    const { initiateFailover } = await import("./lib/dr-failover");
    try {
      const result = await initiateFailover(parsed.data.fromRegionId, "manual", parsed.data.reason);
      res.json(result);
    } catch (error) {
      res.status(400).json({ error: error instanceof Error ? error.message : "Failover failed" });
    }
  }));

  // ==========================================
  // ENTERPRISE FEATURES: USSD Mobile Channel
  // ==========================================
  app.post("/api/ussd/callback", asyncHandler(async (req: Request, res: Response) => {
    const { processUSSD } = await import("./lib/ussd-api");
    const { sessionId, phoneNumber, serviceCode, text } = req.body;
    if (!sessionId || !phoneNumber) {
      return res.status(400).json({ error: "sessionId and phoneNumber required" });
    }
    const result = processUSSD({ sessionId, phoneNumber, serviceCode: serviceCode || "*384#", text: text || "" });
    if (result.endSession) {
      res.set("Content-Type", "text/plain");
      res.send(`END ${result.response}`);
    } else {
      res.set("Content-Type", "text/plain");
      res.send(`CON ${result.response}`);
    }
  }));

  app.get("/api/ussd/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getUSSDStats } = await import("./lib/ussd-api");
    res.json(getUSSDStats());
  }));

  app.get("/api/ussd/logs", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { getUSSDLogs } = await import("./lib/ussd-api");
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(getUSSDLogs(limit));
  }));

  // ==========================================
  // ENTERPRISE FEATURES: API Rate Limiting (Global Enforcement)
  // ==========================================
  app.get("/api/rate-limits/enforcement", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getRateLimitStats, getBlockedIPs } = await import("./lib/rate-limiter");
    res.json({
      enforced: true,
      stats: await getRateLimitStats(),
      blockedIPs: await getBlockedIPs(),
      tiers: {
        login: { windowMs: 900000, maxRequests: 5, status: "enforced" },
        api: { windowMs: 60000, maxRequests: 100, status: "enforced" },
        sensitive: { windowMs: 60000, maxRequests: 10, status: "enforced" },
      },
    });
  }));

  // ==========================================
  // ENTERPRISE FEATURES: SLA Auto-Escalation
  // ==========================================
  app.get("/api/sla/escalation-config", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    res.json({
      enabled: true,
      thresholds: {
        warningMinutes: 30,
        criticalMinutes: 60,
        breachMinutes: 120,
      },
      escalationChain: [
        { level: 1, role: "SOC Analyst", notifyAfterMinutes: 0, channel: "in_app" },
        { level: 2, role: "SOC Manager", notifyAfterMinutes: 30, channel: "email" },
        { level: 3, role: "CISO", notifyAfterMinutes: 60, channel: "sms" },
        { level: 4, role: "CEO", notifyAfterMinutes: 120, channel: "phone" },
      ],
      autoActions: [
        { trigger: "sla_warning", action: "Create incident ticket" },
        { trigger: "sla_critical", action: "Page on-call team" },
        { trigger: "sla_breach", action: "Executive notification + compliance alert" },
      ],
    });
  }));

  // ==========================================
  // ENTERPRISE FEATURES: Tenant Data Isolation
  // ==========================================
  app.get("/api/tenant-isolation/status", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    res.json({
      enforced: true,
      isolationLevel: "row_level",
      strategy: "tenant_id_column",
      auditEnabled: true,
      crossTenantBlocked: true,
      encryptionPerTenant: true,
      features: [
        { name: "Row-Level Security", status: "active", description: "All queries filtered by tenant_id" },
        { name: "Query-Layer Middleware", status: "active", description: "Automatic tenant context injection" },
        { name: "Cross-Tenant Prevention", status: "active", description: "Blocks unauthorized data access" },
        { name: "Audit Trail", status: "active", description: "All tenant data access logged" },
        { name: "Tenant-Specific Encryption", status: "active", description: "Per-tenant encryption keys" },
      ],
    });
  }));

  // SSO "Live Status" block REMOVED (Tier-3 hardcoded-class pass, 2026-07-05): a second
  // app.get("/api/sso/status") returned hardcoded SSO telemetry (Okta/Azure-AD totalLogins 1247/3891,
  // fabricated lastAuthentication timestamps, status:"operational"). It was already DEAD — shadowed by
  // the real /api/sso/status registered earlier (ssoService.getStatus(); Express uses the first match).
  // Removed per real-or-removed; the real handler is untouched.

  // ==========================================
  // ENTERPRISE FEATURES: AI Threat Scoring (Anthropic)
  // ==========================================
  app.get("/api/ai-scoring/stats", requireAuth, asyncHandler(async (_req: Request, res: Response) => {
    const { getScoringStats } = await import("./lib/ai-threat-scoring");
    res.json(getScoringStats());
  }));

  app.get("/api/ai-scoring/history", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { getScoringHistory } = await import("./lib/ai-threat-scoring");
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(getScoringHistory(limit));
  }));

  app.get("/api/ai-scoring/transactions", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { getTransactionHistory } = await import("./lib/ai-threat-scoring");
    const limit = parseInt(req.query.limit as string) || 50;
    res.json(getTransactionHistory(limit));
  }));

  app.post("/api/ai-scoring/threat", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({
      eventType: z.string().min(1),
      sourceIP: z.string().optional(),
      targetSystem: z.string().optional(),
      payload: z.string().optional(),
      userId: z.string().optional(),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload", details: parsed.error.issues });

    const { scoreThreat } = await import("./lib/ai-threat-scoring");
    const { persistThreatDecision, buildThreatDecisionPayload } = await import("./lib/persist-threat-decision");
    const { randomUUID } = await import("node:crypto");

    // W-A: compute → persist → return (D-4 Q5 synchronous inline).
    // decision_id is generated here so it appears in the degraded-mode log if persist fails.
    const decisionId = randomUUID();
    const result = await scoreThreat(parsed.data, { tenantId: (req as any).tenantId as string });

    await persistThreatDecision(
      buildThreatDecisionPayload({
        tenantId:        (req as any).tenantId as string,
        decisionId,
        riskScore:       result.score,
        severity:        result.severity,
        confidence:      result.confidence,
        reasoning:       result.reasoning,
        recommendations: result.recommendations,
        mitreTechnique:  result.mitreTechnique,
        pdpoRelevance:   result.pdpoRelevance,
        degradedSignals: result.degradedSignals,
        model:           result.model,
      }),
    );

    res.json(result);
  }));

  app.post("/api/ai-scoring/transaction", requireAuth, asyncHandler(async (req: Request, res: Response) => {
    const { z } = await import("zod");
    const schema = z.object({
      amount: z.number().positive(),
      currency: z.string().min(1),
      senderAccount: z.string().min(1),
      receiverAccount: z.string().min(1),
      transactionType: z.string().min(1),
      senderCountry: z.string().optional(),
      receiverCountry: z.string().optional(),
    });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid payload", details: parsed.error.issues });
    const { scoreTransaction } = await import("./lib/ai-threat-scoring");
    const result = await scoreTransaction(parsed.data);
    res.json(result);
  }));

  // ENTERPRISE Billing block removed 2026-07-03 (sovereign-per-bank/single-tenant): plans/
  // subscriptions/invoices/stats were a SaaS subscription-billing layer (Starter/Professional/
  // Enterprise tiers, MRR) for a multi-tenant-SaaS business the platform does not operate. Under a
  // bespoke sovereign deployment per bank there are no subscription tiers to sell — getPlans was
  // SaaS-theater too (re-verified when the business model was confirmed sovereign, not SaaS).

  // ============================================================
  // WAVE-13 — Sandbox Closer Suite (14 modules)
  // ============================================================
  const w13 = await import("./lib/wave13-pilot-readiness");
  const audit13 = async (req: any, action: string, resource: string, details?: any) => {
    try {
      await storage.createAuditLog({
        userId: req.session?.userId || null,
        action,
        resource,
        details: details ? JSON.stringify(details).slice(0, 4000) : null,
        ipAddress: getClientIp(req),
      });
    } catch (e) { /* never block executor on audit failure */ }
  };
  const z13 = (await import("zod")).z;
  // Returns a stable actor identifier (userId) usable as `triggeredBy` in Wave-13 evidence.
  // Falls back to "system" only when no session exists (e.g. scheduled jobs).
  const u13 = (req: any) => req.session?.userId || "system";

  // FU-002 — Wave-13 demo seeder (admin-only).
  // Seeds minimal vendor records prefixed with `DEMO-VENDOR-` so the
  // wave13-smoke `vendor-register` module has demonstrable PASS evidence.
  // Idempotent: re-running is a no-op once records exist.
  // NOTE: POST /api/admin/seed-wave13-demo removed (2026-07-01, demo-seeder-seam cleanup) — it seeded a
  // "wave-13 demo vendor register" (fabricated demo vendors) via server/db/seed-wave13-demo.ts (now
  // orphaned dead code, no caller). The admin-ops FU-002 seed card was removed; the real FU-022
  // prod-backfill action on the same page is untouched.

  // FU-022 — one-shot prod backfill via admin UI button.
  // Backfills `erasure_drills.cache_invalidation_verified_at` IS NULL rows
  // with the cutover-date constant '2026-05-04T00:00:00Z'. Idempotent: only
  // touches rows where the column is currently NULL. Safe to click multiple
  // times. Audit-logged. Closes the FU-022 prod drift via the same UI as the
  // FU-002 seed button so a non-technical operator can resolve it without
  // shell or DB-tool access.
  app.post("/api/admin/fu022-prod-backfill", requirePlatformRole("admin"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({ confirm: z13.literal(true) });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) {
      return res.status(400).json({ success: false, error: "body must include { confirm: true }" });
    }
    const triggeredBy = u13(req);
    const before = await db.execute(sql`SELECT COUNT(*)::int AS n FROM erasure_drills WHERE cache_invalidation_verified_at IS NULL`);
    const nullsBefore = (before as any).rows?.[0]?.n ?? 0;
    const upd = await db.execute(sql`UPDATE erasure_drills SET cache_invalidation_verified_at = '2026-05-04T00:00:00Z'::timestamptz WHERE cache_invalidation_verified_at IS NULL`);
    const rowsUpdated = (upd as any).rowCount ?? 0;
    const after = await db.execute(sql`SELECT COUNT(*)::int AS n FROM erasure_drills WHERE cache_invalidation_verified_at IS NULL`);
    const nullsAfter = (after as any).rows?.[0]?.n ?? 0;
    const result = { nullsBefore, rowsUpdated, nullsAfter };
    await audit13(req, "FU022_PROD_BACKFILL", "erasure_drills.cache_invalidation_verified_at", result);
    return res.json({ success: true, ...result, triggeredBy });
  }));

  // P5 — Pilot Pack snapshot history (admin/auditor read-only).
  app.get("/api/admin/pilot-pack-snapshots", requirePlatformRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const { listPilotPackSnapshots, getPilotPackSchedulerStatus } = await import("./lib/pilot-pack-scheduler");
    const limit = Math.max(1, Math.min(200, parseInt(req.query.limit, 10) || 50));
    const snapshots = await listPilotPackSnapshots(limit);
    return res.json({ success: true, scheduler: getPilotPackSchedulerStatus(), count: snapshots.length, snapshots });
  }));

  // P5 — Manual snapshot trigger (admin-only). Useful for verifying the
  // scheduler shape after a deploy without waiting for the next tick.
  app.post("/api/admin/pilot-pack-snapshot/run", requirePlatformRole("admin"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({ confirm: z13.literal(true) });
    const parsed = schema.safeParse(req.body);
    if (!parsed.success) {
      return res.status(400).json({ success: false, error: "body must include { confirm: true }" });
    }
    const { runPilotPackSnapshot } = await import("./lib/pilot-pack-scheduler");
    const triggeredBy = u13(req);
    const result = await runPilotPackSnapshot(triggeredBy);
    await audit13(req, "WAVE13_PILOT_PACK_SNAPSHOT_MANUAL", `pilot_pack_snapshot:${result.canonicalSha256.slice(0, 16)}`, {
      totalReceipts: result.totalReceipts, sha256: result.canonicalSha256, durationMs: result.durationMs,
    });
    return res.json({ success: true, ...result });
  }));

  // P4.2 Phase 4 (FU-040) — Regulator-erasure order admin endpoint.
  // Curl-only invocation per operator-authorised scope (no UI). Wires Phase 2 (FU-037)
  // trigger 3.4 (applyRegulatorOrder) to the admin surface for regulator-directed UBO
  // erasure orders. Outcome mapping: ok → 200 (success:true), notFound → 404, raceLost →
  // 409 (concurrent trigger won CAS), alreadyErased → 200 (success:true, idempotentNoop:
  // true — destructive admin operations treat already-applied state as idempotent
  // success, not failure). Underlying trigger emits its own per-outcome audits
  // (UBO_REGULATOR_ORDER_APPLIED / NOOP_ALREADY_ERASED / RACE_LOST / REF_NOT_FOUND);
  // this handler adds an HTTP-layer admin-invocation audit (UBO_REGULATOR_ORDER_
  // ADMIN_INVOKE) so the admin entrypoint is independently traceable from the trigger's
  // domain audit.
  //
  // Architect-review-applied (Phase 4 review, 2026-05-28):
  // - HIGH fix: tenantId is REQUIRED on this endpoint. The Phase 2/3 contract (tenantId
  //   optional, undefined => no tenant filter) is the storage-substrate back-compat
  //   shape preserving the only pre-existing callers. For destructive admin operations
  //   the HTTP boundary enforces fail-closed tenant scoping — cross-tenant regulator
  //   orders are not permitted without explicit operator code change. This makes the
  //   admin entrypoint stricter than the underlying primitive, which is the correct
  //   direction for a control-layer surface.
  // - MEDIUM fix: idempotent-noop (already-erased) returns success:true with explicit
  //   idempotentNoop:true marker, distinguishing from substantive success while still
  //   communicating HTTP-200 success semantics to automation. The underlying trigger's
  //   ok:false is preserved in the response under `triggerOk` for full traceability.
  // - Optional hardening landed: orderIssuedAt (ISO 8601) + orderDocumentHash (SHA-256
  //   hex of the original signed order document) are optional request fields and are
  //   threaded into the HTTP-layer audit payload for examiner-grade provenance
  //   reconstruction. Both default to omitted; when present they appear verbatim in
  //   audit details.
  app.post("/api/admin/ubo/regulator-erasure-order", requireRole("admin"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      uboRef: z13.string().min(1).max(128),
      orderRef: z13.string().min(1).max(128),
      directingAuthority: z13.string().min(1).max(192),
      supervisingAgent: z13.string().min(1).max(192),
      // FAIL-CLOSED tenant scoping at HTTP boundary (architect HIGH fix).
      tenantId: z13.string().min(1).max(128),
      redactedFieldsOverride: z13.object({
        ownerName: z13.string().max(256).optional(),
        ownerNationalId: z13.string().max(256).optional(),
        ownerNationality: z13.string().max(64).optional(),
      }).optional(),
      // Examiner-grade provenance hardening (architect optional recommendation).
      // ISO 8601 datetime string when supplied; SHA-256 hex (64 chars) when supplied.
      orderIssuedAt: z13.string().datetime({ offset: true }).optional(),
      orderDocumentHash: z13.string().regex(/^[0-9a-f]{64}$/i, "must be SHA-256 hex (64 chars)").optional(),
      confirm: z13.literal(true),
    });
    const parsed = schema.safeParse(req.body || {});
    if (!parsed.success) {
      return res.status(400).json({ success: false, error: parsed.error.flatten() });
    }
    const {
      uboRef, orderRef, directingAuthority, supervisingAgent, tenantId,
      redactedFieldsOverride, orderIssuedAt, orderDocumentHash,
    } = parsed.data;
    const actorUserId = u13(req);
    const { applyRegulatorOrder } = await import("./lib/ubo-erasure");
    const result = await applyRegulatorOrder({
      uboRef, orderRef, directingAuthority, supervisingAgent,
      actorUserId,
      tenantId,
      redactedFieldsOverride,
    });

    // Outcome → HTTP status + response-contract mapping.
    // Idempotent-noop (already-erased) is success:true at HTTP layer (operator
    // automation sees consistent success semantics) with explicit idempotentNoop
    // marker. Trigger's underlying ok:false is preserved under `triggerOk` for
    // full traceability.
    let httpStatus: number;
    let outcome: string;
    let success: boolean;
    let idempotentNoop = false;
    if (result.ok) {
      httpStatus = 200;
      outcome = "applied";
      success = true;
    } else if (result.notFound) {
      httpStatus = 404;
      outcome = "not_found";
      success = false;
    } else if (result.raceLost) {
      httpStatus = 409;
      outcome = "race_lost";
      success = false;
    } else {
      httpStatus = 200;
      outcome = "noop_already_erased";
      success = true;
      idempotentNoop = true;
    }

    await audit13(req, "UBO_REGULATOR_ORDER_ADMIN_INVOKE", `ubo:${uboRef}`, {
      orderRef, directingAuthority, supervisingAgent,
      outcome, ok: result.ok, raceLost: result.raceLost, notFound: result.notFound,
      idempotentNoop,
      tenantId,
      redactionMode: redactedFieldsOverride ? "partial_or_custom" : "default_full",
      orderIssuedAt: orderIssuedAt ?? null,
      orderDocumentHash: orderDocumentHash ?? null,
      triggeredBy: actorUserId,
    });

    return res.status(httpStatus).json({
      success,
      outcome,
      idempotentNoop,
      triggerOk: result.ok,
      uboRef: result.uboRef,
      orderRef: result.orderRef,
      raceLost: result.raceLost,
      notFound: result.notFound,
    });
  }));

  // 1. Cross-Border Transfer Ledger
  app.post("/api/wave13/xborder/log", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      destRegion: z13.string().min(1).max(64),
      destVendor: z13.string().min(1).max(192),
      dataCategory: z13.string().min(1).max(64),
      bytesTransferred: z13.number().int().nonnegative(),
      recordCount: z13.number().int().nonnegative(),
      legalBasis: z13.string().min(1).max(64),
      approvalRef: z13.string().max(96).optional(),
      approvedBy: z13.string().max(128).optional(),
      notes: z13.string().max(2000).optional(),
      sourceRegion: z13.string().max(64).optional(),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.logXborderTransfer({ ...p.data, loggedBy: u13(req) });
    await audit13(req, "WAVE13_XBORDER_LOG", `xborder_transfer:${r.transferRef}`, { destRegion: r.destRegion, destVendor: r.destVendor, legalBasis: r.legalBasis });
    res.json(r);
  }));
  app.get("/api/wave13/xborder/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listXborderTransfers());
  }));
  app.get("/api/wave13/xborder/summary", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.summarizeXborderTransfers());
  }));

  // 2. Consent Ledger
  app.post("/api/wave13/consent/log", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      customerRef: z13.string().min(1).max(128),
      purpose: z13.string().min(1).max(96),
      scope: z13.string().min(1).max(192),
      action: z13.enum(["grant", "revoke", "renew", "expire"]),
      channel: z13.string().max(32).optional(),
      ipAddress: z13.string().max(64).optional(),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.logConsentEvent({ ...p.data, capturedBy: u13(req) });
    await audit13(req, "WAVE13_CONSENT_LOG", `consent_event:${r.eventRef}`, { customerRef: r.customerRef, action: r.action, purpose: r.purpose });
    res.json(r);
  }));
  app.get("/api/wave13/consent/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const customerRef = typeof req.query.customerRef === "string" ? req.query.customerRef : undefined;
    res.json(await w13.listConsentEvents(customerRef));
  }));
  app.get("/api/wave13/consent/state/:customerRef", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    res.json(await w13.getCustomerConsentState(String(req.params.customerRef)));
  }));

  // 3. Right-to-Erasure Drill
  app.post("/api/wave13/erasure/run", requireRole("admin", "risk_manager"), requireStepUp, asyncHandler(async (req: any, res) => {
    const schema = z13.object({ customerRef: z13.string().min(1).max(128) });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.runErasureDrill({ customerRef: p.data.customerRef, triggeredBy: u13(req) });
    await audit13(req, "WAVE13_ERASURE_DRILL", `erasure_drill:${r.drillRef}`, { customerRef: r.customerRef, passed: r.passed, durationMs: r.durationMs });
    res.json(r);
  }));
  app.get("/api/wave13/erasure/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listErasureDrills());
  }));

  // 4. SoD Checker
  app.post("/api/wave13/sod/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await w13.runSodCheck({ triggeredBy: u13(req) });
    await audit13(req, "WAVE13_SOD_CHECK", `sod_run:${r.runRef}`, { violations: r.violationsFound, passed: r.passed });
    res.json(r);
  }));
  app.get("/api/wave13/sod/rules", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    await w13.ensureDefaultSodRules();
    res.json(await w13.listSodRules());
  }));
  app.get("/api/wave13/sod/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listSodRuns());
  }));

  // 5. Sanctions Latency Benchmark — FU-019 RETIREMENT 2026-05-07.
  // POST returns HTTP 410 Gone with structured retirement body. GET /runs preserved
  // for read-only access to 36 historical receipts (immutability). See FOLLOW-UPS.md FU-019,
  // PLATFORM_BEHAVIOUR_NOTES.md (strict-(β) standard-application).
  app.post("/api/wave13/sanctions/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    await audit13(req, "WAVE13_SANCTIONS_RETIREMENT_INVOKED", "sanctions_retirement", { route: "POST /api/wave13/sanctions/run", retiredAt: "2026-05-07", fu: "FU-019" });
    return res.status(410).json({
      error: "Gone",
      code: "WAVE13_SANCTIONS_RETIRED",
      message: "Sanctions screening latency benchmark retired 2026-05-07 under FU-019. Schema fields (p50Ms/p95Ms/p99Ms, staleListsCount, hitsCount, listsChecked) describe a sanctions-screening operation against real upstream OFAC/UN/EU/UK/BoU-PEP list pulls. The platform's sanctions_lists registry contents are locally-stamped metadata rather than real upstream-pulled list data; substrate-substitution would have produced measurements in mismatched vocabulary. Real upstream-pull infrastructure deferred to a future programme cycle, not declined. 36 historical sanctions_screening_runs receipts retained per immutability and remain queryable at GET /api/wave13/sanctions/runs. See FOLLOW-UPS.md FU-019.",
      retiredAt: "2026-05-07",
      historical: { listEndpoint: "/api/wave13/sanctions/runs", retainedReceipts: 36 },
    });
  }));
  app.get("/api/wave13/sanctions/runs", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listSanctionsRuns());
  }));

  // 6. Vendor Register
  app.post("/api/wave13/vendor/register", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      vendorName: z13.string().min(1).max(192),
      serviceCategory: z13.string().min(1).max(64),
      criticality: z13.enum(["low", "medium", "high", "critical"]).optional(),
      country: z13.string().max(64).optional(),
      contractStart: z13.string().datetime().optional(),
      contractEnd: z13.string().datetime().optional(),
      exitClauseDocumented: z13.number().int().min(0).max(1).optional(),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.registerVendor({
      ...p.data,
      contractStart: p.data.contractStart ? new Date(p.data.contractStart) : null,
      contractEnd: p.data.contractEnd ? new Date(p.data.contractEnd) : null,
      registeredBy: u13(req),
    });
    await audit13(req, "WAVE13_VENDOR_REGISTER", `vendor:${r.vendorRef}`, { vendorName: r.vendorName, criticality: r.criticality });
    res.json(r);
  }));
  app.get("/api/wave13/vendor/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listVendors());
  }));
  app.post("/api/wave13/vendor/attestation", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      vendorRef: z13.string().min(1).max(64),
      attestationType: z13.string().min(1).max(64),
      validFrom: z13.string().datetime(),
      validUntil: z13.string().datetime(),
      attesterRef: z13.string().min(1).max(128),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.uploadVendorAttestation({
      ...p.data,
      validFrom: new Date(p.data.validFrom),
      validUntil: new Date(p.data.validUntil),
      uploadedBy: u13(req),
    });
    await audit13(req, "WAVE13_VENDOR_ATTESTATION", `vendor_attestation:${r.attestationRef}`, { vendorRef: r.vendorRef, type: r.attestationType });
    res.json(r);
  }));
  app.get("/api/wave13/vendor/attestations", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req, res) => {
    const vendorRef = typeof req.query.vendorRef === "string" ? req.query.vendorRef : undefined;
    res.json(await w13.listVendorAttestations(vendorRef));
  }));
  app.get("/api/wave13/vendor/summary", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.vendorRegisterSummary());
  }));

  // 7. MTTD/MTTR
  app.post("/api/wave13/mttr/record", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      threatClass: z13.string().min(1).max(64),
      occurredAt: z13.string().datetime({ offset: true }),
      detectedAt: z13.string().datetime({ offset: true }),
      containedAt: z13.string().datetime({ offset: true }),
      recoveredAt: z13.string().datetime({ offset: true }).optional(),
      severity: z13.enum(["low", "medium", "high", "critical"]).optional(),
      notes: z13.string().max(2000).optional(),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.recordMttr({
      ...p.data,
      occurredAt: new Date(p.data.occurredAt),
      detectedAt: new Date(p.data.detectedAt),
      containedAt: new Date(p.data.containedAt),
      recoveredAt: p.data.recoveredAt ? new Date(p.data.recoveredAt) : null,
      recordedBy: u13(req),
    });
    await audit13(req, "WAVE13_MTTR_RECORD", `mttr_record:${r.recordRef}`, { class: r.threatClass, mttd: r.mttdSeconds, mttr: r.mttrSeconds });
    res.json(r);
  }));
  app.get("/api/wave13/mttr/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listMttrRecords());
  }));
  app.get("/api/wave13/mttr/summary", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.mttrSummary());
  }));

  // 8. Full IR-Cycle Drill — REAL-WIRED 2026-05-06 (FU-011 silent-pass conv #2).
  //    runIrDrill drives a real incident through incident-SLA tracker;
  //    receipt fields trace to incident_slas via the new incident_ref column.
  //    Drill rows persist in incident_slas with explicit prefixes
  //    ("IR drill:" in title, "automated-drill-template:" in rootCause/resolution).
  app.post("/api/wave13/ir-drill/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({ scenario: z13.string().max(96).optional() });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.runIrDrill({ scenario: p.data.scenario, triggeredBy: u13(req) });
    await audit13(req, "WAVE13_IR_DRILL", `ir_drill:${r.drillRef}`, { scenario: r.scenario, totalMs: r.totalMs, passed: r.passed });
    res.json(r);
  }));
  app.get("/api/wave13/ir-drill/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listIrDrills());
  }));

  // 9. Break-Glass Drill
  app.post("/api/wave13/breakglass/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      primaryOfficer: z13.string().min(1).max(128),
      approverOfficer: z13.string().min(1).max(128),
      reason: z13.string().min(1).max(255),
      durationMinutes: z13.number().int().min(5).max(240).optional(),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    try {
      const r = await w13.runBreakglassDrill({ ...p.data, triggeredBy: u13(req) });
      await audit13(req, "WAVE13_BREAKGLASS_DRILL", `breakglass_drill:${r.drillRef}`, { primary: r.primaryOfficer, approver: r.approverOfficer, passed: r.passed });
      res.json(r);
    } catch (e: any) {
      res.status(400).json({ error: e?.message || "drill failed" });
    }
  }));
  app.get("/api/wave13/breakglass/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listBreakglassDrills());
  }));

  // 10. Network Segmentation — FU-020 RETIREMENT 2026-05-08 (FU-011 programme close-out).
  // POST returns HTTP 410 Gone with structured retirement body. GET /list preserved
  // for read-only access to 36 historical receipts (immutability). See FOLLOW-UPS.md FU-020.
  app.post("/api/wave13/segmentation/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    await audit13(req, "WAVE13_SEGMENTATION_RETIREMENT_INVOKED", "segmentation_retirement", { route: "POST /api/wave13/segmentation/run", retiredAt: "2026-05-08", fu: "FU-020" });
    return res.status(410).json({
      error: "Gone",
      code: "WAVE13_SEGMENTATION_RETIRED",
      message: "Network segmentation reachability matrix retired 2026-05-08 under FU-020 (FU-011 programme close-out). Schema vocabulary (pairsTested, expectedReachable, expectedBlocked, unexpectedReachable, unexpectedBlocked, passed, detailsJson per-pair results) describes a network-segmentation reachability matrix probed between separately-deployed architectural components. The platform's current Replit-hosted deployment runs as a single Node process against a single DATABASE_URL: the named components are not separate network entities, and the inter-component network boundaries the schema fields describe do not exist as network properties of the deployment. Substrate-substitution would have produced measurements in mismatched vocabulary. 36 historical segmentation_runs receipts retained per immutability and remain queryable at GET /api/wave13/segmentation/list. See FOLLOW-UPS.md FU-020.",
      retiredAt: "2026-05-08",
      historical: { listEndpoint: "/api/wave13/segmentation/list", retainedReceipts: 36 },
    });
  }));
  app.get("/api/wave13/segmentation/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listSegmentationRuns());
  }));

  // 11. Adversarial Examples — FU-018 RETIREMENT 2026-05-06.
  // POST returns HTTP 410 Gone with structured retirement body. GET /list preserved
  // for read-only access to 35 historical receipts (immutability). See FOLLOW-UPS.md FU-018.
  app.post("/api/wave13/adversarial/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    await audit13(req, "WAVE13_ADVERSARIAL_RETIREMENT_INVOKED", "adversarial_retirement", { route: "POST /api/wave13/adversarial/run", retiredAt: "2026-05-06", fu: "FU-018" });
    return res.status(410).json({
      error: "Gone",
      code: "WAVE13_ADVERSARIAL_RETIRED",
      message: "Adversarial example harness retired 2026-05-06 under FU-018. Schema vocabulary (robustAccuracyPct, meanPerturbationL2, attackKind enum [fgsm|pgd|boundary|feature-flip]) describes classical-ML adversarial robustness against a deployed differentiable model. Platform has no such model; substrate-substitution would have produced measurements in mismatched vocabulary. 35 historical adversarial_example_runs receipts retained per immutability and remain queryable at GET /api/wave13/adversarial/list. See FOLLOW-UPS.md FU-018.",
      retiredAt: "2026-05-06",
      historical: { listEndpoint: "/api/wave13/adversarial/list", retainedReceipts: 35 },
    });
  }));
  app.get("/api/wave13/adversarial/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listAdversarialExampleRuns());
  }));

  // 12. Model Card / Fairness
  app.post("/api/wave13/model-card/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      modelRef: z13.string().max(96).optional(),
      modelVersion: z13.string().max(32).optional(),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.runModelCardAudit({ ...p.data, triggeredBy: u13(req) });
    await audit13(req, "WAVE13_MODEL_CARD_AUDIT", `model_card:${r.auditRef}`, { model: r.modelRef, disparity: r.maxDisparityRatio, passed: r.passed });
    res.json(r);
  }));
  app.get("/api/wave13/model-card/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listModelCardAudits());
  }));

  // 13. SBOM + SLSA
  app.post("/api/wave13/sbom/generate", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({ buildRef: z13.string().max(96).optional() });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await w13.generateSbomAttestation({ ...p.data, triggeredBy: u13(req) });
    await audit13(req, "WAVE13_SBOM_GENERATE", `sbom_attestation:${r.attestationRef}`, { buildRef: r.buildRef, slsa: r.slsaLevel, components: r.componentCount });
    res.json(r);
  }));
  app.get("/api/wave13/sbom/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listSbomAttestations());
  }));

  // 14. EOL Inventory
  app.post("/api/wave13/eol/scan", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await w13.runEolScan({ triggeredBy: u13(req) });
    await audit13(req, "WAVE13_EOL_SCAN", `eol_run:${r.runRef}`, { eol: r.eolCount, nearEol: r.nearEolCount, passed: r.passed });
    res.json(r);
  }));
  app.get("/api/wave13/eol/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listEolRuns());
  }));

  // Master summary
  app.get("/api/wave13/summary", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.wave13Summary());
  }));

  // ─── Pilot Smoke Run ───
  app.post("/api/wave13/smoke/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await w13.runWave13PilotSmoke({ triggeredBy: u13(req) });
    await audit13(req, "WAVE13_SMOKE_RUN", r.smokeRef, { passed: r.passed, modulesPassed: r.modulesPassed, modulesFailed: r.modulesFailed, modulesErrored: r.modulesErrored, bundleHash: r.bundleHash });
    res.json(r);
  }));
  app.get("/api/wave13/smoke/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listSmokeRuns());
  }));
  // P4.3 Option A (FU-045) — expose FU-003-sanctioned expected-findings
  // register for the dashboard's per-module classification layer. Read-only;
  // seed is idempotent at boot. Future admin add/acknowledge endpoints can
  // be added when operator-driven additions are needed beyond the FU-003 trio.
  app.get("/api/wave13/expected-findings", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    const w13Expected = await import("./lib/wave13-expected-findings");
    res.json(await w13Expected.listExpectedFindings());
  }));

  // ─── Chaos Drills ───
  app.post("/api/wave13/chaos/network-partition/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const body = z13.object({ partitionType: z13.string().optional(), totalZones: z13.number().int().min(3).max(9).optional() }).parse(req.body || {});
    const r = await w13.runNetworkPartitionDrill({ triggeredBy: u13(req), ...body });
    await audit13(req, "WAVE13_CHAOS_NETWORK_PARTITION", r.drillRef, { passed: r.passed, partitionType: r.partitionType, affectedZones: r.affectedZones, totalZones: r.totalZones });
    res.json(r);
  }));
  app.get("/api/wave13/chaos/network-partition/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listNetworkPartitionDrills());
  }));
  app.post("/api/wave13/chaos/db-failover/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const body = z13.object({ primaryRegion: z13.string().optional(), failoverRegion: z13.string().optional(), rtoTargetSeconds: z13.number().int().positive().optional(), rpoTargetSeconds: z13.number().int().nonnegative().optional() }).parse(req.body || {});
    const r = await w13.runDbFailoverDrill({ triggeredBy: u13(req), ...body });
    await audit13(req, "WAVE13_CHAOS_DB_FAILOVER", r.drillRef, { passed: r.passed, rtoSeconds: r.rtoSeconds, rpoSeconds: r.rpoSeconds, primaryRegion: r.primaryRegion, failoverRegion: r.failoverRegion });
    res.json(r);
  }));
  app.get("/api/wave13/chaos/db-failover/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listDbFailoverDrills());
  }));
  app.post("/api/wave13/chaos/queue-backpressure/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const body = z13.object({ queueName: z13.string().optional(), injectedRatePerSec: z13.number().int().positive().optional(), consumerRatePerSec: z13.number().int().positive().optional(), durationMs: z13.number().int().positive().optional() }).parse(req.body || {});
    const r = await w13.runQueueBackpressureDrill({ triggeredBy: u13(req), ...body });
    await audit13(req, "WAVE13_CHAOS_QUEUE_BACKPRESSURE", r.drillRef, { passed: r.passed, peakDepth: r.peakDepth, deadletterCount: r.deadletterCount, queueName: r.queueName });
    res.json(r);
  }));
  app.get("/api/wave13/chaos/queue-backpressure/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await w13.listQueueBackpressureDrills());
  }));
  app.post("/api/wave13/chaos/run-all", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await w13.runAllChaosDrills({ triggeredBy: u13(req) });
    await audit13(req, "WAVE13_CHAOS_RUN_ALL", "all-drills", { passed: r.passed, np: r.networkPartition?.drillRef, db: r.dbFailover?.drillRef, qbp: r.queueBackpressure?.drillRef });
    res.json(r);
  }));

  // ============================================================
  // REGULATOR PILOT TIER A — Public Verifier + 3 Pilot Drills
  // ============================================================
  const tA = await import("./lib/regulator-pilot-tier-a");
  const auditTA = audit13; // reuse same audit helper
  const uTA = u13;

  // 1. PUBLIC bundle verifier — intentionally NO auth, NO CSRF.
  // The regulator must be able to verify any signed bundle without an account.
  // Each verification attempt is logged in bundle_verifications.
  app.post("/api/regulator/verify-bundle", asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      // Accept any JSON shape: object, array, primitive, or pre-canonical string.
      // Cap at ~2 MB raw via the body parser; signature must be 64 hex chars (sha256 HMAC) but allow 8..256 for forward-compat.
      payload: z13.union([
        z13.string().max(2_000_000),
        z13.record(z13.any()),
        z13.array(z13.any()),
        z13.number(),
        z13.boolean(),
        z13.null(),
      ]),
      signatureHex: z13.string().min(8).max(256).regex(/^[0-9a-fA-F]+$/, "must be hex"),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const ipRaw = getClientIp(req);
    const ipHash = ipRaw ? createHash("sha256").update(ipRaw).digest("hex").slice(0, 32) : null;
    const r = await tA.verifyBundle({
      payload: p.data.payload,
      signatureHex: p.data.signatureHex,
      ipHash,
      userAgent: (req.headers?.["user-agent"] || "").toString().slice(0, 1000),
    });
    res.json(r);
  }));
  app.get("/api/regulator/verify-bundle/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tA.listBundleVerifications());
  }));

  // 2. Audit-Chain Tamper Detection drill
  app.post("/api/regulator/audit-tamper/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tA.runAuditChainTamperDrill({ triggeredBy: uTA(req) });
    await auditTA(req, "REGULATOR_TIER_A_AUDIT_TAMPER", r.drillRef, { passed: r.passed, rowsScanned: r.rowsScanned, liveValid: r.liveValid, tamperDetected: r.tamperDetected });
    res.json(r);
  }));
  app.get("/api/regulator/audit-tamper/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tA.listAuditTamperDrills());
  }));

  // 3. Tenant Isolation Proof drill
  app.post("/api/regulator/tenant-isolation/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tA.runTenantIsolationDrill({ triggeredBy: uTA(req) });
    await auditTA(req, "REGULATOR_TIER_A_TENANT_ISOLATION", r.drillRef, { passed: r.passed, tenantsTested: r.tenantsTested, probesRun: r.probesRun, leaksFound: r.leaksFound });
    res.json(r);
  }));
  app.get("/api/regulator/tenant-isolation/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tA.listTenantIsolationDrills());
  }));

  // 4. Graceful-Degradation drills (3 sub-scenarios)
  app.post("/api/regulator/degradation/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tA.runDegradationDrills({ triggeredBy: uTA(req) });
    await auditTA(req, "REGULATOR_TIER_A_DEGRADATION", r.drillRef, { passed: r.passed, scenariosPassed: r.scenariosPassed, scenariosRun: r.scenariosRun });
    res.json(r);
  }));
  app.get("/api/regulator/degradation/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tA.listDegradationDrills());
  }));

  // 5. One-click run-all Tier A (3 drills)
  app.post("/api/regulator/tier-a/run-all", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tA.runAllTierADrills({ triggeredBy: uTA(req) });
    await auditTA(req, "REGULATOR_TIER_A_RUN_ALL", "tier-a-all", {
      allPassed: r.allPassed,
      auditTamper: r.results.auditTamper?.drillRef ?? null,
      tenantIsolation: r.results.tenantIsolation?.drillRef ?? null,
      degradation: r.results.degradation?.drillRef ?? null,
    });
    res.json(r);
  }));

  // ============================================================
  // REGULATOR PILOT TIER B — 6 additional drills + Pilot Pack ZIP +
  // public status + demo-pack snapshot test + pre-seeded regulator account
  // ============================================================
  const tB = await import("./lib/regulator-pilot-tier-b");
  const regSeed = await import("./lib/regulator-seed");
  // Best-effort, fire-and-forget. Doesn't block boot.
  regSeed.ensureRegulatorAccount().catch(() => {});

  // 1. Reproducibility / Determinism drill
  app.post("/api/regulator/tier-b/reproducibility/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({ iterations: z13.number().int().min(10).max(1000).optional() });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await tB.runReproducibilityDrill({ triggeredBy: u13(req), iterations: p.data.iterations });
    await audit13(req, "REGULATOR_TIER_B_REPRODUCIBILITY", r.drillRef, { passed: r.passed, iterations: r.iterations, uniqueScores: r.uniqueScores });
    res.json(r);
  }));
  app.get("/api/regulator/tier-b/reproducibility/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tB.listReproducibilityDrills());
  }));

  // 2. PII Egress Sentinel
  app.post("/api/regulator/tier-b/pii-egress/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tB.runPiiEgressDrill({ triggeredBy: u13(req) });
    await audit13(req, "REGULATOR_TIER_B_PII_EGRESS", r.drillRef, { passed: r.passed, channelsScanned: r.channelsScanned, leaksFound: r.leaksFound });
    res.json(r);
  }));
  app.get("/api/regulator/tier-b/pii-egress/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tB.listPiiEgressDrills());
  }));

  // 3. Backup-Restore drill
  app.post("/api/regulator/tier-b/backup-restore/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tB.runBackupRestoreDrill({ triggeredBy: u13(req) });
    await audit13(req, "REGULATOR_TIER_B_BACKUP_RESTORE", r.drillRef, { passed: r.passed, tablesChecked: r.tablesChecked, mismatches: r.rowMismatchCount });
    res.json(r);
  }));
  app.get("/api/regulator/tier-b/backup-restore/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tB.listBackupRestoreTierbDrills());
  }));

  // 4. Time-sync / NTP drift drill
  app.post("/api/regulator/tier-b/time-sync/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({ thresholdMs: z13.number().int().min(100).max(60000).optional() });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await tB.runTimeSyncDrill({ triggeredBy: u13(req), thresholdMs: p.data.thresholdMs });
    await audit13(req, "REGULATOR_TIER_B_TIME_SYNC", r.drillRef, { passed: r.passed, driftMs: r.driftMs });
    res.json(r);
  }));
  app.get("/api/regulator/tier-b/time-sync/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tB.listTimeSyncDrills());
  }));

  // 5. Key-rotation drill
  app.post("/api/regulator/tier-b/key-rotation/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tB.runKeyRotationDrill({ triggeredBy: u13(req) });
    await audit13(req, "REGULATOR_TIER_B_KEY_ROTATION", r.drillRef, { passed: r.passed, crossKeyForgeBlocked: r.crossKeyForgeBlocked });
    res.json(r);
  }));
  app.get("/api/regulator/tier-b/key-rotation/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tB.listKeyRotationTierbDrills());
  }));

  // 6. Rate-limit / DoS drill
  app.post("/api/regulator/tier-b/rate-limit/run", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const schema = z13.object({
      requests: z13.number().int().min(20).max(1000).optional(),
      endpoint: z13.string().min(1).max(256).optional(),
    });
    const p = schema.safeParse(req.body || {});
    if (!p.success) return res.status(400).json({ error: p.error.flatten() });
    const r = await tB.runRateLimitDrill({ triggeredBy: u13(req), requests: p.data.requests, endpoint: p.data.endpoint });
    await audit13(req, "REGULATOR_TIER_B_RATE_LIMIT", r.drillRef, { passed: r.passed, requestsSent: r.requestsSent, rateLimited: r.rateLimited });
    res.json(r);
  }));
  app.get("/api/regulator/tier-b/rate-limit/list", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (_req, res) => {
    res.json(await tB.listRateLimitDrills());
  }));

  // Tier B run-all (one click — all 6 drills in sequence)
  app.post("/api/regulator/tier-b/run-all", requireRole("admin", "risk_manager"), asyncHandler(async (req: any, res) => {
    const r = await tB.runAllTierBDrills({ triggeredBy: u13(req) });
    await audit13(req, "REGULATOR_TIER_B_RUN_ALL", "tier-b-all", {
      passed: r.summary.passed, failed: r.summary.failed, total: r.summary.total,
    });
    res.json(r);
  }));

  // PUBLIC status page API — no auth, returns ONLY aggregate counters.
  // Cached for 30 seconds via Cache-Control. Never includes payload data.
  app.get("/api/regulator/status", asyncHandler(async (_req, res) => {
    // DISABLED (honest-floor pass): PUBLIC no-auth endpoint served SYNTHETIC regulator-pilot (tier-B)
    // drill status. Public fabricated compliance status is uncontainable once scraped/cached. Disabled
    // until it serves REAL measured pilot results.
    res.status(503).json({ status: "unavailable", message: "Regulator pilot status is not yet available; it will return once it serves real, measured results." });
  }));

  // ─── Pilot Pack ZIP ─────────────────────────────────────────────────
  // A single download containing every signed receipt we have for the
  // pilot, plus the verifier CLI source and a README. Anyone with the
  // signing secret can run the CLI and verify every receipt.
  app.get("/api/regulator/pilot-pack.zip", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const archiver = (await import("archiver")).default;
    const fs = await import("fs/promises");
    const path = await import("path");
    const { sql } = await import("drizzle-orm");
    const { db } = await import("./db");

    // P3: parameterize value comparisons; validate identifier interpolations.
    const { safeIdentifier } = await import("./lib/sql-allowlist");

    const dumpJobs: Array<[string, string, string]> = [
      ["tierA_audit_tamper",       "audit_tamper_drills",         "tier-a/audit-tamper"],
      ["tierA_tenant_isolation",   "tenant_isolation_drills",     "tier-a/tenant-isolation"],
      ["tierA_degradation",        "degradation_drills",          "tier-a/degradation"],
      ["tierB_reproducibility",    "reproducibility_drills",      "tier-b/reproducibility"],
      ["tierB_pii_egress",         "pii_egress_drills",           "tier-b/pii-egress"],
      ["tierB_backup_restore",     "backup_restore_tierb_drills", "tier-b/backup-restore"],
      ["tierB_time_sync",          "time_sync_drills",            "tier-b/time-sync"],
      ["tierB_key_rotation",       "key_rotation_tierb_drills",   "tier-b/key-rotation"],
      ["tierB_rate_limit",         "rate_limit_drills",           "tier-b/rate-limit"],
      ["wave13_smoke",             "wave13_smoke_runs",           "wave13/smoke-runs"],
      ["chaos_network_partition",  "network_partition_drills",    "chaos/network-partition"],
      ["chaos_db_failover",        "db_failover_drills",          "chaos/db-failover"],
      ["chaos_queue_backpressure", "queue_backpressure_drills",   "chaos/queue-backpressure"],
    ];

    // FU-053 T001 Shape 3 — PREFETCH PHASE (bounded tenant DB). Every receipt
    // query runs HERE, on a short-lived pinned tenant connection, materialized
    // into memory BEFORE any streaming starts. The ZIP is then assembled and
    // streamed below with NO DB connection held — this is the route that
    // previously ran `db.execute(...)` row-by-row INSIDE the archive stream
    // (FU-053 Blocker 1: an in-stream query holds a pool client for the whole
    // ZIP build). Raw `db` is forbidden in this carved-out handler outside this
    // phase (loud throw via resolveRunner); the GUC is set on the querying
    // connection here so the receipt reads are RLS-ready for T003.
    //
    // COMPLETION-PHASE QUESTION FOR ARCHITECT: this materializes up to
    // 50 rows/table × 13 tables into memory before the stream starts — bounded
    // and small today, but a behavioral change vs. the prior in-stream read.
    // Flagged so any per-pack receipt-volume ceiling can be confirmed as the
    // pilot corpus grows.
    type Prefetched = { rows: any[]; tsCol: string; missing?: boolean; error?: string };
    const prefetched: Record<string, Prefetched> = await withTenantDbPhase(req, async () => {
      const out: Record<string, Prefetched> = {};
      for (const [, table] of dumpJobs) {
        try {
          const exists = await db.execute(sql`SELECT to_regclass(${table}) AS t`);
          if (!(exists.rows[0] as any)?.t) { out[table] = { rows: [], tsCol: "id", missing: true }; continue; }
          const tsR = await db.execute(sql`
            SELECT column_name FROM information_schema.columns
              WHERE table_schema='public' AND table_name=${table}
                AND column_name IN ('triggered_at','ran_at','generated_at','captured_at','logged_at','recorded_at','verified_at')
              ORDER BY CASE column_name
                WHEN 'triggered_at' THEN 1 WHEN 'ran_at' THEN 2 WHEN 'generated_at' THEN 3 ELSE 9 END
              LIMIT 1`);
          const tsCol = (tsR.rows[0] as any)?.column_name || "id";
          const r = await db.execute(sql.raw(`SELECT * FROM "${safeIdentifier(table)}" ORDER BY ${safeIdentifier(tsCol)} DESC LIMIT 50`));
          out[table] = { rows: r.rows as any[], tsCol };
        } catch (e: any) {
          out[table] = { rows: [], tsCol: "id", error: e?.message || String(e) };
        }
      }
      return out;
    });

    // FU-053 T001 CLOSEOUT — pilot-pack prefetch-size guardrail (architect
    // completion re-review #2 Q2, ratified 2026-05-29). Shape 3 materializes the
    // full receipt set into memory BEFORE streaming, so memory scales with pack
    // content. The architect ratified the materialize-before-stream pattern with
    // an explicit operational ceiling of <=20MB serialized prefetch, and named
    // the revisit conditions (per-table cap raised materially, or table-count /
    // payload growth pushing the prefetch toward tens of MB). This guardrail
    // ENFORCES that ratified ceiling — leaving it unenforced would document the
    // ceiling-as-agreed while letting the first oversized pack breach it silently.
    //
    // Enforcement shape (surfaced to architect at re-review #3, advisor lean):
    // SOFT by default — telemetry (logger.warn) + an operator-facing response
    // header + a warning file inside the pack — so a legitimately larger pack is
    // not broken in production. HARD enforcement (reject 413 BEFORE any byte of
    // the stream is sent) is available behind PILOT_PACK_PREFETCH_HARD_LIMIT=1
    // for environments that want the ceiling to be a real wall. Measured as the
    // byte length of the serialized materialized rows — the exact quantity that
    // scales with pilot-corpus growth.
    const PREFETCH_CEILING_BYTES = 20 * 1024 * 1024; // 20MB — architect Q2 answer
    const prefetchBytes = Buffer.byteLength(JSON.stringify(prefetched));
    const prefetchOverCeiling = prefetchBytes > PREFETCH_CEILING_BYTES;
    const prefetchHardLimit = process.env.PILOT_PACK_PREFETCH_HARD_LIMIT === "1";
    if (prefetchOverCeiling) {
      logger.warn("Pilot-pack prefetch exceeded operational ceiling", {
        metadata: {
          prefetchBytes,
          ceilingBytes: PREFETCH_CEILING_BYTES,
          enforcement: prefetchHardLimit ? "hard" : "soft",
          generatedBy: u13(req),
          fu: "FU-053 T001 Q2",
        },
      });
    }
    if (prefetchOverCeiling && prefetchHardLimit) {
      // Headers not yet sent — safe to reject cleanly before streaming starts.
      return res.status(413).json({
        error: "pilot_pack_prefetch_over_ceiling",
        message:
          "Pilot-pack prefetch exceeded the configured serialized-prefetch ceiling " +
          "(hard enforcement enabled). Reduce per-table receipt volume or split the pack.",
        prefetchBytes,
        ceilingBytes: PREFETCH_CEILING_BYTES,
      });
    }

    // ---- STREAMING PHASE (no DB connection held) ----
    if (prefetchOverCeiling) {
      // Soft enforcement: operator-facing signal that the ceiling was breached
      // without breaking pack generation.
      res.setHeader("X-Aegis-Prefetch-Warning", `prefetch=${prefetchBytes}B exceeds ceiling=${PREFETCH_CEILING_BYTES}B`);
    }
    const archive = archiver("zip", { zlib: { level: 9 } });
    res.setHeader("Content-Type", "application/zip");
    res.setHeader("Content-Disposition", `attachment; filename="aegis-pilot-pack-${Date.now()}.zip"`);
    archive.on("error", (err) => {
      // best-effort surface; archive will end the response.
      try { res.status(500).end(String(err)); } catch {}
    });
    archive.pipe(res);

    // Helper: pull the latest N receipt-bearing rows from a table and
    // emit one normalized bundle JSON per receipt: { payload, signatureHex, receiptHash }.
    // The `payload` is the EXACT shape the executor signed, reconstructed using the same
    // logic as /api/regulator/pilot-pack/verify-snapshot so the offline CLI can verify
    // every file with `node verify-bundle.cjs --pack <folder>`.
    //   • Tier A executors store the signed receipt verbatim in `details_json` (object with
    //     a string `drillRef`). We use it directly.
    //   • Tier B executors sign a `recordable` shape whose camelCase keys map 1:1 to the
    //     DB columns. We reconstruct by camelCasing every column except DB surrogates.
    //   • Other receipt tables (Wave-13 smoke, chaos drills) follow the same Tier B pattern.
    // Pure CPU: reads from the in-memory `prefetched` rows above and appends
    // bundle JSON to the archive. No DB access (raw `db` is forbidden in this
    // carved-out handler outside the prefetch phase).
    function dumpReceipts(table: string, folder: string) {
      try {
        const pre = prefetched[table];
        if (!pre || pre.missing) return { written: 0, signed: 0 };
        if (pre.error) {
          archive.append(`# error dumping ${table}: ${pre.error}\n`, { name: `${folder}/_error.txt` });
          return { written: 0, signed: 0 };
        }
        const tsCol = pre.tsCol;
        let n = 0;
        let signed = 0;
        for (const row of pre.rows) {
          const sigHex = (row as any).signature_hex;
          const rcptHash = (row as any).receipt_hash;
          let payload: any;
          const dj = (row as any).details_json;
          if (table === "wave13_smoke_runs") {
            // FU-001 option (c) — preferred path (landed 2026-05-02): if the
            // executor stored the exact canonical bytes it signed in
            // `signed_payload`, parse and use them verbatim. No
            // reconstruction, no shape-drift risk, no driver-format coercion
            // needed. Future bundle-shape changes cannot break verification
            // for receipts signed under (c).
            const sp = (row as any).signed_payload;
            if (sp && typeof sp === "string" && sp.length > 0) {
              try {
                payload = JSON.parse(sp);
              } catch {
                // Defensive: fall through to reconstruction if the column is
                // somehow corrupted. Reconstruction will still produce the
                // canonical shape for receipts signed under fix (a)+(b)+(b.2).
                payload = null;
              }
            }
            if (!payload) {
              // FU-001 fix (b): reconstruct the exact 10-field bundle that
              // runWave13PilotSmoke signed via canonicalize(). This branch is
              // taken for pre-(c) rows (signed_payload IS NULL). Field
              // declaration order does not matter — the verifier canonicalizes,
              // which sorts keys at every level. Receipts signed before the
              // FU-001 fix (pre-2026-05-02) used non-canonical signing AND a
              // different bundle shape; they will not verify even with this
              // reconstruction. They are retained as historical record per
              // immutability principle (see docs/regulatory/FOLLOW-UPS.md).
              const ta = (row as any).triggered_at;
              // FU-001 fix (b.2 — 2026-05-02): the Neon serverless driver
              // returns timestamp columns as Postgres text strings (e.g.
              // "2026-05-01 20:29:44.915+00") for sql.raw queries, NOT JS
              // Date objects. The executor signed with
              // new Date().toISOString() (e.g. "2026-05-01T20:29:44.915Z"),
              // so we coerce both shapes to that ISO form to match
              // bundleHash/signatureHex.
              const taIso = ta instanceof Date
                ? ta.toISOString()
                : new Date(String(ta)).toISOString();
              const djObj = (dj && typeof dj === "object" && !Array.isArray(dj)) ? dj : {};
              payload = {
                smokeRef:         (row as any).smoke_ref,
                triggeredAt:      taIso,
                triggeredBy:      (row as any).triggered_by,
                modulesAttempted: (row as any).modules_attempted,
                modulesPassed:    (row as any).modules_passed,
                modulesFailed:    (row as any).modules_failed,
                modulesErrored:   (row as any).modules_errored,
                durationMs:       (row as any).duration_ms,
                overallPass:      (row as any).passed === 1,
                results:          Array.isArray(djObj.results) ? djObj.results : [],
              };
            }
          } else if (dj && typeof dj === "object" && !Array.isArray(dj) && typeof dj.drillRef === "string") {
            payload = dj; // Tier A: use stored signed receipt verbatim.
          } else {
            // Tier B / other: reconstruct camelCase recordable shape from columns,
            // dropping only DB surrogates and signature fields.
            const skip = new Set(["signature_hex", "receipt_hash", "id", tsCol]);
            payload = {};
            for (const k of Object.keys(row)) {
              if (skip.has(k)) continue;
              const camel = k.replace(/_([a-z])/g, (_m, c) => c.toUpperCase());
              payload[camel] = (row as any)[k];
            }
          }
          const baseName = (row.drill_ref || row.id || row.smoke_run_ref || `row-${n}`)
            .toString().replace(/[^A-Za-z0-9_.-]/g, "_");
          const bundle: any = { payload };
          if (sigHex)   { bundle.signatureHex = sigHex; signed++; }
          if (rcptHash) { bundle.receiptHash  = rcptHash; }
          archive.append(JSON.stringify(bundle, null, 2), { name: `${folder}/${baseName}.json` });
          n++;
        }
        return { written: n, signed };
      } catch (e: any) {
        archive.append(`# error dumping ${table}: ${e?.message || e}\n`, { name: `${folder}/_error.txt` });
        return { written: 0, signed: 0 };
      }
    }

    const dumps: Record<string, { written: number; signed: number }> = {};
    for (const [key, table, folder] of dumpJobs) {
      dumps[key] = dumpReceipts(table, folder);
    }

    // Bundle the verifier CLI source so the regulator can verify offline.
    try {
      const cliPath = path.resolve(process.cwd(), "tools", "verify-bundle.cjs");
      const cliSrc = await fs.readFile(cliPath, "utf8");
      archive.append(cliSrc, { name: "tools/verify-bundle.cjs" });
    } catch (e: any) {
      archive.append(`# verify-bundle.cjs not found: ${e?.message || e}\n`, { name: "tools/_error.txt" });
    }

    // Manifest + README
    const totalSigned = Object.values(dumps).reduce((a, d) => a + d.signed, 0);
    const manifest = {
      generatedAt: new Date().toISOString(),
      generatedBy: u13(req),
      platform: "AEGIS CYBER",
      pilotJurisdiction: "Uganda — BoU/FIA/UCC sandbox",
      contents: dumps,
      totalSignedReceipts: totalSigned,
      receiptFormat: "{ payload, signatureHex, receiptHash } — HMAC-SHA256 over canonical JSON of payload",
      verifier: "tools/verify-bundle.cjs",
      verification: "Run `node tools/verify-bundle.cjs --bundle <file>.json` (single) or `--pack <folder>` (every JSON in a folder). Both modes fail with exit 1 if any signature mismatches OR if zero signed receipts are found.",
    };
    archive.append(JSON.stringify(manifest, null, 2), { name: "MANIFEST.json" });
    archive.append([
      "AEGIS CYBER — Regulator Pilot Pack",
      "===================================",
      "",
      "This archive contains every signed evidence receipt for the BoU sandbox pilot,",
      "organized by tier:",
      "",
      "  tier-a/   — Public Verifier, Audit-Chain Tamper, Tenant Isolation, Degradation",
      "  tier-b/   — Reproducibility, PII Egress, Backup-Restore, Time-Sync, Key-Rotation, Rate-Limit",
      "  wave13/   — Master smoke runs (14 modules each)",
      "  chaos/    — Network-Partition, DB-Failover, Queue-Backpressure",
      "  tools/    — Pure-Node verifier CLI",
      "",
      "Receipt file format:",
      "  Each .json file in a tier-*/chaos-*/wave13-* subfolder is a 'bundle' shaped:",
      "    { \"payload\": { ... }, \"signatureHex\": \"<hex>\", \"receiptHash\": \"<hex>\" }",
      "  The payload is the EXACT object the server canonicalized + HMAC'd at the time the",
      "  drill ran. The CLI re-canonicalizes the payload and recomputes the HMAC.",
      "",
      "Verifying a single bundle:",
      "  node tools/verify-bundle.cjs --bundle tier-b/reproducibility/REPRO-XXXX.json",
      "",
      "Verifying every bundle in a folder:",
      "  node tools/verify-bundle.cjs --pack tier-b/reproducibility/",
      "  (Exits 1 if any signature is invalid OR if zero verifiable bundles were found.)",
      "",
      "Verifying every bundle in the pack (recursive):",
      "  for d in tier-a/*/ tier-b/*/ wave13/*/ chaos/*/; do",
      "    node tools/verify-bundle.cjs --pack \"$d\" || exit 1",
      "  done",
      "",
      "Secret resolution (CLI side):",
      "  --secret <hex> | AEGIS_VERIFY_SECRET | WAVE10_SIGNING_SECRET | SESSION_SECRET (derived)",
      "",
      "HMAC: SHA-256 over canonical JSON of the payload (keys sorted at every level,",
      "undefined-valued keys skipped). The verifier reproduces that byte-for-byte.",
      "",
    ].join("\n"), { name: "README.txt" });

    // FU-053 T001 Q2 soft-enforcement: in-pack warning when the prefetch breached
    // the ratified operational ceiling. Present alongside the X-Aegis-Prefetch-
    // Warning header so the breach is visible both to the requesting client and
    // to anyone opening the pack later.
    if (prefetchOverCeiling) {
      archive.append([
        "PREFETCH SIZE WARNING",
        "=====================",
        "",
        `This pilot pack's serialized prefetch was ${prefetchBytes} bytes, which`,
        `exceeds the ratified operational ceiling of ${PREFETCH_CEILING_BYTES} bytes`,
        "(FU-053 T001 architect re-review #2 Q2, 2026-05-29).",
        "",
        "The pack was still generated (soft enforcement). If this recurs, the",
        "design must be revisited per the architect's named revisit conditions:",
        "per-table receipt cap raised materially, or table-count / payload growth",
        "pushing the materialize-before-stream prefetch toward tens of MB. Hard",
        "enforcement (reject with 413) can be enabled via PILOT_PACK_PREFETCH_HARD_LIMIT=1.",
        "",
      ].join("\n"), { name: "_PREFETCH_WARNING.txt" });
    }

    await archive.finalize();
  }));

  // Pilot Pack snapshot self-test — generates the pack in-memory, parses it
  // back, and verifies every embedded HMAC. Returns pass/fail + per-folder
  // counts. Used by automated tests and by the dashboard's "Self-Test" button.
  app.post("/api/regulator/pilot-pack/verify-snapshot", requireRole("admin", "risk_manager", "auditor"), asyncHandler(async (req: any, res) => {
    const archiver = (await import("archiver")).default;
    const { sql } = await import("drizzle-orm");
    const { db } = await import("./db");
    const { canonicalize } = tB;
    const crypto2 = await import("crypto");

    // Same secret derivation the executors use.
    function deriveSecret(): string {
      const w = process.env.WAVE10_SIGNING_SECRET;
      if (typeof w === "string" && w.length >= 32) return w;
      const seed = process.env.SESSION_SECRET || "";
      if (seed.length < 16) throw new Error("no signing secret");
      return crypto2.createHash("sha256").update("aegis-wave-signing:v1:" + seed).digest("hex");
    }
    const SECRET = deriveSecret();

    // Build an in-memory pack (we just verify receipts; no need to write a file).
    const tables: Array<[string, string]> = [
      ["audit_tamper_drills",         "tier-a/audit-tamper"],
      ["tenant_isolation_drills",     "tier-a/tenant-isolation"],
      ["degradation_drills",          "tier-a/degradation"],
      ["reproducibility_drills",      "tier-b/reproducibility"],
      ["pii_egress_drills",           "tier-b/pii-egress"],
      ["backup_restore_tierb_drills", "tier-b/backup-restore"],
      ["time_sync_drills",            "tier-b/time-sync"],
      ["key_rotation_tierb_drills",   "tier-b/key-rotation"],
      ["rate_limit_drills",           "tier-b/rate-limit"],
    ];
    const perFolder: Record<string, { found: number; valid: number; invalid: number; skipped: number }> = {};
    let totalFound = 0, totalValid = 0, totalInvalid = 0;
    for (const [tbl, folder] of tables) {
      perFolder[folder] = { found: 0, valid: 0, invalid: 0, skipped: 0 };
      try {
        // P3: parameterize value comparisons; validate identifier interpolations.
        const { safeIdentifier } = await import("./lib/sql-allowlist");
        const exists = await db.execute(sql`SELECT to_regclass(${tbl}) AS t`);
        if (!(exists.rows[0] as any)?.t) { perFolder[folder].skipped = 1; continue; }
        // Use triggered_at for chronological ordering — id is `serial` for Tier B but
        // varchar/uuid for Tier A, where lex-sort doesn't reflect insert order.
        const r = await db.execute(sql.raw(`SELECT * FROM "${safeIdentifier(tbl)}" ORDER BY triggered_at DESC LIMIT 25`));
        for (const row of (r.rows as any[])) {
          const sigHex = (row as any).signature_hex;
          if (!sigHex) { perFolder[folder].skipped++; continue; }
          // Reconstruct the EXACT payload the executor signed.
          //   • Tier A executors sign a payload that includes a JS-generated `triggeredAt` ISO
          //     string and uses different field names than the DB columns (e.g. `liveValid` vs
          //     column `live_chain_valid`). They store that signed payload verbatim in
          //     `details_json`, so we use it directly.
          //   • Tier B executors sign a `recordable` shape whose camelCase keys map 1:1 to the
          //     DB columns; their `details_json` is supplemental, so we reconstruct from columns.
          let payload: any;
          const dj = (row as any).details_json;
          if (dj && typeof dj === "object" && !Array.isArray(dj) && typeof dj.drillRef === "string") {
            payload = dj;
          } else {
            // Tier B: signed `recordable` shape ≈ DB columns + detailsJson; drop only DB
            // surrogates and signature fields.
            const skip = new Set(["signature_hex", "receipt_hash", "id", "triggered_at"]);
            payload = {};
            for (const k of Object.keys(row)) {
              if (skip.has(k)) continue;
              const camel = k.replace(/_([a-z])/g, (_m, c) => c.toUpperCase());
              payload[camel] = (row as any)[k];
            }
          }
          const canon = canonicalize(payload);
          const expected = crypto2.createHmac("sha256", SECRET).update(canon).digest("hex");
          const sigStr = String(sigHex);
          let valid = false;
          try {
            valid = expected.length === sigStr.length &&
                    crypto2.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(sigStr, "hex"));
          } catch { valid = false; }
          perFolder[folder].found++;
          totalFound++;
          if (valid) { perFolder[folder].valid++; totalValid++; }
          else       { perFolder[folder].invalid++; totalInvalid++; }
        }
      } catch (e: any) {
        perFolder[folder].skipped++;
      }
    }

    // Also sanity-check that the ZIP archiver actually produces a valid ZIP
    // header (so the download endpoint isn't silently broken).
    const zipHead: Buffer = await new Promise((resolve, reject) => {
      const a = archiver("zip", { zlib: { level: 0 } });
      const chunks: Buffer[] = [];
      a.on("data", (c: Buffer) => chunks.push(c));
      a.on("end", () => resolve(Buffer.concat(chunks)));
      a.on("error", reject);
      a.append("hello", { name: "smoke.txt" });
      a.finalize();
    });
    const zipMagic = zipHead.length >= 4 && zipHead[0] === 0x50 && zipHead[1] === 0x4b;
    const expectedFolders = tables.map(([_, f]) => f);
    const passed = totalInvalid === 0 && totalFound > 0 && zipMagic ? 1 : 0;
    await audit13(req, "REGULATOR_PILOT_PACK_SNAPSHOT", "verify-snapshot", { passed, totalFound, totalValid, totalInvalid });
    res.json({
      passed,
      summary: { totalFound, totalValid, totalInvalid },
      perFolder,
      expectedFolders,
      zipMagicOk: zipMagic,
    });
  }));

  // ─── T003 Option A: RLS enforcement diagnostic ──────────────────────────────
  // PERMANENT INFRASTRUCTURE — Rule 17 (2026-06-04). Do NOT remove this route or buildAppConnectionString.
  // Rule 9 architect PASS cycle 2 (2026-06-04). Re-running is mandatory after any change to
  // RLS policies, grants, roles, or current_tenant_id().
  // Two-layer protection: admin session + RLS_DIAGNOSTIC_ENABLED env flag (404 if absent/not "true").
  // Flag management: set RLS_DIAGNOSTIC_ENABLED=true in Secrets to enable; remove/unset to flag-off (route stays deployed).
  // See docs/regulatory/T003_OPTION_A_DESIGN_BRIEF.md §10.
  app.post(
    "/api/internal/rls-diagnostic",
    requireRole("admin"),
    asyncHandler(async (req, res) => {
      if (process.env.RLS_DIAGNOSTIC_ENABLED !== "true") {
        return res.status(404).json(createErrorResponse("AEGIS_ERR_001", { path: req.path }));
      }

      const diagLogger = logger.child("rls-diagnostic");
      const invoker = req.session.userId ?? "unknown";

      if (rlsDiagnosticRunning) {
        diagLogger.warn(`REJECTED already-running invoker=${invoker}`);
        return res.status(409).json({ error: "A diagnostic run is already in progress" });
      }
      rlsDiagnosticRunning = true;

      const runId = `t003-diag-${Date.now()}`;
      const PROBE_PREFIX = runId;
      const startMs = Date.now();

      const probeResults: Array<{
        probe: string;
        result: "PASS" | "FAIL";
        detail?: string;
        cleanupFailed?: boolean;
      }> = [];
      const residuals: Array<{ table: string; id: string | number }> = [];
      let probesPassed = 0;
      let probesFailed = 0;
      let cleanupFailures = 0;

      function pass(probe: string): void {
        probesPassed++;
        probeResults.push({ probe, result: "PASS" });
      }
      function fail(probe: string, detail: string): void {
        probesFailed++;
        probeResults.push({ probe, result: "FAIL", detail });
      }
      function cleanupErr(table: string, id: string | number): void {
        cleanupFailures++;
        residuals.push({ table, id });
        if (probeResults.length > 0) {
          probeResults[probeResults.length - 1].cleanupFailed = true;
        }
      }

      const { Pool } = pg;
      const ephemeralAppPool = new Pool({ connectionString: buildAppConnectionString() });

      diagLogger.info(
        `START runId=${runId} invoker=${invoker} ip=${req.ip ?? "unknown"}`,
      );

      try {
        // === PROBES 1 / 2 / 3 — CLASS 1 + CLASS 3 (incident_slas) ===
        let incidentSlaId: number | null = null;
        {
          const suC = await ddlPool.connect();
          try {
            const seedR = await suC.query<{ id: number }>(
              `INSERT INTO incident_slas
                 (tenant_id, incident_id, severity, title, status,
                  sla_target_minutes, escalation_level, is_sla_breached, created_at)
               VALUES ($1, $2, 'critical', 'T003 Probe', 'open', 240, 0, false, NOW())
               RETURNING id`,
              [`${PROBE_PREFIX}-A`, `${PROBE_PREFIX}-inc-001`],
            );
            incidentSlaId = seedR.rows[0].id;
          } catch (e: any) {
            fail("Probe 1 — CLASS1 enforcement", `Seed failed: ${e?.message ?? e}`);
            fail("Probe 2 — CLASS1 isolation", `Seed failed: ${e?.message ?? e}`);
            fail("Probe 3 — CLASS3 §13.0 fail-closed (empty-string)", `Seed failed: ${e?.message ?? e}`);
          } finally {
            suC.release();
          }
        }

        if (incidentSlaId !== null) {
          const appC = await ephemeralAppPool.connect();
          try {
            // Probe 1 — CLASS 1: correct GUC → own-tenant row visible
            try {
              await appC.query("BEGIN");
              await appC.query(
                "SELECT set_config('app.current_tenant_id', $1, true)",
                [`${PROBE_PREFIX}-A`],
              );
              const r1 = await appC.query<{ id: number }>(
                "SELECT id FROM incident_slas WHERE id = $1",
                [incidentSlaId],
              );
              await appC.query("COMMIT");
              if (r1.rows.length === 1) {
                pass("Probe 1 — CLASS1 enforcement: own-tenant row visible (GUC matches)");
              } else {
                fail("Probe 1 — CLASS1 enforcement", `Expected 1 row, got ${r1.rows.length}`);
              }
            } catch (e: any) {
              await appC.query("ROLLBACK").catch(() => {});
              fail("Probe 1 — CLASS1 enforcement", `Threw: ${e?.message ?? e}`);
            }

            // Probe 2 — CLASS 1: wrong GUC → 0 rows
            try {
              await appC.query("BEGIN");
              await appC.query(
                "SELECT set_config('app.current_tenant_id', $1, true)",
                [`${PROBE_PREFIX}-B`],
              );
              const r2 = await appC.query<{ id: number }>(
                "SELECT id FROM incident_slas WHERE id = $1",
                [incidentSlaId],
              );
              await appC.query("COMMIT");
              if (r2.rows.length === 0) {
                pass("Probe 2 — CLASS1 isolation: 0 rows (wrong tenant GUC)");
              } else {
                fail("Probe 2 — CLASS1 isolation", `Expected 0 rows, got ${r2.rows.length}`);
              }
            } catch (e: any) {
              await appC.query("ROLLBACK").catch(() => {});
              fail("Probe 2 — CLASS1 isolation", `Threw: ${e?.message ?? e}`);
            }

            // Probe 3 — CLASS 3: empty-string GUC → 0 rows (§13.0 fail-closed)
            try {
              await appC.query("BEGIN");
              await appC.query("SELECT set_config('app.current_tenant_id', '', true)");
              const r3 = await appC.query<{ id: number }>(
                "SELECT id FROM incident_slas WHERE id = $1",
                [incidentSlaId],
              );
              await appC.query("COMMIT");
              if (r3.rows.length === 0) {
                pass("Probe 3 — CLASS3 §13.0 fail-closed (empty-string GUC → 0 rows)");
              } else {
                fail(
                  "Probe 3 — CLASS3 §13.0 fail-closed (empty-string)",
                  `Expected 0 rows, got ${r3.rows.length}`,
                );
              }
            } catch (e: any) {
              await appC.query("ROLLBACK").catch(() => {});
              fail("Probe 3 — CLASS3 §13.0 fail-closed (empty-string)", `Threw: ${e?.message ?? e}`);
            }
          } finally {
            appC.release();
          }
        }

        // Probe 9 — CLASS 3: NEVER-SET GUC (fresh connection, no set_config at all)
        if (incidentSlaId === null) {
          fail(
            "Probe 9 — CLASS3 §13.0 fail-closed (NEVER-SET GUC)",
            "Skipped: incident_slas seed row was not created",
          );
        } else {
          const appC9 = await ephemeralAppPool.connect();
          try {
            const r9 = await appC9.query<{ id: number }>(
              "SELECT id FROM incident_slas WHERE id = $1",
              [incidentSlaId],
            );
            if (r9.rows.length === 0) {
              pass(
                "Probe 9 — CLASS3 §13.0 fail-closed (NEVER-SET GUC: no set_config called → 0 rows)",
              );
            } else {
              fail(
                "Probe 9 — CLASS3 §13.0 fail-closed (NEVER-SET)",
                `Expected 0 rows, got ${r9.rows.length} — never-set GUC does NOT fail-closed`,
              );
            }
          } catch (e: any) {
            fail("Probe 9 — CLASS3 §13.0 fail-closed (NEVER-SET)", `Threw: ${e?.message ?? e}`);
          } finally {
            appC9.release();
          }
        }

        // Cleanup probes 1/2/3/9 seed row (strict — residuals on failure)
        if (incidentSlaId !== null) {
          try {
            await ddlPool.query("DELETE FROM incident_slas WHERE id = $1", [incidentSlaId]);
          } catch {
            cleanupErr("incident_slas", incidentSlaId);
          }
        }

        // === PROBE 4 — CLASS 2: cross-tenant isolation (dsar_requests) ===
        {
          const suC = await ddlPool.connect();
          const appC = await ephemeralAppPool.connect();
          let dsarIdA: string | null = null;
          let dsarIdB: string | null = null;
          try {
            const deadline = new Date(Date.now() + 30 * 24 * 3600 * 1000).toISOString();
            const r4a = await suC.query<{ id: string }>(
              `INSERT INTO dsar_requests
                 (tenant_id, reference, subject_name, subject_email, request_type,
                  request_channel, sla_deadline, status, received_at, created_at, updated_at)
               VALUES ($1, $2, 'Alice Probe', 'alice@probe.t3st', 'access',
                       'portal', $3, 'received', NOW(), NOW(), NOW())
               RETURNING id`,
              [`${PROBE_PREFIX}-A`, `${PROBE_PREFIX}-DSAR-A`, deadline],
            );
            const r4b = await suC.query<{ id: string }>(
              `INSERT INTO dsar_requests
                 (tenant_id, reference, subject_name, subject_email, request_type,
                  request_channel, sla_deadline, status, received_at, created_at, updated_at)
               VALUES ($1, $2, 'Bob Probe', 'bob@probe.t3st', 'access',
                       'portal', $3, 'received', NOW(), NOW(), NOW())
               RETURNING id`,
              [`${PROBE_PREFIX}-B`, `${PROBE_PREFIX}-DSAR-B`, deadline],
            );
            dsarIdA = r4a.rows[0].id;
            dsarIdB = r4b.rows[0].id;

            await appC.query("BEGIN");
            await appC.query(
              "SELECT set_config('app.current_tenant_id', $1, true)",
              [`${PROBE_PREFIX}-A`],
            );
            const seenByA = await appC.query<{ id: string }>(
              "SELECT id FROM dsar_requests WHERE id = ANY($1)",
              [[dsarIdA, dsarIdB]],
            );
            await appC.query("COMMIT");

            if (seenByA.rows.length === 1 && seenByA.rows[0].id === dsarIdA) {
              pass("Probe 4 — CLASS2 cross-tenant isolation: tenant-A sees only idA, not idB");
            } else if (seenByA.rows.length === 2) {
              fail(
                "Probe 4 — CLASS2 cross-tenant isolation",
                "tenant-A context returned BOTH rows — cross-tenant leak",
              );
            } else if (seenByA.rows.length === 0) {
              fail(
                "Probe 4 — CLASS2 cross-tenant isolation",
                "tenant-A context returned 0 rows — RLS is over-blocking own-tenant rows",
              );
            } else {
              fail(
                "Probe 4 — CLASS2 cross-tenant isolation",
                `Unexpected: ${seenByA.rows.length} rows`,
              );
            }
          } catch (e: any) {
            await appC.query("ROLLBACK").catch(() => {});
            fail("Probe 4 — CLASS2 cross-tenant isolation", `Threw: ${e?.message ?? e}`);
          } finally {
            appC.release();
            const ids4 = [dsarIdA, dsarIdB].filter(Boolean) as string[];
            if (ids4.length > 0) {
              try {
                await suC.query("DELETE FROM dsar_requests WHERE id = ANY($1)", [ids4]);
              } catch {
                for (const id of ids4) cleanupErr("dsar_requests", id);
              }
            }
            suC.release();
          }
        }

        // === PROBE 5 — CLASS 3: kyt_results empty-string GUC ===
        {
          const suC = await ddlPool.connect();
          const appC = await ephemeralAppPool.connect();
          const kytProbeId = `${PROBE_PREFIX}-kyt`;
          let kytSeeded = false;
          try {
            await suC.query(
              `INSERT INTO kyt_results
                 (id, tenant_id, user_id, amount, currency, recipient_type, channel,
                  risk_level, risk_score, risk_factors, recommendation, required_verification, scored_at)
               VALUES ($1, $2, 'probe-user', 1000, 'UGX', 'individual', 'mobile',
                       'critical', 0.95, '[]', 'block', '[]', NOW())`,
              [kytProbeId, `${PROBE_PREFIX}-FC`],
            );
            kytSeeded = true;

            await appC.query("BEGIN");
            await appC.query("SELECT set_config('app.current_tenant_id', '', true)");
            const r5 = await appC.query<{ id: string }>(
              "SELECT id FROM kyt_results WHERE id = $1",
              [kytProbeId],
            );
            await appC.query("COMMIT");
            if (r5.rows.length === 0) {
              pass("Probe 5 — CLASS3 §13.0 fail-closed (kyt_results, empty-string GUC → 0 rows)");
            } else {
              fail(
                "Probe 5 — CLASS3 §13.0 fail-closed (kyt_results)",
                `Expected 0 rows, got ${r5.rows.length}`,
              );
            }
          } catch (e: any) {
            await appC.query("ROLLBACK").catch(() => {});
            fail("Probe 5 — CLASS3 §13.0 fail-closed (kyt_results)", `Threw: ${e?.message ?? e}`);
          } finally {
            appC.release();
            if (kytSeeded) {
              try {
                await suC.query("DELETE FROM kyt_results WHERE id = $1", [kytProbeId]);
              } catch {
                cleanupErr("kyt_results", kytProbeId);
              }
            }
            suC.release();
          }
        }

        // === PROBES 6 / 7 / 8 — CLASS 4: audit_chain_entries DML denial (Option B) ===
        {
          const suC = await ddlPool.connect();
          const appC = await ephemeralAppPool.connect();
          let auditChainSeedId: number | null = null;
          try {
            // Probe 6 — aegis_app INSERT denied (42501)
            let insertDenied = false;
            try {
              await appC.query(
                `INSERT INTO audit_chain_entries
                   (hash, previous_hash, action, user_id, resource, details,
                    created_at, source_audit_id, entry_timestamp)
                 VALUES ('probe-h', 'probe-ph', 'T003_PROBE',
                         'probe-u', 'probe-r', '{}', NOW(), 999, NOW())`,
              );
            } catch (e: any) {
              if (e?.code === "42501") {
                insertDenied = true;
              } else {
                throw e;
              }
            }
            if (insertDenied) {
              pass("Probe 6 — CLASS4 audit-chain INSERT denied (42501 insufficient_privilege)");
            } else {
              fail(
                "Probe 6 — CLASS4 audit-chain INSERT",
                "INSERT SUCCEEDED — Option B REVOKE not in force; aegis_app can write audit chain",
              );
            }

            // Seed a row for probe 7 (DELETE) and probe 8 (SELECT)
            const seedA6 = await suC.query<{ id: number }>(
              `INSERT INTO audit_chain_entries
                 (hash, previous_hash, action, user_id, resource, details,
                  created_at, source_audit_id, entry_timestamp)
               VALUES ('probe-del-h', 'probe-del-ph', 'T003_PROBE_DEL',
                       'probe-u', 'probe-r', '{}', NOW(), 999, NOW())
               RETURNING id`,
            );
            auditChainSeedId = seedA6.rows[0].id;

            // Probe 7 — aegis_app DELETE denied (42501)
            let deleteDenied = false;
            try {
              await appC.query(
                "DELETE FROM audit_chain_entries WHERE id = $1",
                [auditChainSeedId],
              );
            } catch (e: any) {
              if (e?.code === "42501") {
                deleteDenied = true;
              } else {
                throw e;
              }
            }
            if (deleteDenied) {
              pass("Probe 7 — CLASS4 audit-chain DELETE denied (42501 insufficient_privilege)");
            } else {
              fail(
                "Probe 7 — CLASS4 audit-chain DELETE",
                "DELETE SUCCEEDED — Option B REVOKE not in force; aegis_app can delete audit chain rows",
              );
            }

            // Probe 8 — aegis_app SELECT allowed (read path intact)
            const r8 = await appC.query<{ id: number }>(
              "SELECT id FROM audit_chain_entries WHERE id = $1",
              [auditChainSeedId],
            );
            if (r8.rows.length === 1) {
              pass("Probe 8 — CLASS4 audit-chain SELECT allowed (Option B read path intact)");
            } else {
              fail(
                "Probe 8 — CLASS4 audit-chain SELECT",
                `Expected 1 row, got ${r8.rows.length} — SELECT is unexpectedly blocked`,
              );
            }
          } catch (e: any) {
            fail("Probes 6/7/8 — CLASS4 group", `Threw: ${e?.message ?? e}`);
          } finally {
            appC.release();
            if (auditChainSeedId !== null) {
              try {
                await suC.query(
                  "DELETE FROM audit_chain_entries WHERE id = $1",
                  [auditChainSeedId],
                );
              } catch {
                cleanupErr("audit_chain_entries", auditChainSeedId);
              }
            }
            suC.release();
          }
        }

        // === PROBE 10 — CLASS 5: backup_records SYSTEM-EXEMPT verification ===
        // F-RP-07 (2026-06-20): backup_records is no longer a TENANT_TABLE — it is
        // a documented system-exempt table (RLS DISABLED, no policy). This probe
        // verifies BOTH that the exemption is real (relrowsecurity=false, 0
        // policies) AND that the system-scope write path still functions. A bare
        // "insert succeeded" while RLS was silently re-enabled would be a
        // hollow-green (Rule 18) — so the catalog state is asserted alongside.
        {
          const appC = await ephemeralAppPool.connect();
          const suC = await ddlPool.connect();
          let probeBackupId: string | null = null;
          try {
            const exemptState = await suC.query<{
              relrowsecurity: boolean;
              policy_count: string;
            }>(
              `SELECT c.relrowsecurity,
                      (SELECT count(*) FROM pg_policy p WHERE p.polrelid = c.oid) AS policy_count
               FROM pg_class c
               JOIN pg_namespace n ON n.oid = c.relnamespace
               WHERE n.nspname = 'public' AND c.relname = 'backup_records'`,
            );
            const es = exemptState.rows[0];
            const rlsDisabled =
              !!es && es.relrowsecurity === false && Number(es.policy_count) === 0;

            await appC.query("BEGIN");
            await appC.query("SET LOCAL ROLE aegis_rls_bypass");
            const rBk = await appC.query<{ id: string }>(
              `INSERT INTO backup_records (backup_type, status, retention_days, created_at)
               VALUES ('full', 'in_progress', 90, NOW())
               RETURNING id`,
            );
            await appC.query("COMMIT");
            if (rBk.rows.length === 1 && rlsDisabled) {
              probeBackupId = rBk.rows[0].id;
              pass(
                "Probe 10 — CLASS5 backup_records SYSTEM-EXEMPT verified (relrowsecurity=false, 0 policies) + system-scope write path functions (BACKUP-SYS, F-RP-07)",
              );
            } else if (rBk.rows.length === 1 && !rlsDisabled) {
              probeBackupId = rBk.rows[0].id;
              fail(
                "Probe 10 — CLASS5 backup_records system-exempt",
                `Write succeeded but exemption NOT verified (relrowsecurity=${es?.relrowsecurity}, policies=${es?.policy_count}; want false/0) — hollow-green guard`,
              );
            } else {
              fail(
                "Probe 10 — CLASS5 backup_records system-exempt",
                "Expected 1 row returned, got 0",
              );
            }
          } catch (e: any) {
            await appC.query("ROLLBACK").catch(() => {});
            fail("Probe 10 — CLASS5 backup_records system-exempt", `Threw: ${e?.message ?? e}`);
          } finally {
            appC.release();
            if (probeBackupId !== null) {
              try {
                await suC.query("DELETE FROM backup_records WHERE id = $1", [probeBackupId]);
              } catch {
                cleanupErr("backup_records", probeBackupId);
              }
            }
            suC.release();
          }
        }

        // === PROBE 11 — CLASS 2: DSAR cross-tenant isolation (PDPO-critical) ===
        {
          const suC = await ddlPool.connect();
          const appCa = await ephemeralAppPool.connect();
          const appCb = await ephemeralAppPool.connect();
          let probeIdA: string | null = null;
          let probeIdB: string | null = null;
          try {
            const seedA11 = await suC.query<{ id: string }>(
              `INSERT INTO dsar_requests
                 (reference, tenant_id, subject_name, subject_email, request_type,
                  request_channel, received_at, sla_deadline, status, created_at, updated_at)
               VALUES ($1, $2, 'Probe A', 'probe-a@test.invalid', 'erasure',
                       'portal', NOW(), NOW() + INTERVAL '30 days', 'received', NOW(), NOW())
               RETURNING id`,
              [`${PROBE_PREFIX}-dsar-a`, `${PROBE_PREFIX}-dsar-tenant-a`],
            );
            probeIdA = seedA11.rows[0].id;
            const seedB11 = await suC.query<{ id: string }>(
              `INSERT INTO dsar_requests
                 (reference, tenant_id, subject_name, subject_email, request_type,
                  request_channel, received_at, sla_deadline, status, created_at, updated_at)
               VALUES ($1, $2, 'Probe B', 'probe-b@test.invalid', 'erasure',
                       'portal', NOW(), NOW() + INTERVAL '30 days', 'received', NOW(), NOW())
               RETURNING id`,
              [`${PROBE_PREFIX}-dsar-b`, `${PROBE_PREFIX}-dsar-tenant-b`],
            );
            probeIdB = seedB11.rows[0].id;

            // 11a: tenant-A context → own row visible (1 row expected)
            await appCa.query("BEGIN");
            await appCa.query(
              "SELECT set_config('app.current_tenant_id', $1, true)",
              [`${PROBE_PREFIX}-dsar-tenant-a`],
            );
            const r11a = await appCa.query<{ id: string }>(
              "SELECT id FROM dsar_requests WHERE id = $1",
              [probeIdA],
            );
            await appCa.query("COMMIT");

            // 11b: tenant-A context → cross-tenant row invisible (0 rows expected)
            await appCb.query("BEGIN");
            await appCb.query(
              "SELECT set_config('app.current_tenant_id', $1, true)",
              [`${PROBE_PREFIX}-dsar-tenant-a`],
            );
            const r11b = await appCb.query<{ id: string }>(
              "SELECT id FROM dsar_requests WHERE id = $1",
              [probeIdB],
            );
            await appCb.query("COMMIT");

            if (r11a.rows.length === 1 && r11b.rows.length === 0) {
              pass(
                "Probe 11 — CLASS2 DSAR cross-tenant isolation (withTenantRls own=1 cross=0, PDPO-critical)",
              );
            } else {
              fail(
                "Probe 11 — CLASS2 DSAR cross-tenant isolation",
                `own-tenant rows=${r11a.rows.length} (want 1), cross-tenant rows=${r11b.rows.length} (want 0)`,
              );
            }
          } catch (e: any) {
            await appCa.query("ROLLBACK").catch(() => {});
            await appCb.query("ROLLBACK").catch(() => {});
            fail("Probe 11 — CLASS2 DSAR cross-tenant isolation", `Threw: ${e?.message ?? e}`);
          } finally {
            appCa.release();
            appCb.release();
            const ids11 = [probeIdA, probeIdB].filter(Boolean) as string[];
            if (ids11.length > 0) {
              try {
                await suC.query(
                  "DELETE FROM dsar_requests WHERE id = ANY($1::text[])",
                  [ids11],
                );
              } catch {
                for (const id of ids11) cleanupErr("dsar_requests", id);
              }
            }
            suC.release();
          }
        }

        // === PROBE 12 — CLASS 5: sbom_snapshots bypass INSERT (SBOM-SYS) ===
        {
          const appC = await ephemeralAppPool.connect();
          const suC = await ddlPool.connect();
          let probeSbomId: string | null = null;
          try {
            await appC.query("BEGIN");
            await appC.query("SET LOCAL ROLE aegis_rls_bypass");
            const rSb = await appC.query<{ id: string }>(
              `INSERT INTO sbom_snapshots
                 (snapshot_name, component_count, critical_vulns, high_vulns,
                  outdated_components, license_issues, trigger, components_json,
                  tenant_id, snapshot_at)
               VALUES ($1, 0, 0, 0, 0, 0, 'probe', '[]', $2, NOW())
               RETURNING id`,
              [`${PROBE_PREFIX}-sbom`, `${PROBE_PREFIX}-sbom-tenant`],
            );
            await appC.query("COMMIT");
            if (rSb.rows.length === 1) {
              probeSbomId = rSb.rows[0].id;
              pass("Probe 12 — CLASS5 sbom_snapshots INSERT via bypass succeeded (SBOM-SYS)");
            } else {
              fail("Probe 12 — CLASS5 sbom_snapshots bypass INSERT", "Expected 1 row returned, got 0");
            }
          } catch (e: any) {
            await appC.query("ROLLBACK").catch(() => {});
            fail("Probe 12 — CLASS5 sbom_snapshots bypass INSERT", `Threw: ${e?.message ?? e}`);
          } finally {
            appC.release();
            if (probeSbomId !== null) {
              try {
                await suC.query("DELETE FROM sbom_snapshots WHERE id = $1", [probeSbomId]);
              } catch {
                cleanupErr("sbom_snapshots", probeSbomId);
              }
            }
            suC.release();
          }
        }

        // === PROBE 13 — CLASS 5: PILOT-COUNT bypass isolation ===
        {
          const suC = await ddlPool.connect();
          const appCBare = await ephemeralAppPool.connect();
          const appCBypass = await ephemeralAppPool.connect();
          let probePilotId: string | null = null;
          try {
            const seedP = await suC.query<{ id: string }>(
              `INSERT INTO sbom_snapshots
                 (snapshot_name, component_count, critical_vulns, high_vulns,
                  outdated_components, license_issues, trigger, components_json,
                  tenant_id, snapshot_at)
               VALUES ($1, 0, 0, 0, 0, 0, 'probe', '[]', $2, NOW())
               RETURNING id`,
              [`${PROBE_PREFIX}-pilot-count`, `${PROBE_PREFIX}-pilot-tenant`],
            );
            probePilotId = seedP.rows[0].id;

            // 13a: bare aegis_app — no GUC — RLS must return 0
            const r13bare = await appCBare.query<{ c: string }>(
              "SELECT count(*)::int AS c FROM sbom_snapshots WHERE tenant_id = $1",
              [`${PROBE_PREFIX}-pilot-tenant`],
            );
            const bareCount = Number(r13bare.rows[0]?.c ?? 0);

            // 13b: bypass role — must see the seeded row (≥1)
            await appCBypass.query("BEGIN");
            await appCBypass.query("SET LOCAL ROLE aegis_rls_bypass");
            const r13bypass = await appCBypass.query<{ c: string }>(
              "SELECT count(*)::int AS c FROM sbom_snapshots WHERE tenant_id = $1",
              [`${PROBE_PREFIX}-pilot-tenant`],
            );
            await appCBypass.query("COMMIT");
            const bypassCount = Number(r13bypass.rows[0]?.c ?? 0);

            if (bareCount === 0 && bypassCount >= 1) {
              pass(
                "Probe 13 — CLASS5 PILOT-COUNT bypass isolation (bare=0 bypass≥1, cross-tenant aggregate works)",
              );
            } else {
              fail(
                "Probe 13 — CLASS5 PILOT-COUNT bypass isolation",
                `bare=${bareCount} (want 0), bypass=${bypassCount} (want ≥1)`,
              );
            }
          } catch (e: any) {
            await appCBypass.query("ROLLBACK").catch(() => {});
            fail("Probe 13 — CLASS5 PILOT-COUNT bypass isolation", `Threw: ${e?.message ?? e}`);
          } finally {
            appCBare.release();
            appCBypass.release();
            if (probePilotId !== null) {
              try {
                await suC.query("DELETE FROM sbom_snapshots WHERE id = $1", [probePilotId]);
              } catch {
                cleanupErr("sbom_snapshots", probePilotId);
              }
            }
            suC.release();
          }
        }

        // === PROBE 14 — CLASS 4: aegis_rls_bypass INSERT denied (Option Y) ===
        {
          const appC = await ephemeralAppPool.connect();
          try {
            await appC.query("BEGIN");
            await appC.query("SET LOCAL ROLE aegis_rls_bypass");
            let caught42501 = false;
            try {
              await appC.query(
                `INSERT INTO audit_chain_entries
                   (hash, previous_hash, action, user_id, resource, details,
                    created_at, source_audit_id, entry_timestamp)
                 VALUES ('probe14h', 'probe14ph', 'T003_PROBE14_BYPASS',
                         'probe-u', 'probe-r', '{}', NOW(), 999, NOW())`,
              );
            } catch (e: any) {
              if (e?.code === "42501") {
                caught42501 = true;
              } else {
                throw e;
              }
            }
            await appC.query("ROLLBACK");
            if (caught42501) {
              pass(
                "Probe 14 — CLASS4 Option Y aegis_rls_bypass INSERT on audit_chain_entries denied (42501)",
              );
            } else {
              fail(
                "Probe 14 — CLASS4 Option Y aegis_rls_bypass INSERT on audit_chain_entries denied",
                "INSERT succeeded — Option Y REVOKE did NOT take effect; bypass role can write the chain",
              );
            }
          } catch (e: any) {
            await appC.query("ROLLBACK").catch(() => {});
            fail(
              "Probe 14 — CLASS4 Option Y aegis_rls_bypass INSERT on audit_chain_entries denied",
              `Threw: ${e?.message ?? e}`,
            );
          } finally {
            appC.release();
          }
        }

        // === PROBE 15 — CLASS 6: LOGIN-UTR bypass correctness ===
        {
          const suC = await ddlPool.connect();
          const appCBare = await ephemeralAppPool.connect();
          const appCBypass = await ephemeralAppPool.connect();
          try {
            const adminRow = await suC.query<{ id: string }>(
              "SELECT id FROM users WHERE username = 'admin' LIMIT 1",
            );
            if (adminRow.rows.length === 0) {
              fail(
                "Probe 15 — CLASS6 LOGIN-UTR bypass correctness",
                "Admin user not found — cannot run login-path probe",
              );
            } else {
              const adminId = adminRow.rows[0].id;

              // 15a: bare aegis_app, no set_config — the pre-auth GUC state (regression path)
              const r15a = await appCBare.query<{ tenant_id: string }>(
                `SELECT tenant_id FROM user_tenant_roles
                 WHERE user_id = $1 AND is_primary = true AND is_active = true
                 LIMIT 1`,
                [adminId],
              );

              // 15b: bypass role — the fix's path (LOGIN-UTR bypass register entry)
              await appCBypass.query("BEGIN");
              await appCBypass.query("SET LOCAL ROLE aegis_rls_bypass");
              const r15b = await appCBypass.query<{ tenant_id: string }>(
                `SELECT tenant_id FROM user_tenant_roles
                 WHERE user_id = $1 AND is_primary = true AND is_active = true
                 LIMIT 1`,
                [adminId],
              );
              await appCBypass.query("COMMIT");

              if (r15a.rows.length === 0 && r15b.rows.length === 1) {
                pass(
                  `Probe 15 — CLASS6 LOGIN-UTR bypass correctness: bare=0 (pre-auth GUC → RLS blocks) bypass=1 tenant=${r15b.rows[0].tenant_id}`,
                );
              } else if (r15a.rows.length > 0) {
                fail(
                  "Probe 15 — CLASS6 LOGIN-UTR bypass correctness",
                  `bare-path returned ${r15a.rows.length} rows — RLS not enforcing on user_tenant_roles under pre-auth GUC`,
                );
              } else if (r15b.rows.length === 0) {
                fail(
                  "Probe 15 — CLASS6 LOGIN-UTR bypass correctness",
                  "bypass-path returned 0 rows — admin has no primary active UTR; login would fail even with fix applied",
                );
              } else {
                fail(
                  "Probe 15 — CLASS6 LOGIN-UTR bypass correctness",
                  `bare=${r15a.rows.length}, bypass=${r15b.rows.length} — unexpected state`,
                );
              }
            }
          } catch (e: any) {
            await appCBypass.query("ROLLBACK").catch(() => {});
            fail(
              "Probe 15 — CLASS6 LOGIN-UTR bypass correctness",
              `Threw: ${e?.message ?? e}`,
            );
          } finally {
            appCBare.release();
            appCBypass.release();
            suC.release();
          }
        }

        // === PROBE 16 — CLASS 7: VARCHAR predicate enforcement (billing_invoices) ===
        //
        // WHY THIS PROBE EXISTS (added 2026-06-04, same-session discovery):
        // Probes 1/4/11 target TEXT-predicate tables (incident_slas, dsar_requests).
        // Six tables use varchar("tenant_id"), which PostgreSQL normalizes to the
        // ((tenant_id)::text = current_tenant_id()) form. This probe provides the
        // prod-empirical proof that the ::text cast form enforces isolation in the
        // REAL prod container — not just in dev reasoning.
        // Both halves required (Rule 18): own-tenant visible + cross-tenant invisible.
        {
          const suC16 = await ddlPool.connect();
          const appC16a = await ephemeralAppPool.connect();
          const appC16b = await ephemeralAppPool.connect();
          const inv16Id = `${PROBE_PREFIX}-INV16`;
          const inv16TenantA = `${PROBE_PREFIX}-VAR-A`;
          const inv16TenantB = `${PROBE_PREFIX}-VAR-B`;
          try {
            // Seed one billing_invoices row under tenant-VAR-A (varchar tenant_id).
            await suC16.query(
              `INSERT INTO billing_invoices
                 (id, tenant_id, period, status, line_items_json,
                  subtotal_usd, tax_usd, total_usd)
               VALUES ($1, $2, '2026-probe', 'DRAFT', '[]', 0, 0, 0)`,
              [inv16Id, inv16TenantA],
            );

            // 16a — POSITIVE: GUC=VAR-A → own-tenant row must be visible (1 row).
            // Proves the ::text cast form allows reads when the GUC matches.
            await appC16a.query("BEGIN");
            await appC16a.query(
              "SELECT set_config('app.current_tenant_id', $1, true)",
              [inv16TenantA],
            );
            const r16a = await appC16a.query<{ id: string }>(
              "SELECT id FROM billing_invoices WHERE id = $1",
              [inv16Id],
            );
            await appC16a.query("COMMIT");

            // 16b — DENIAL: GUC=VAR-B → cross-tenant row must be invisible (0 rows).
            // Proves the ::text cast form blocks reads when the GUC doesn't match.
            await appC16b.query("BEGIN");
            await appC16b.query(
              "SELECT set_config('app.current_tenant_id', $1, true)",
              [inv16TenantB],
            );
            const r16b = await appC16b.query<{ id: string }>(
              "SELECT id FROM billing_invoices WHERE id = $1",
              [inv16Id],
            );
            await appC16b.query("COMMIT");

            if (r16a.rows.length === 1 && r16b.rows.length === 0) {
              pass(
                "Probe 16 — CLASS7 VARCHAR predicate enforcement: billing_invoices own=1 cross=0 " +
                "(((tenant_id)::text=current_tenant_id()) form enforces isolation in prod)",
              );
            } else if (r16a.rows.length === 0) {
              fail(
                "Probe 16 — CLASS7 VARCHAR predicate enforcement",
                `own-tenant returned 0 rows — ::text cast form BLOCKING own-tenant reads ` +
                `(broken isolation); GUC=${inv16TenantA} should see id=${inv16Id}`,
              );
            } else if (r16b.rows.length > 0) {
              fail(
                "Probe 16 — CLASS7 VARCHAR predicate enforcement",
                `cross-tenant returned ${r16b.rows.length} rows — ::text cast form NOT isolating ` +
                `(cross-tenant leak); GUC=${inv16TenantB} should NOT see id=${inv16Id}`,
              );
            } else {
              fail(
                "Probe 16 — CLASS7 VARCHAR predicate enforcement",
                `Unexpected: own=${r16a.rows.length} cross=${r16b.rows.length}`,
              );
            }
          } catch (e: any) {
            await appC16a.query("ROLLBACK").catch(() => {});
            await appC16b.query("ROLLBACK").catch(() => {});
            fail(
              "Probe 16 — CLASS7 VARCHAR predicate enforcement",
              `Threw: ${e?.message ?? e}`,
            );
          } finally {
            appC16a.release();
            appC16b.release();
            await suC16.query(
              "DELETE FROM billing_invoices WHERE id = $1",
              [inv16Id],
            ).catch(() => cleanupErr("billing_invoices", inv16Id));
            suC16.release();
          }
        }

        // === PROBE 17 — CLASS 1+2: decision_scoring_outputs (#70) isolation ===
        //
        // WHY THIS PROBE EXISTS (added 2026-06-08, post-count-sweep):
        // decision_scoring_outputs is TENANT_TABLES[#70] — added for P5 Item 2 on
        // 2026-06-07, AFTER the T003 diagnostic ran at 15/15. That run confirmed
        // 15 tables; this probe is the FIRST functional diagnostic confirmation
        // that table #70's tenant-isolation actually holds. Step 3a at boot verified
        // the USING+WITH CHECK predicate structurally; this probe verifies it
        // functionally: own-tenant query returns 1 row; cross-tenant returns 0.
        // Rule 18: both halves required (positive enforcement + cross-tenant denial).
        {
          const suC17 = await ddlPool.connect();
          const appC17a = await ephemeralAppPool.connect();
          const appC17b = await ephemeralAppPool.connect();
          const dso17TenantA = `${PROBE_PREFIX}-DSO-A`;
          const dso17TenantB = `${PROBE_PREFIX}-DSO-B`;
          const dso17DecisionId = `${PROBE_PREFIX}-DECISION-17`;
          let dso17Id: number | null = null;
          try {
            // Seed one decision_scoring_outputs row under tenant-DSO-A.
            // id is SERIAL — capture via RETURNING id.
            const ins17 = await suC17.query<{ id: number }>(
              `INSERT INTO decision_scoring_outputs
                 (tenant_id, decision_id, scoring_path, model_identifier,
                  risk_score, reasoning_text, factors_json)
               VALUES ($1, $2, 'PROBE', 'probe-model', 0, 'probe', '{}')
               RETURNING id`,
              [dso17TenantA, dso17DecisionId],
            );
            dso17Id = ins17.rows[0]?.id ?? null;
            if (dso17Id === null) throw new Error("INSERT RETURNING id returned no row");

            // 17a — POSITIVE: GUC=DSO-A → own-tenant row must be visible (1 row).
            await appC17a.query("BEGIN");
            await appC17a.query(
              "SELECT set_config('app.current_tenant_id', $1, true)",
              [dso17TenantA],
            );
            const r17a = await appC17a.query<{ id: number }>(
              "SELECT id FROM decision_scoring_outputs WHERE id = $1",
              [dso17Id],
            );
            await appC17a.query("COMMIT");

            // 17b — DENIAL: GUC=DSO-B → cross-tenant row must be invisible (0 rows).
            await appC17b.query("BEGIN");
            await appC17b.query(
              "SELECT set_config('app.current_tenant_id', $1, true)",
              [dso17TenantB],
            );
            const r17b = await appC17b.query<{ id: number }>(
              "SELECT id FROM decision_scoring_outputs WHERE id = $1",
              [dso17Id],
            );
            await appC17b.query("COMMIT");

            if (r17a.rows.length === 1 && r17b.rows.length === 0) {
              pass(
                "Probe 17 — CLASS1+2 decision_scoring_outputs (#70) isolation: own=1 cross=0 " +
                "(first functional diagnostic confirmation of table #70 tenant-isolation)",
              );
            } else if (r17a.rows.length === 0) {
              fail(
                "Probe 17 — CLASS1+2 decision_scoring_outputs (#70) isolation",
                `own-tenant returned 0 rows — RLS blocking own-tenant reads; ` +
                `GUC=${dso17TenantA} should see id=${dso17Id}`,
              );
            } else if (r17b.rows.length > 0) {
              fail(
                "Probe 17 — CLASS1+2 decision_scoring_outputs (#70) isolation",
                `cross-tenant returned ${r17b.rows.length} rows — tenant-isolation NOT enforced on #70; ` +
                `GUC=${dso17TenantB} should NOT see id=${dso17Id}`,
              );
            } else {
              fail(
                "Probe 17 — CLASS1+2 decision_scoring_outputs (#70) isolation",
                `Unexpected: own=${r17a.rows.length} cross=${r17b.rows.length}`,
              );
            }
          } catch (e: any) {
            await appC17a.query("ROLLBACK").catch(() => {});
            await appC17b.query("ROLLBACK").catch(() => {});
            fail(
              "Probe 17 — CLASS1+2 decision_scoring_outputs (#70) isolation",
              `Threw: ${e?.message ?? e}`,
            );
          } finally {
            appC17a.release();
            appC17b.release();
            if (dso17Id !== null) {
              await suC17.query(
                "DELETE FROM decision_scoring_outputs WHERE id = $1",
                [dso17Id],
              ).catch(() => cleanupErr("decision_scoring_outputs", String(dso17Id)));
            }
            suC17.release();
          }
        }

      } finally {
        await ephemeralAppPool.end();
        rlsDiagnosticRunning = false;
        const allPassFinal = probesPassed === 17 && cleanupFailures === 0;
        diagLogger.info(
          `COMPLETE runId=${runId} invoker=${invoker} passed=${probesPassed} failed=${probesFailed} cleanupFailures=${cleanupFailures} allPass=${allPassFinal} durationMs=${Date.now() - startMs}`,
        );
      }

      const allPass = probesPassed === 17 && cleanupFailures === 0;
      return res.json({
        runId,
        environment: process.env.NODE_ENV ?? "unknown",
        invoker,
        probes: probeResults,
        residuals,
        summary: {
          total: 17,
          passed: probesPassed,
          failed: probesFailed,
          cleanupFailures,
          allPass,
        },
      });
    }),
  );

  // T004b route removed per D-LIFECYCLE-1 (prod execution 2026-06-07 confirmed;
  // module-level state + route handler removed in same session).

  // ─── Path A encryption probe ─────────────────────────────────────────────────
  // Rule 9 architect PASS 2026-06-07 (v1.1-RATIFIED).
  // Permanent Rule 17 infrastructure: ENCRYPTION_PROBE_ENABLED flag-off after use;
  // route stays deployed. Re-run mandatory after any change touching PII encryption,
  // encryptPii(), decision_scoring_outputs write path, or dsar_requests write path.
  //
  // BC-1: raw ciphertext never in response — encryptedPrefixMatch + observedPrefixClass only.
  // BC-2: marker-based cleanup — pre-sweep + DELETE-by-marker in finally + post-residual check.
  // BC-3: probeMode:true on createRequest — no audit-chain or notification artifacts.
  // BC-4: probe runs as HTTP handler — request-tx GUC context (tenantMiddleware) already
  //       sets app.current_tenant_id for all db.* calls via AsyncLocalStorage.
  app.post(
    "/api/internal/encryption-probe",
    requireRole("admin"),
    asyncHandler(async (req, res) => {
      if (process.env.ENCRYPTION_PROBE_ENABLED !== "true") {
        return res.status(404).json(createErrorResponse("AEGIS_ERR_001", { path: req.path }));
      }

      const probeLogger = logger.child("encryption-probe");
      const invoker = req.session.userId ?? "unknown";

      if (encryptionProbeRunning) {
        probeLogger.warn(`REJECTED already-running invoker=${invoker}`);
        return res.status(409).json({ error: "An encryption probe run is already in progress" });
      }
      encryptionProbeRunning = true;

      const runId   = `ENC-PROBE-${Date.now()}`;
      const startMs = Date.now();

      // Tenant from the admin's authenticated session (set by tenantMiddleware via AsyncLocalStorage)
      const probeTenantId = (req as any).tenantId as string;

      type ProbeEntry = {
        probe:              string;
        result:             "PASS" | "FAIL";
        encryptedPrefixMatch: boolean;
        observedPrefixClass:  string;
        detail?:            string;
        cleanupFailed?:     boolean;
      };

      const probeResults: ProbeEntry[] = [];
      let probesPassed  = 0;
      let probesFailed  = 0;
      let cleanupFailures = 0;
      let staleMarkersFound = 0;

      function pass(probe: string, encryptedPrefixMatch: boolean, observedPrefixClass: string, detail?: string): void {
        probesPassed++;
        probeResults.push({ probe, result: "PASS", encryptedPrefixMatch, observedPrefixClass, detail });
      }
      function fail(probe: string, encryptedPrefixMatch: boolean, observedPrefixClass: string, detail: string): void {
        probesFailed++;
        probeResults.push({ probe, result: "FAIL", encryptedPrefixMatch, observedPrefixClass, detail });
      }

      // BC-1: classify observed prefix without exposing raw value
      function classifyPrefix(raw: string | null | undefined): { match: boolean; cls: string } {
        if (!raw) return { match: false, cls: "null-or-empty" };
        if (raw.startsWith("ENC:v1:")) return { match: true, cls: "ENC:v1:" };
        if (raw.startsWith("ENC:v2:")) return { match: true, cls: "ENC:v2:" }; // T2a: envelope format is also valid-encrypted
        if (raw.startsWith("ENC:"))    return { match: false, cls: "ENC:other-version" };
        return { match: false, cls: "non-ENC" };
      }

      try {
        probeLogger.info(`[encryption-probe] START runId=${runId} invoker=${invoker} tenantId=${probeTenantId}`);

        // ── BC-2 pre-run stale-marker sweep — 17 marker tables ───────────────
        // Probes 1–16 + P18 (users). P17 (key_inventory) is read-only — no marker row.
        // Run in parallel; abort if ANY stale rows found from a prior failed run.
        const staleResults = await Promise.all([
          db.execute(sql`SELECT count(*)::int AS cnt FROM decision_scoring_outputs WHERE decision_id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM dsar_requests WHERE description LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM pam_sessions WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM kyc_customers WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM ubo_registrations WHERE registered_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM auditor_credentials WHERE created_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM biometric_profiles WHERE user_id = ${"9999999"}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM suspicious_activity_reports WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM explanation_dossiers WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM ombudsman_complaints WHERE category LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM momo_sandbox_txns WHERE txn_type LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM regulator_onboarding_sessions WHERE started_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM examiner_tokens WHERE issued_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM model_cards_v2 WHERE model_key LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM vendor_risk_register WHERE vendor_key LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM scim_provisions WHERE external_id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM users WHERE username LIKE ${'probe-enc-ENC-PROBE-%@probe.internal'}`),
        ]);
        staleMarkersFound = staleResults.reduce(
          (acc, r) => acc + ((((r as any).rows?.[0]) as any)?.cnt ?? 0), 0,
        );
        if (staleMarkersFound > 0) {
          probeLogger.warn(`[encryption-probe] STALE MARKERS FOUND — aborting runId=${runId} stale=${staleMarkersFound}`);
          encryptionProbeRunning = false;
          return res.status(409).json({
            error:   "Stale probe markers found from a prior failed run",
            runId,
            staleMarkersFound,
            detail:  "Manually DELETE stale ENC-PROBE-% rows across all 17 marker tables (see probe documentation) then retry.",
          });
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 1 — decision_scoring_outputs (reasoning_text + factors_json)
        // Write path: persistThreatDecision() → encryptPii() → INSERT
        // ════════════════════════════════════════════════════════════════════

        const { persistThreatDecision, buildThreatDecisionPayload } = await import("./lib/persist-threat-decision");

        const p1DecisionId = `${runId}-P1`;
        let p1Inserted = false;

        try {
          // Step 1: write via the actual service path (D-1-B)
          await persistThreatDecision(
            buildThreatDecisionPayload({
              tenantId:        probeTenantId,
              decisionId:      p1DecisionId,
              riskScore:       0,
              severity:        "probe",
              confidence:      0,
              reasoning:       "ENCRYPTION_PROBE_PLAINTEXT_REASONING",
              recommendations: [],
              model:           "probe",
            }),
          );
          p1Inserted = true;

          // Step 2: read back LEFT(20) of reasoning_text (BC-1 — raw value never leaves this scope)
          const p1RowsRes = await db.execute(sql`
            SELECT LEFT(reasoning_text, 20) AS prefix_rt,
                   LEFT(factors_json,   20) AS prefix_fj
            FROM decision_scoring_outputs
            WHERE decision_id = ${p1DecisionId}
          `);
          const p1Row = (p1RowsRes as any).rows?.[0] as { prefix_rt?: string; prefix_fj?: string } | undefined;

          const rtClass = classifyPrefix(p1Row?.prefix_rt);
          const fjClass = classifyPrefix(p1Row?.prefix_fj);

          if (p1Row && rtClass.match && fjClass.match) {
            pass(
              "Probe 1 — decision_scoring_outputs reasoning_text+factors_json (persistThreatDecision write path)",
              true,
              "ENC:v1:",
              "Both columns store ENC:v1: ciphertext — persistThreatDecision encrypts before INSERT",
            );
          } else {
            fail(
              "Probe 1 — decision_scoring_outputs reasoning_text+factors_json (persistThreatDecision write path)",
              rtClass.match && fjClass.match,
              `reasoning_text:${rtClass.cls} factors_json:${fjClass.cls}`,
              p1Row
                ? "Column prefix mismatch — write path may not be calling encryptPii() before INSERT"
                : "No row found after INSERT — persistThreatDecision may have swallowed an error",
            );
          }
        } finally {
          // BC-2: DELETE by marker (always runs)
          if (p1Inserted) {
            try {
              await db.execute(sql`
                DELETE FROM decision_scoring_outputs WHERE decision_id = ${p1DecisionId}
              `);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 1 cleanup FAILED decisionId=${p1DecisionId}`, {
                error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)),
              });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 2 — dsar_requests (subject_email)
        // Write path: dsarWorkflow.createRequest({probeMode:true}) → encryptPii() → INSERT
        // ════════════════════════════════════════════════════════════════════

        const { dsarWorkflow } = await import("./lib/dsar-workflow");

        const p2Ref  = `${runId}-P2`;
        let p2Id: string | null = null;

        try {
          // Step 1: write via the actual service path, probeMode suppresses audit/notification (BC-3)
          const p2Request = await dsarWorkflow.createRequest({
            subjectName:  "ENCRYPTION_PROBE_NAME",
            subjectEmail: "probe@enc-probe.internal",
            requestType:  "access",
            requestChannel: "probe",
            description:  p2Ref,   // BC-2 marker embedded here for lookup + DELETE
            tenantId:     probeTenantId,
            probeMode:    true,
          });
          p2Id = p2Request.id ?? null;

          // Step 2: read back LEFT(20) of subject_email (BC-1 — raw value never leaves this scope)
          const p2RowsRes = await db.execute(sql`
            SELECT LEFT(subject_email, 20) AS prefix_email
            FROM dsar_requests
            WHERE description = ${p2Ref}
          `);
          const p2Row = (p2RowsRes as any).rows?.[0] as { prefix_email?: string } | undefined;

          const emailClass = classifyPrefix(p2Row?.prefix_email);

          if (p2Row && emailClass.match) {
            pass(
              "Probe 2 — dsar_requests subject_email (dsarWorkflow.createRequest probeMode:true write path)",
              true,
              "ENC:v1:",
              "subject_email stores ENC:v1: ciphertext — dsarWorkflow.createRequest encrypts before INSERT",
            );
          } else {
            fail(
              "Probe 2 — dsar_requests subject_email (dsarWorkflow.createRequest probeMode:true write path)",
              emailClass.match,
              emailClass.cls,
              p2Row
                ? "Column prefix mismatch — write path may not be calling encryptPii() before INSERT"
                : "No row found after INSERT — createRequest may have thrown or written with different description",
            );
          }
        } finally {
          // BC-2: DELETE by marker (always runs)
          try {
            await db.execute(sql`
              DELETE FROM dsar_requests WHERE description = ${p2Ref}
            `);
          } catch (cleanErr) {
            cleanupFailures++;
            probeLogger.error(`[encryption-probe] Probe 2 cleanup FAILED p2Ref=${p2Ref}`, {
              error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)),
            });
            const last = probeResults[probeResults.length - 1];
            if (last) last.cleanupFailed = true;
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 3 — pam_sessions (accountName + userName)
        // Write path: savePamSession() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT, no external side effects
        // ════════════════════════════════════════════════════════════════════

        const { savePamSession } = await import("./lib/privileged-access-db");

        const p3Id = `${runId}-P3`;
        let p3Inserted = false;

        try {
          await savePamSession({
            id: p3Id,
            accessRequestId: "probe-access-req",
            accountId: "probe-account-id",
            accountName: "ENCRYPTION_PROBE_ACCOUNT",
            userId: "probe-user-id",
            userName: "ENCRYPTION_PROBE_USER",
            startTime: new Date(),
            status: "completed",
            commands: [],
            riskEvents: [],
            tenantId: probeTenantId,
          });
          p3Inserted = true;

          const p3Res = await db.execute(sql`
            SELECT LEFT(account_name, 20) AS prefix_an, LEFT(user_name, 20) AS prefix_un
            FROM pam_sessions WHERE id = ${p3Id}
          `);
          const p3Row = (p3Res as any).rows?.[0] as { prefix_an?: string; prefix_un?: string } | undefined;
          const p3AnClass = classifyPrefix(p3Row?.prefix_an);
          const p3UnClass = classifyPrefix(p3Row?.prefix_un);

          if (p3Row && p3AnClass.match && p3UnClass.match) {
            pass("Probe 3 — pam_sessions accountName+userName (savePamSession write path)", true, "ENC:v1:", "Both columns ENC:v1: — savePamSession encrypts via pamSessionCtx before INSERT");
          } else {
            fail("Probe 3 — pam_sessions accountName+userName (savePamSession write path)", p3AnClass.match && p3UnClass.match, `accountName:${p3AnClass.cls} userName:${p3UnClass.cls}`, p3Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p3Inserted) {
            try {
              await db.execute(sql`DELETE FROM pam_sessions WHERE id = ${p3Id}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 3 cleanup FAILED id=${p3Id}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 4 — kyc_customers (fullName + nationalId)
        // Write path: saveKycCustomer() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT
        // ════════════════════════════════════════════════════════════════════

        const { saveKycCustomer } = await import("./lib/kyc-agent-engine-db");

        const p4Id = `${runId}-P4`;
        let p4Inserted = false;

        try {
          await saveKycCustomer({
            id: p4Id,
            nationalId: "PROBE-NATID-P4",
            fullName: "PROBE FULL NAME P4",
            dateOfBirth: "1990-01-01",
            phoneNumber: "+256700000004",
            status: "pending",
            riskTier: "LOW",
            tenantId: probeTenantId,
          });
          p4Inserted = true;

          const p4Res = await db.execute(sql`
            SELECT LEFT(full_name, 20) AS prefix_fn, LEFT(national_id, 20) AS prefix_ni
            FROM kyc_customers WHERE id = ${p4Id}
          `);
          const p4Row = (p4Res as any).rows?.[0] as { prefix_fn?: string; prefix_ni?: string } | undefined;
          const p4FnClass = classifyPrefix(p4Row?.prefix_fn);
          const p4NiClass = classifyPrefix(p4Row?.prefix_ni);

          if (p4Row && p4FnClass.match && p4NiClass.match) {
            pass("Probe 4 — kyc_customers fullName+nationalId (saveKycCustomer write path)", true, "ENC:v1:", "Both PII columns ENC:v1: — saveKycCustomer encrypts treat-(i) + treat-(ii) before INSERT");
          } else {
            fail("Probe 4 — kyc_customers fullName+nationalId (saveKycCustomer write path)", p4FnClass.match && p4NiClass.match, `fullName:${p4FnClass.cls} nationalId:${p4NiClass.cls}`, p4Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p4Inserted) {
            try {
              await db.execute(sql`DELETE FROM kyc_customers WHERE id = ${p4Id}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 4 cleanup FAILED id=${p4Id}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 5 — ubo_registrations (ownerName + ownerNationalId + ownerNationality)
        // Write path: registerUbo() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT; marker = registeredBy field
        // ════════════════════════════════════════════════════════════════════

        const { registerUbo } = await import("./lib/pilot-readiness-extras-7");

        const p5Marker = `${runId}-P5`;
        let p5Inserted = false;

        try {
          await registerUbo({
            corporateCustomerRef: "PROBE-CORP-P5",
            corporateName: "PROBE CORPORATE P5",
            ownerName: "PROBE OWNER NAME P5",
            ownerNationalId: "PROBE-NATID-P5",
            ownerNationality: "Ugandan",
            ownershipPct: 30,
            controlType: "direct",
            registeredBy: p5Marker,
            tenantId: probeTenantId,
          });
          p5Inserted = true;

          const p5Res = await db.execute(sql`
            SELECT LEFT(owner_name, 20) AS prefix_on, LEFT(owner_national_id, 20) AS prefix_oni
            FROM ubo_registrations WHERE registered_by = ${p5Marker}
          `);
          const p5Row = (p5Res as any).rows?.[0] as { prefix_on?: string; prefix_oni?: string } | undefined;
          const p5OnClass  = classifyPrefix(p5Row?.prefix_on);
          const p5OniClass = classifyPrefix(p5Row?.prefix_oni);

          if (p5Row && p5OnClass.match && p5OniClass.match) {
            pass("Probe 5 — ubo_registrations ownerName+ownerNationalId (registerUbo write path)", true, "ENC:v1:", "Both PII columns ENC:v1: — registerUbo encrypts treat-(i) + treat-(ii) before INSERT");
          } else {
            fail("Probe 5 — ubo_registrations ownerName+ownerNationalId (registerUbo write path)", p5OnClass.match && p5OniClass.match, `ownerName:${p5OnClass.cls} ownerNationalId:${p5OniClass.cls}`, p5Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p5Inserted) {
            try {
              await db.execute(sql`DELETE FROM ubo_registrations WHERE registered_by = ${p5Marker}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 5 cleanup FAILED registered_by=${p5Marker}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 6 — auditor_credentials (auditorEmail)
        // Write path: issueAuditorCredential() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT; marker = createdBy field
        // ════════════════════════════════════════════════════════════════════

        const { issueAuditorCredential } = await import("./lib/pilot-readiness-extras-7");

        const p6Marker = `${runId}-P6`;
        let p6Inserted = false;

        try {
          await issueAuditorCredential({
            firmName: "PROBE FIRM P6",
            auditorEmail: "probe6@enc.internal",
            scopes: ["audit"],
            ttlDays: 1,
            createdBy: p6Marker,
          });
          p6Inserted = true;

          const p6Res = await db.execute(sql`
            SELECT LEFT(auditor_email, 20) AS prefix_ae
            FROM auditor_credentials WHERE created_by = ${p6Marker}
          `);
          const p6Row = (p6Res as any).rows?.[0] as { prefix_ae?: string } | undefined;
          const p6AeClass = classifyPrefix(p6Row?.prefix_ae);

          if (p6Row && p6AeClass.match) {
            pass("Probe 6 — auditor_credentials auditorEmail (issueAuditorCredential write path)", true, "ENC:v1:", "auditorEmail stores ENC:v1: — issueAuditorCredential encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 6 — auditor_credentials auditorEmail (issueAuditorCredential write path)", p6AeClass.match, p6AeClass.cls, p6Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p6Inserted) {
            try {
              await db.execute(sql`DELETE FROM auditor_credentials WHERE created_by = ${p6Marker}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 6 cleanup FAILED created_by=${p6Marker}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 7 — biometric_profiles (keystrokeBaselineJson + mouseBaselineJson)
        // Write path: saveBiometricProfile() → encryptPii() → INSERT/UPSERT
        // Tier 1: real service path; sentinel userId=9999999 (no FK, no conflict with real users)
        // ════════════════════════════════════════════════════════════════════

        const { saveBiometricProfile } = await import("./lib/wave-final-services");

        const p7UserId = "9999999";
        let p7Inserted = false;

        try {
          await saveBiometricProfile({
            userId: p7UserId,
            keystrokeBaseline: { probe: "enc_test_keystroke" },
            mouseBaseline: { probe: "enc_test_mouse" },
            sampleCount: 1,
            confidenceScore: 0,
          }, probeTenantId);
          p7Inserted = true;

          const p7Res = await db.execute(sql`
            SELECT LEFT(keystroke_baseline_json, 20) AS prefix_kb, LEFT(mouse_baseline_json, 20) AS prefix_mb
            FROM biometric_profiles WHERE user_id = ${p7UserId}
          `);
          const p7Row = (p7Res as any).rows?.[0] as { prefix_kb?: string; prefix_mb?: string } | undefined;
          const p7KbClass = classifyPrefix(p7Row?.prefix_kb);
          const p7MbClass = classifyPrefix(p7Row?.prefix_mb);

          if (p7Row && p7KbClass.match && p7MbClass.match) {
            pass("Probe 7 — biometric_profiles keystroke+mouseBaselineJson (saveBiometricProfile write path)", true, "ENC:v1:", "Both JSON columns ENC:v1: — saveBiometricProfile encrypts via biometricUserCtx before INSERT");
          } else {
            fail("Probe 7 — biometric_profiles keystroke+mouseBaselineJson (saveBiometricProfile write path)", p7KbClass.match && p7MbClass.match, `keystroke:${p7KbClass.cls} mouse:${p7MbClass.cls}`, p7Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p7Inserted) {
            try {
              await db.execute(sql`DELETE FROM biometric_profiles WHERE user_id = ${p7UserId}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 7 cleanup FAILED user_id=${p7UserId}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 8 — suspicious_activity_reports (subjectName + subjectId)
        // Write path: saveSAR() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT
        // ════════════════════════════════════════════════════════════════════

        const { saveSAR } = await import("./lib/regulator-gateway-db");

        const p8Id = `${runId}-P8`;
        let p8Inserted = false;

        try {
          await saveSAR({
            id: p8Id,
            tenantId: probeTenantId,
            referenceNumber: "PROBE-SAR-P8",
            status: "draft",
            priority: "HIGH",
            subjectType: "individual",
            subjectName: "PROBE SUBJECT NAME P8",
            subjectId: "PROBE-SUBJECT-ID-P8",
            activityType: "unusual_transfer",
            activityDate: new Date(),
            currency: "UGX",
            description: "Probe SAR description P8",
            proofChainHash: "0000000000000000000000000000000000000000000000000000000000000000",
            kycDecisions: [],
            transactionIds: [],
            preparedBy: "probe",
          });
          p8Inserted = true;

          const p8Res = await db.execute(sql`
            SELECT LEFT(subject_name, 20) AS prefix_sn, LEFT(subject_id, 20) AS prefix_si
            FROM suspicious_activity_reports WHERE id = ${p8Id}
          `);
          const p8Row = (p8Res as any).rows?.[0] as { prefix_sn?: string; prefix_si?: string } | undefined;
          const p8SnClass = classifyPrefix(p8Row?.prefix_sn);
          const p8SiClass = classifyPrefix(p8Row?.prefix_si);

          if (p8Row && p8SnClass.match && p8SiClass.match) {
            pass("Probe 8 — suspicious_activity_reports subjectName+subjectId (saveSAR write path)", true, "ENC:v1:", "Both PII columns ENC:v1: — saveSAR encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 8 — suspicious_activity_reports subjectName+subjectId (saveSAR write path)", p8SnClass.match && p8SiClass.match, `subjectName:${p8SnClass.cls} subjectId:${p8SiClass.cls}`, p8Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p8Inserted) {
            try {
              await db.execute(sql`DELETE FROM suspicious_activity_reports WHERE id = ${p8Id}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 8 cleanup FAILED id=${p8Id}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 9 — explanation_dossiers (subjectName + contactInformation)
        // Write path: saveExplanationDossier() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT (onConflictDoNothing — fresh id per run)
        // ════════════════════════════════════════════════════════════════════

        const { saveExplanationDossier } = await import("./lib/regulator-gateway-db");

        const p9Id = `${runId}-P9`;
        let p9Inserted = false;

        try {
          await saveExplanationDossier({
            id: p9Id,
            type: "kyc",
            subjectId: "PROBE-SUBJECT-P9",
            subjectName: "PROBE SUBJECT NAME P9",
            decisionDate: new Date(),
            decision: "approved",
            decisionConfidence: 0.95,
            summary: "Probe dossier summary",
            detailedReasoning: ["probe"],
            factorsConsidered: [],
            appealProcess: "Standard appeal process",
            appealDeadline: new Date(Date.now() + 30 * 86400000),
            contactInformation: "probe9@enc.internal",
            dataRetentionDays: 30,
          });
          p9Inserted = true;

          const p9Res = await db.execute(sql`
            SELECT LEFT(subject_name, 20) AS prefix_sn, LEFT(contact_information, 20) AS prefix_ci
            FROM explanation_dossiers WHERE id = ${p9Id}
          `);
          const p9Row = (p9Res as any).rows?.[0] as { prefix_sn?: string; prefix_ci?: string } | undefined;
          const p9SnClass = classifyPrefix(p9Row?.prefix_sn);
          const p9CiClass = classifyPrefix(p9Row?.prefix_ci);

          if (p9Row && p9SnClass.match && p9CiClass.match) {
            pass("Probe 9 — explanation_dossiers subjectName+contactInformation (saveExplanationDossier write path)", true, "ENC:v1:", "Both PII columns ENC:v1: — saveExplanationDossier encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 9 — explanation_dossiers subjectName+contactInformation (saveExplanationDossier write path)", p9SnClass.match && p9CiClass.match, `subjectName:${p9SnClass.cls} contactInfo:${p9CiClass.cls}`, p9Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p9Inserted) {
            try {
              await db.execute(sql`DELETE FROM explanation_dossiers WHERE id = ${p9Id}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 9 cleanup FAILED id=${p9Id}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 10 — ombudsman_complaints (customerName + customerContact)
        // Write path: fileComplaint() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT; marker = category field (stored plaintext)
        // ════════════════════════════════════════════════════════════════════

        const { fileComplaint } = await import("./lib/pilot-readiness-extras-8");

        const p10Marker = `${runId}-P10`;
        let p10Inserted = false;

        try {
          await fileComplaint({
            customerName: "PROBE CUSTOMER P10",
            customerContact: "probe10@enc.internal",
            channel: "email",
            category: p10Marker,
            description: "Probe complaint description P10",
          });
          p10Inserted = true;

          const p10Res = await db.execute(sql`
            SELECT LEFT(customer_name, 20) AS prefix_cn, LEFT(customer_contact, 20) AS prefix_cc
            FROM ombudsman_complaints WHERE category = ${p10Marker}
          `);
          const p10Row = (p10Res as any).rows?.[0] as { prefix_cn?: string; prefix_cc?: string } | undefined;
          const p10CnClass = classifyPrefix(p10Row?.prefix_cn);
          const p10CcClass = classifyPrefix(p10Row?.prefix_cc);

          if (p10Row && p10CnClass.match && p10CcClass.match) {
            pass("Probe 10 — ombudsman_complaints customerName+customerContact (fileComplaint write path)", true, "ENC:v1:", "Both PII columns ENC:v1: — fileComplaint encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 10 — ombudsman_complaints customerName+customerContact (fileComplaint write path)", p10CnClass.match && p10CcClass.match, `customerName:${p10CnClass.cls} customerContact:${p10CcClass.cls}`, p10Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p10Inserted) {
            try {
              await db.execute(sql`DELETE FROM ombudsman_complaints WHERE category = ${p10Marker}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 10 cleanup FAILED category=${p10Marker}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 11 — momo_sandbox_txns (msisdn)
        // Write path: runMomoSandboxTxn() → encryptPii() → INSERT
        // Tier 1: real service path; marker = txnType field (stored plaintext)
        // Note: runMomoSandboxTxn has no audit chain writes — probeMode not needed.
        // ════════════════════════════════════════════════════════════════════

        const { runMomoSandboxTxn } = await import("./lib/pilot-readiness-extras-8");

        const p11Marker = `${runId}-P11`;
        let p11Inserted = false;

        try {
          await runMomoSandboxTxn({
            provider: "MTN_MOMO",
            txnType: p11Marker,
            msisdn: "+256700000011",
            amountUgx: 10000,
          });
          p11Inserted = true;

          const p11Res = await db.execute(sql`
            SELECT LEFT(msisdn, 20) AS prefix_ms
            FROM momo_sandbox_txns WHERE txn_type = ${p11Marker}
          `);
          const p11Row = (p11Res as any).rows?.[0] as { prefix_ms?: string } | undefined;
          const p11MsClass = classifyPrefix(p11Row?.prefix_ms);

          if (p11Row && p11MsClass.match) {
            pass("Probe 11 — momo_sandbox_txns msisdn (runMomoSandboxTxn write path)", true, "ENC:v1:", "msisdn stores ENC:v1: — runMomoSandboxTxn encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 11 — momo_sandbox_txns msisdn (runMomoSandboxTxn write path)", p11MsClass.match, p11MsClass.cls, p11Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p11Inserted) {
            try {
              await db.execute(sql`DELETE FROM momo_sandbox_txns WHERE txn_type = ${p11Marker}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 11 cleanup FAILED txn_type=${p11Marker}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 12 — regulator_onboarding_sessions (examinerName + examinerEmail)
        // Write path: startOnboardingSession() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT; marker = startedBy field (stored plaintext)
        // Note: startOnboardingSession has no audit chain writes — probeMode not needed.
        // ════════════════════════════════════════════════════════════════════

        const { startOnboardingSession } = await import("./lib/pilot-readiness-extras-8");

        const p12Marker = `${runId}-P12`;
        let p12Inserted = false;

        try {
          await startOnboardingSession({
            regulatorAgency: "PROBE-AGENCY-P12",
            examinerName: "PROBE EXAMINER P12",
            examinerEmail: "probe12@enc.internal",
            startedBy: p12Marker,
          });
          p12Inserted = true;

          const p12Res = await db.execute(sql`
            SELECT LEFT(examiner_name, 20) AS prefix_en, LEFT(examiner_email, 20) AS prefix_ee
            FROM regulator_onboarding_sessions WHERE started_by = ${p12Marker}
          `);
          const p12Row = (p12Res as any).rows?.[0] as { prefix_en?: string; prefix_ee?: string } | undefined;
          const p12EnClass = classifyPrefix(p12Row?.prefix_en);
          const p12EeClass = classifyPrefix(p12Row?.prefix_ee);

          if (p12Row && p12EnClass.match && p12EeClass.match) {
            pass("Probe 12 — regulator_onboarding_sessions examinerName+examinerEmail (startOnboardingSession write path)", true, "ENC:v1:", "Both PII columns ENC:v1: — startOnboardingSession encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 12 — regulator_onboarding_sessions examinerName+examinerEmail (startOnboardingSession write path)", p12EnClass.match && p12EeClass.match, `examinerName:${p12EnClass.cls} examinerEmail:${p12EeClass.cls}`, p12Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p12Inserted) {
            try {
              await db.execute(sql`DELETE FROM regulator_onboarding_sessions WHERE started_by = ${p12Marker}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 12 cleanup FAILED started_by=${p12Marker}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 13 — examiner_tokens (examinerName + examinerEmail)
        // Write path: issueExaminerToken() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT; marker = issuedBy field (stored plaintext)
        // Note: issueExaminerToken has no audit chain writes — probeMode not needed.
        // ════════════════════════════════════════════════════════════════════

        const { issueExaminerToken } = await import("./lib/pilot-readiness-extras-9");

        const p13Marker = `${runId}-P13`;
        let p13Inserted = false;

        try {
          await issueExaminerToken({
            examinerName: "PROBE EXAMINER P13",
            examinerEmail: "probe13@enc.internal",
            scopes: ["audit"],
            ttlHours: 1,
            issuedBy: p13Marker,
          });
          p13Inserted = true;

          const p13Res = await db.execute(sql`
            SELECT LEFT(examiner_name, 20) AS prefix_en, LEFT(examiner_email, 20) AS prefix_ee
            FROM examiner_tokens WHERE issued_by = ${p13Marker}
          `);
          const p13Row = (p13Res as any).rows?.[0] as { prefix_en?: string; prefix_ee?: string } | undefined;
          const p13EnClass = classifyPrefix(p13Row?.prefix_en);
          const p13EeClass = classifyPrefix(p13Row?.prefix_ee);

          if (p13Row && p13EnClass.match && p13EeClass.match) {
            pass("Probe 13 — examiner_tokens examinerName+examinerEmail (issueExaminerToken write path)", true, "ENC:v1:", "Both PII columns ENC:v1: — issueExaminerToken encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 13 — examiner_tokens examinerName+examinerEmail (issueExaminerToken write path)", p13EnClass.match && p13EeClass.match, `examinerName:${p13EnClass.cls} examinerEmail:${p13EeClass.cls}`, p13Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p13Inserted) {
            try {
              await db.execute(sql`DELETE FROM examiner_tokens WHERE issued_by = ${p13Marker}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 13 cleanup FAILED issued_by=${p13Marker}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 14 — model_cards_v2 (ownerEmail)
        // Write path: upsertModelCard() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT; marker = modelKey (unique conflict target)
        // ════════════════════════════════════════════════════════════════════

        const { upsertModelCard } = await import("./lib/pilot-readiness-extras-10");

        const p14ModelKey = `${runId}-P14`;
        let p14Inserted = false;

        try {
          await upsertModelCard({
            modelKey: p14ModelKey,
            modelName: "PROBE MODEL P14",
            modelVersion: "0.0.1-probe",
            modelType: "classification",
            vendor: "PROBE VENDOR",
            purpose: "Encryption probe test model card",
            trainingData: "synthetic",
            ownerEmail: "probe14@enc.internal",
          });
          p14Inserted = true;

          const p14Res = await db.execute(sql`
            SELECT LEFT(owner_email, 20) AS prefix_oe
            FROM model_cards_v2 WHERE model_key = ${p14ModelKey}
          `);
          const p14Row = (p14Res as any).rows?.[0] as { prefix_oe?: string } | undefined;
          const p14OeClass = classifyPrefix(p14Row?.prefix_oe);

          if (p14Row && p14OeClass.match) {
            pass("Probe 14 — model_cards_v2 ownerEmail (upsertModelCard write path)", true, "ENC:v1:", "ownerEmail stores ENC:v1: — upsertModelCard encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 14 — model_cards_v2 ownerEmail (upsertModelCard write path)", p14OeClass.match, p14OeClass.cls, p14Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p14Inserted) {
            try {
              await db.execute(sql`DELETE FROM model_cards_v2 WHERE model_key = ${p14ModelKey}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 14 cleanup FAILED model_key=${p14ModelKey}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 15 — vendor_risk_register (contactEmail)
        // Write path: upsertVendor() → encryptPii() → INSERT
        // Tier 1: real service path, clean INSERT; marker = vendorKey (unique conflict target)
        // ════════════════════════════════════════════════════════════════════

        const { upsertVendor } = await import("./lib/pilot-readiness-extras-10");

        const p15VendorKey = `${runId}-P15`;
        let p15Inserted = false;

        try {
          await upsertVendor({
            vendorKey: p15VendorKey,
            vendorName: "PROBE VENDOR P15",
            category: "cloud",
            contactEmail: "probe15@enc.internal",
            riskScore: 0,
            riskTier: "LOW",
          });
          p15Inserted = true;

          const p15Res = await db.execute(sql`
            SELECT LEFT(contact_email, 20) AS prefix_ce
            FROM vendor_risk_register WHERE vendor_key = ${p15VendorKey}
          `);
          const p15Row = (p15Res as any).rows?.[0] as { prefix_ce?: string } | undefined;
          const p15CeClass = classifyPrefix(p15Row?.prefix_ce);

          if (p15Row && p15CeClass.match) {
            pass("Probe 15 — vendor_risk_register contactEmail (upsertVendor write path)", true, "ENC:v1:", "contactEmail stores ENC:v1: — upsertVendor encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 15 — vendor_risk_register contactEmail (upsertVendor write path)", p15CeClass.match, p15CeClass.cls, p15Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p15Inserted) {
            try {
              await db.execute(sql`DELETE FROM vendor_risk_register WHERE vendor_key = ${p15VendorKey}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 15 cleanup FAILED vendor_key=${p15VendorKey}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 16 — scim_provisions (userName + email)
        // Write path: createScimProvision() → encryptPii() → INSERT  [Tier 2 extract+repoint]
        // Probe calls the extracted helper directly — same code the POST route now calls.
        // marker = externalId field (stored plaintext, not subject to encryption)
        // ════════════════════════════════════════════════════════════════════

        const { createScimProvision } = await import("./lib/scim");

        const p16ExternalId = `${runId}-P16`;
        let p16Inserted = false;

        try {
          await createScimProvision({
            tenantId: probeTenantId,
            externalId: p16ExternalId,
            userName: "probe-scim-user-p16",
            displayName: "PROBE SCIM DISPLAY P16",
            email: "probe16@enc.internal",
          });
          p16Inserted = true;

          const p16Res = await db.execute(sql`
            SELECT LEFT(user_name, 20) AS prefix_un, LEFT(email, 20) AS prefix_em,
                   LEFT(display_name, 20) AS prefix_dn
            FROM scim_provisions WHERE external_id = ${p16ExternalId}
          `);
          const p16Row = (p16Res as any).rows?.[0] as { prefix_un?: string; prefix_em?: string; prefix_dn?: string } | undefined;
          const p16UnClass = classifyPrefix(p16Row?.prefix_un);
          const p16EmClass = classifyPrefix(p16Row?.prefix_em);
          const p16DnClass = classifyPrefix(p16Row?.prefix_dn);

          if (p16Row && p16UnClass.match && p16EmClass.match && p16DnClass.match) {
            pass("Probe 16 — scim_provisions userName+email+displayName (createScimProvision write path, Tier 2 extract+repoint)", true, "ENC:v1:", "All 3 PII columns ENC:v1: — createScimProvision encrypts via scimPiiCtx(tenantId) before INSERT");
          } else {
            fail("Probe 16 — scim_provisions userName+email+displayName (createScimProvision write path, Tier 2 extract+repoint)", false, `userName:${p16UnClass.cls} email:${p16EmClass.cls} displayName:${p16DnClass.cls}`, p16Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p16Inserted) {
            try {
              await db.execute(sql`DELETE FROM scim_provisions WHERE external_id = ${p16ExternalId}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 16 cleanup FAILED external_id=${p16ExternalId}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 16b — scim_provisions displayName truthy guard (empty-string not encrypted)
        // Documents the conditional-semantic decision in createScimProvision():
        // truthy guard (not != null) → empty string "" bypasses encryptPii(), stored as-is.
        // True refactor: matches pre-extract if (body.displayName) semantics exactly.
        // Expected: display_name = "" or null → classifyPrefix → "null-or-empty" (not ENC:v1:).
        // ════════════════════════════════════════════════════════════════════

        {
          const p16bExternalId = `${runId}-P16B`;
          let p16bInserted = false;
          try {
            await createScimProvision({
              tenantId:    probeTenantId,
              externalId:  p16bExternalId,
              userName:    "probe-scim-p16b",
              displayName: "",   // empty string — truthy guard → not encrypted
            });
            p16bInserted = true;

            const p16bRes = await db.execute(sql`
              SELECT display_name FROM scim_provisions WHERE external_id = ${p16bExternalId}
            `);
            const p16bRow = (p16bRes as any).rows?.[0] as { display_name?: string | null } | undefined;
            const p16bDn = p16bRow?.display_name;
            // PASS condition: stored as "" or null — classifyPrefix would return "null-or-empty"
            // meaning the truthy guard correctly skipped encryptPii() for empty string.
            if (p16bRow !== undefined && (p16bDn === "" || p16bDn === null)) {
              pass(
                "Probe 16b — scim_provisions displayName truthy guard (empty-string not encrypted)",
                true,
                "plaintext",
                `displayName="" stored as ${p16bDn === "" ? '""' : "null"} — truthy guard skips encryptPii() for empty/null; true refactor matches pre-extract route`,
              );
            } else {
              fail(
                "Probe 16b — scim_provisions displayName truthy guard (empty-string not encrypted)",
                false,
                `display_name: ${String(p16bDn ?? "").substring(0, 20)}`,
                p16bRow !== undefined
                  ? "Expected empty string or null — guard may have changed from truthy to != null"
                  : "No row found after INSERT",
              );
            }
          } finally {
            if (p16bInserted) {
              try {
                await db.execute(sql`DELETE FROM scim_provisions WHERE external_id = ${p16bExternalId}`);
              } catch (cleanErr) {
                cleanupFailures++;
                probeLogger.error(`[encryption-probe] Probe 16b cleanup FAILED external_id=${p16bExternalId}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
                const last = probeResults[probeResults.length - 1];
                if (last) last.cleanupFailed = true;
              }
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 17 — key_inventory (ownerEmail)
        // Write path: seedKeyInventory() at boot → encryptPii() → INSERT
        // Tier 3: read-only probe — seedKeyInventory is the sole writer, runs only at boot.
        // No INSERT/DELETE — stale-sweep and residual-check have no entry for this table.
        // ════════════════════════════════════════════════════════════════════

        {
          const p17Res = await db.execute(sql`
            SELECT LEFT(owner_email, 20) AS prefix_oe FROM key_inventory LIMIT 1
          `);
          const p17Row = (p17Res as any).rows?.[0] as { prefix_oe?: string } | undefined;

          if (!p17Row) {
            probeResults.push({
              probe:   "Probe 17 — key_inventory ownerEmail (seedKeyInventory boot path, Tier 3 read-only)",
              result:  "SKIP" as any,
              encryptedPrefixMatch: false,
              observedPrefixClass:  "NO_ROWS",
              detail:  "No boot-seeded key_inventory rows found — seedKeyInventory has not run yet on this database; Tier 3 read probe skipped (not a write-path failure).",
            });
          } else {
            const p17OeClass = classifyPrefix(p17Row.prefix_oe);
            if (p17OeClass.match) {
              pass("Probe 17 — key_inventory ownerEmail (seedKeyInventory boot path, Tier 3 read-only)", true, "ENC:v1:", "Existing ownerEmail ENC:v1: — boot-seeded rows written by seedKeyInventory with encryption confirmed");
            } else {
              fail("Probe 17 — key_inventory ownerEmail (seedKeyInventory boot path, Tier 3 read-only)", false, p17OeClass.cls, "Boot-seeded key_inventory row has non-ENC prefix — seedKeyInventory encryption path not writing ciphertext");
            }
          }
        }

        // ════════════════════════════════════════════════════════════════════
        // PROBE 18 — users (fullName)
        // Write path: storage.createUser() → encryptPii() → INSERT
        // Tier 4: real write path via storage, marked test entity + guaranteed DELETE.
        // username marker: probe-enc-<runId>@probe.internal (unique per run).
        // isActive: false — cannot log in even if password somehow matched.
        // ════════════════════════════════════════════════════════════════════

        const p18Username = `probe-enc-${runId}@probe.internal`;
        let p18UserId: string | null = null;

        try {
          const p18User = await storage.createUser({
            username: p18Username,
            password: `PROBE-UNUSABLE-${runId}`,
            role: "auditor" as any,
            fullName: "PROBE FULL NAME P18",
            isActive: false,
          } as any);
          p18UserId = (p18User as any).id as string;

          const p18Res = await db.execute(sql`
            SELECT LEFT(full_name, 20) AS prefix_fn
            FROM users WHERE id = ${p18UserId}
          `);
          const p18Row = (p18Res as any).rows?.[0] as { prefix_fn?: string } | undefined;
          const p18FnClass = classifyPrefix(p18Row?.prefix_fn);

          if (p18Row && p18FnClass.match) {
            pass("Probe 18 — users.fullName (storage.createUser() write path, Tier 4: real path + marked entity)", true, "ENC:v1:", "fullName stores ENC:v1: — createUser() encrypts via PLATFORM_CTX before INSERT");
          } else {
            fail("Probe 18 — users.fullName (storage.createUser() write path, Tier 4: real path + marked entity)", p18FnClass.match, p18FnClass.cls, p18Row ? "Column prefix mismatch" : "No row found after INSERT");
          }
        } finally {
          if (p18UserId) {
            try {
              await db.execute(sql`DELETE FROM users WHERE id = ${p18UserId}`);
            } catch (cleanErr) {
              cleanupFailures++;
              probeLogger.error(`[encryption-probe] Probe 18 cleanup FAILED username=${p18Username}`, { error: cleanErr instanceof Error ? cleanErr : new Error(String(cleanErr)) });
              const last = probeResults[probeResults.length - 1];
              if (last) last.cleanupFailed = true;
            }
          }
        }

        // ── BC-2 post-run residual check — 17 marker tables ──────────────────
        // P17 (key_inventory) is read-only — no marker row, no entry here.
        const residualResults = await Promise.all([
          db.execute(sql`SELECT count(*)::int AS cnt FROM decision_scoring_outputs WHERE decision_id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM dsar_requests WHERE description LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM pam_sessions WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM kyc_customers WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM ubo_registrations WHERE registered_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM auditor_credentials WHERE created_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM biometric_profiles WHERE user_id = ${"9999999"}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM suspicious_activity_reports WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM explanation_dossiers WHERE id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM ombudsman_complaints WHERE category LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM momo_sandbox_txns WHERE txn_type LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM regulator_onboarding_sessions WHERE started_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM examiner_tokens WHERE issued_by LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM model_cards_v2 WHERE model_key LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM vendor_risk_register WHERE vendor_key LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM scim_provisions WHERE external_id LIKE ${'ENC-PROBE-%'}`),
          db.execute(sql`SELECT count(*)::int AS cnt FROM users WHERE username LIKE ${'probe-enc-ENC-PROBE-%@probe.internal'}`),
        ]);
        const residualRows = residualResults.reduce(
          (acc, r) => acc + ((((r as any).rows?.[0]) as any)?.cnt ?? 0), 0,
        );
        if (residualRows > 0) {
          probesFailed++;
          probeResults.push({
            probe:   "Residual check — BC-2 post-run cleanup verification (17 tables)",
            result:  "FAIL",
            encryptedPrefixMatch: false,
            observedPrefixClass:  "n/a",
            detail:  `${residualRows} probe row(s) remain after cleanup across 17 marker tables — manual DELETE required`,
          });
        } else {
          probesPassed++;
          probeResults.push({
            probe:   "Residual check — BC-2 post-run cleanup verification (17 tables)",
            result:  "PASS",
            encryptedPrefixMatch: false,
            observedPrefixClass:  "n/a",
            detail:  "0 probe rows remain across all 17 marker tables — cleanup confirmed",
          });
        }

        const allPass = probesFailed === 0 && cleanupFailures === 0 && residualRows === 0;
        const elapsedMs = Date.now() - startMs;

        probeLogger.info(
          `[encryption-probe] COMPLETE runId=${runId} allPass=${allPass} passed=${probesPassed} failed=${probesFailed} cleanupFailures=${cleanupFailures} residualRows=${residualRows} elapsedMs=${elapsedMs}`,
        );

        return res.json({
          runId,
          environment: process.env.NODE_ENV ?? "unknown",
          invoker,
          tenantId:     probeTenantId,
          elapsedMs,
          probes:       probeResults,
          summary: {
            total:          probeResults.length,
            passed:         probesPassed,
            failed:         probesFailed,
            cleanupFailures,
            staleMarkersFound,
            residualRows,
            allPass,
          },
        });
      } finally {
        encryptionProbeRunning = false;
      }
    }),
  );

  // Handle 404 for API routes - simple middleware approach for Express 5
  app.use((req, res, next) => {
    if (req.path.startsWith("/api/") && !res.headersSent) {
      return notFoundHandler(req, res);
    }
    next();
  });

  // Register global error handler (must be last)
  app.use(globalErrorHandler);

  return httpServer;
}

// Extend session types
// Session augmentation: declare the userId/userRole + CSRF fields used by the
// app. The CSRF fields back the FU-005 multi-instance migration (Task #2):
// instead of an in-process Map keyed by sessionID, the token rides along
// with the session itself, which is pg-backed via connect-pg-simple.
declare module "express-session" {
  interface SessionData {
    userId: string;
    userRole: string;
    // FU-053 Deliverable 7 (2b): tenantId is DB-derived at login (from the
    // user's active primary user_tenant_roles row) and written post-regenerate.
    // Non-optional by convention — follows userId/userRole pattern. Absent
    // pre-login; tenant-middleware reads it as (req.session as any)?.tenantId
    // which tolerates undefined for pre-auth requests.
    tenantId: string;
    // FU-005 amendment 3 (Task #2): CSRF token now lives on the session
    // itself instead of an in-process Map, making the protection multi-
    // instance-safe via the existing pg-backed connect-pg-simple store.
    csrfToken?: string;
    csrfMintedAt?: number;
    // Step-up authentication (auth-hardening tranche 1): a fresh second-factor challenge
    // (TOTP if enrolled, else password) gates sensitive actions via requireStepUp. steppedUpAt
    // is the epoch-ms of the last successful step-up; stepUpDemanded is set true when the
    // behavioral-biometrics signal flags an anomaly, forcing a re-step-up before the next gated action.
    steppedUpAt?: number;
    stepUpDemanded?: boolean;
    // Concurrent-session cap (auth-hardening tranche 2): stamped at login so a user can see and
    // manage their active sessions, and so the per-user session cap can evict the oldest.
    loginAt?: number;
    loginIp?: string;
    // Session idle timeout (auth-hardening tranche 3): epoch-ms of the last activity; the /api
    // middleware expires the session after SESSION_IDLE_MS of inactivity and caps it at
    // SESSION_ABSOLUTE_MS from loginAt.
    lastActivityAt?: number;
  }
}
