{
  "version": 3,
  "sources": ["../server.ts", "../src/services/agentServiceServer.ts", "../src/lib/bridgeSecurity.ts", "../src/lib/storefrontBridge.ts", "../src/lib/units.ts", "../src/lib/studioOperations.ts", "../src/services/bridgeRouter.ts", "../src/lib/interAppCapsule.ts", "../src/services/storefrontRouter.ts", "../src/lib/quebecCompliance.ts", "../src/lib/authGate.ts", "../src/lib/b2bPricing.ts"],
  "sourcesContent": ["import \"dotenv/config\";\nimport express from \"express\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { initializeApp, getApps, cert, type ServiceAccount } from \"firebase-admin/app\";\nimport { getAuth } from \"firebase-admin/auth\";\nimport { getFirestore } from \"firebase-admin/firestore\";\nimport { getAgentResponseServer } from \"./src/services/agentServiceServer.js\";\nimport { createBridgeRouter } from \"./src/services/bridgeRouter.js\";\nimport { createStorefrontRouter } from \"./src/services/storefrontRouter.js\";\nimport {\n  AUTHORIZED_EMAILS,\n  isAllowedOrigin,\n  isAuthorizedEmail,\n} from \"./src/lib/authGate.js\";\nimport { computeB2BKitTiers } from \"./src/lib/b2bPricing.js\";\n\nfunction getServerDir(): string {\n  return typeof __dirname === \"string\" ? __dirname : process.cwd();\n}\n\nfunction readFirebaseConfig(): { projectId?: string; firestoreDatabaseId?: string } {\n  const serverDir = getServerDir();\n  const candidates = [\n    path.join(process.cwd(), \"firebase-applet-config.json\"),\n    path.resolve(serverDir, \"firebase-applet-config.json\"),\n    path.resolve(serverDir, \"..\", \"firebase-applet-config.json\"),\n  ];\n  for (const cfgPath of candidates) {\n    try {\n      if (fs.existsSync(cfgPath)) {\n        return JSON.parse(fs.readFileSync(cfgPath, \"utf-8\"));\n      }\n    } catch (err) {\n      console.warn(\"Could not read firebase-applet-config.json:\", err);\n    }\n  }\n  return {};\n}\n\nfunction parseServiceAccountFromEnv(): ServiceAccount | null {\n  const raw = (process.env.FIREBASE_SERVICE_ACCOUNT_JSON || \"\").trim();\n  if (!raw) return null;\n  try {\n    const jsonText = raw.startsWith(\"{\")\n      ? raw\n      : Buffer.from(raw, \"base64\").toString(\"utf8\");\n    const parsed = JSON.parse(jsonText) as ServiceAccount;\n    if (parsed && typeof parsed === \"object\" && (parsed as any).client_email && (parsed as any).private_key) {\n      return parsed;\n    }\n  } catch (err) {\n    console.warn(\"Could not parse FIREBASE_SERVICE_ACCOUNT_JSON:\", err);\n  }\n  return null;\n}\n\nfunction initFirebaseAdmin() {\n  if (getApps().length > 0) return;\n  const cfg = readFirebaseConfig();\n  const projectId = process.env.GOOGLE_CLOUD_PROJECT || process.env.GCLOUD_PROJECT || cfg.projectId;\n  const serviceAccount = parseServiceAccountFromEnv();\n\n  if (serviceAccount) {\n    initializeApp({\n      credential: cert(serviceAccount),\n      ...(projectId ? { projectId } : {}),\n    });\n    return;\n  }\n\n  initializeApp(projectId ? { projectId } : undefined);\n}\n\nfunction getFirestoreDb() {\n  const cfg = readFirebaseConfig();\n  return cfg.firestoreDatabaseId\n    ? getFirestore(getApps()[0], cfg.firestoreDatabaseId)\n    : getFirestore(getApps()[0]);\n}\n\nasync function resolveOwnerUid(db: ReturnType<typeof getFirestore>): Promise<string | null> {\n  for (const email of AUTHORIZED_EMAILS) {\n    try {\n      const ownerRecord = await getAuth().getUserByEmail(email);\n      if (ownerRecord?.uid) return ownerRecord.uid;\n    } catch {\n      // Continue checking next authorized owner email\n    }\n  }\n  try {\n    const snap = await db.collection(\"profiles\").limit(1).get();\n    if (!snap.empty) {\n      return snap.docs[0].id;\n    }\n  } catch {\n    return null;\n  }\n  return null;\n}\n\nasync function requireStudioOwner(req: express.Request, res: express.Response, next: express.NextFunction) {\n  try {\n    const authHeader = req.headers.authorization;\n    if (!authHeader || !authHeader.startsWith(\"Bearer \")) {\n      return res.status(401).json({ error: \"Authentication required. Missing Bearer token.\" });\n    }\n    const idToken = authHeader.slice(7).trim();\n    if (!idToken) {\n      return res.status(401).json({ error: \"Authentication required. Empty Bearer token.\" });\n    }\n\n    const decoded = await getAuth().verifyIdToken(idToken);\n    if (!decoded.email_verified || !isAuthorizedEmail(decoded.email)) {\n      return res.status(403).json({ error: \"Access denied. Account is not an authorized verified studio owner.\" });\n    }\n\n    (req as any).studioUser = decoded;\n    return next();\n  } catch (err: any) {\n    console.warn(\"Token verification failed on /api/agent/response:\", err?.code || err?.message);\n    return res.status(401).json({ error: \"Invalid or expired authentication session.\" });\n  }\n}\n\nfunction resolveDistDir(): string {\n  const serverDir = getServerDir();\n  const candidates = [\n    path.join(process.cwd(), \"dist\"),\n    path.resolve(serverDir, \"dist\"),\n    path.resolve(serverDir, \"..\", \"dist\"),\n  ];\n  for (const dir of candidates) {\n    if (fs.existsSync(path.join(dir, \"index.html\"))) {\n      return dir;\n    }\n  }\n  return path.join(process.cwd(), \"dist\");\n}\n\nasync function startServer() {\n  initFirebaseAdmin();\n  const app = express();\n  const rawPort = (process.env.PORT || \"\").trim();\n  const PORT: string | number = rawPort\n    ? /^\\d+$/.test(rawPort)\n      ? Number(rawPort)\n      : rawPort\n    : 3000;\n\n  // Respect X-Forwarded-For behind Namecheap / Passenger / proxy load balancer\n  app.set(\"trust proxy\", 1);\n\n  // Security Headers & Origin Allowlist CORS Middleware (artisan.ljwellness.net & ljwellness.net)\n  app.use((req, res, next) => {\n    res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n    res.setHeader(\"X-Frame-Options\", \"SAMEORIGIN\");\n    res.setHeader(\"Referrer-Policy\", \"strict-origin-when-cross-origin\");\n\n    const origin = req.headers.origin;\n    if (origin && isAllowedOrigin(origin, process.env.APP_URL)) {\n      res.setHeader(\"Access-Control-Allow-Origin\", origin);\n      res.setHeader(\"Vary\", \"Origin\");\n      res.setHeader(\n        \"Access-Control-Allow-Headers\",\n        \"Content-Type, Authorization, X-Bridge-Key, X-Bridge-Timestamp, X-Bridge-Signature\",\n      );\n      res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\");\n      if (req.method === \"OPTIONS\") {\n        return res.status(204).end();\n      }\n    } else if (origin && req.path.startsWith(\"/api/\") && req.method === \"OPTIONS\") {\n      return res.status(403).json({ error: \"Origin not permitted by studio policy.\" });\n    }\n    next();\n  });\n\n  app.use(express.json({\n    limit: \"2mb\",\n    verify: (req: any, _res, buf) => {\n      req.rawBody = buf;\n    },\n  }));\n  app.use(express.urlencoded({ extended: true, limit: \"2mb\" }));\n\n  // In-memory rate limiter (120 requests per minute per IP)\n  const ipRequests = new Map<string, { count: number; resetTime: number }>();\n  const rateLimiter = (req: express.Request, res: express.Response, next: express.NextFunction) => {\n    const ip = req.ip || req.socket.remoteAddress || 'unknown';\n    const now = Date.now();\n    const entry = ipRequests.get(ip) || { count: 0, resetTime: now + 60000 };\n\n    if (now > entry.resetTime) {\n      entry.count = 1;\n      entry.resetTime = now + 60000;\n    } else {\n      entry.count += 1;\n    }\n\n    ipRequests.set(ip, entry);\n\n    if (entry.count > 120) {\n      return res.status(429).json({ error: \"Rate limit exceeded. Please throttle requests.\" });\n    }\n    next();\n  };\n\n  // Stricter rate limiter for public inquiry/pre-order intake (10 submissions per 15 mins per IP)\n  const inquiryIpRequests = new Map<string, { count: number; resetTime: number }>();\n  const inquiryRateLimiter = (req: express.Request, res: express.Response, next: express.NextFunction) => {\n    const ip = req.ip || req.socket.remoteAddress || \"unknown\";\n    const now = Date.now();\n    const windowMs = 15 * 60 * 1000;\n    const entry = inquiryIpRequests.get(ip) || { count: 0, resetTime: now + windowMs };\n    if (now > entry.resetTime) {\n      entry.count = 1;\n      entry.resetTime = now + windowMs;\n    } else {\n      entry.count += 1;\n    }\n    inquiryIpRequests.set(ip, entry);\n    if (entry.count > 10) {\n      return res.status(429).json({ error: \"Too many inquiry submissions. Please wait a few minutes before retrying.\" });\n    }\n    next();\n  };\n\n  // API Route: Health check\n  app.get(\"/api/health\", (req, res) => {\n    res.json({ \n      status: \"healthy\", \n      timestamp: new Date().toISOString() \n    });\n  });\n\n  // API Route: Public B2B Sample Box & Pre-Order Inquiry Intake\n  app.post(\"/api/inquiries\", inquiryRateLimiter, async (req, res) => {\n    try {\n      const body = req.body || {};\n      const companyName = String(body.companyName || \"\").trim().slice(0, 200);\n      const contactPerson = String(body.contactPerson || \"\").trim().slice(0, 160);\n      const email = String(body.email || \"\").trim().slice(0, 200);\n      const phone = String(body.phone || \"\").trim().slice(0, 60);\n      const allowedTypes = [\n        \"Luxury Builder\",\n        \"Condo Developer\",\n        \"Rental Developer\",\n        \"Realtor\",\n        \"Architecture / Design\",\n        \"Corporate Gifting\"\n      ];\n      const accountType = allowedTypes.includes(body.accountType) ? body.accountType : \"Luxury Builder\";\n      const audienceMode = body.audienceMode === \"renter\" ? \"renter\" : \"homeowner\";\n      const language = [\"en\", \"fr\", \"bilingual\"].includes(body.language) ? body.language : \"bilingual\";\n      const unitCount = Math.min(10000, Math.max(1, Math.round(Number(body.unitCount) || 10)));\n      const requestType = body.requestType === \"sample-box\" ? \"Sample Specimen Box\" : \"Pre-Order / Production Run\";\n      const handoverDate = String(body.handoverDate || \"\").trim().slice(0, 40);\n      const notes = String(body.notes || \"\").trim().slice(0, 1500);\n\n      if (!companyName || !contactPerson || !email || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {\n        return res.status(400).json({\n          error: \"Please provide company name, contact person, and a valid business email.\"\n        });\n      }\n\n      const tiers = computeB2BKitTiers({\n        botanicalUnitCost: 14,\n        specimenBoxCost: 8.5,\n        customBinderPrintCost: 16,\n        wholesaleBinderPrintCost: 11,\n        qrInsertCardCost: 1.25,\n        customAssemblyCost: 6,\n        wholesaleAssemblyCost: 2.5,\n        overheadPerKit: 12,\n        shippingFreightPerKit: 2.25,\n        insuranceTestingPerKit: 1.0,\n        spoilageBufferPct: 3,\n        paymentProcessingPct: 2.9,\n        customTargetMarginPct: 75,\n        wholesaleFloorMarginPct: 55\n      });\n\n      const selectedTier =\n        unitCount >= 50\n          ? tiers[3]\n          : unitCount >= 25\n            ? tiers[2]\n            : unitCount >= 10\n              ? tiers[1]\n              : tiers[0];\n\n      const totalEstimate = Number((selectedTier.recommendedPrice * unitCount).toFixed(2));\n      const deposit50Pct = Number((totalEstimate * 0.5).toFixed(2));\n\n      const db = getFirestoreDb();\n      const ownerUid = await resolveOwnerUid(db);\n\n      if (!ownerUid) {\n        return res.status(503).json({\n          error: \"Studio owner inbox is not initialized yet. Please contact the studio directly.\"\n        });\n      }\n\n      const nowIso = new Date().toISOString();\n      const today = nowIso.split(\"T\")[0];\n      const suffix = Math.random().toString(36).slice(2, 7).toUpperCase();\n      const referenceId = `LJW-${today.replace(/-/g, \"\")}-${suffix}`;\n      const accountId = `inq_${Date.now().toString(36)}_${suffix.toLowerCase()}`;\n      const taskId = `task_${Date.now().toString(36)}_${suffix.toLowerCase()}`;\n\n      const formattedNotes = [\n        `[${requestType}] Ref: ${referenceId}`,\n        `Units: ${unitCount} (${selectedTier.name}) | Audience: ${audienceMode === \"renter\" ? \"Resident / Renter (Lease)\" : \"Condo Buyer / Homeowner\"}`,\n        `Language Spec: ${language.toUpperCase()} (Loi 96)`,\n        `Indicative Quote: $${selectedTier.recommendedPrice.toFixed(2)}/kit \u00B7 Est. Total $${totalEstimate.toLocaleString()} \u00B7 50% Deposit $${deposit50Pct.toLocaleString()}`,\n        handoverDate ? `Target Handover: ${handoverDate}` : null,\n        notes ? `Project Notes: ${notes}` : null\n      ]\n        .filter(Boolean)\n        .join(\"\\n\");\n\n      await db.collection(\"corporate_accounts\").doc(accountId).set({\n        id: accountId,\n        uid: ownerUid,\n        companyName,\n        contactPerson,\n        email,\n        phone,\n        accountType,\n        nicheFocus: `${selectedTier.name} (${audienceMode})`,\n        annualBudgetPotential: totalEstimate,\n        status: \"Lead\",\n        notes: formattedNotes,\n        createdAt: today,\n        updatedAt: today\n      });\n\n      await db.collection(\"tasks\").doc(taskId).set({\n        id: taskId,\n        uid: ownerUid,\n        title: `Inbound B2B ${requestType}: ${companyName} (${unitCount} units)`,\n        description: `${contactPerson} (${email}${phone ? `, ${phone}` : \"\"}) submitted an inquiry via the public landing page.\\n\\n${formattedNotes}`,\n        assignedTo: \"Business\",\n        status: \"pending\",\n        priority: \"high\",\n        createdAt: today\n      });\n\n      return res.status(201).json({\n        ok: true,\n        referenceId,\n        estimate: {\n          tierName: selectedTier.name,\n          unitPrice: selectedTier.recommendedPrice,\n          totalEstimate,\n          deposit50Pct\n        }\n      });\n    } catch (error: any) {\n      console.error(\"Error saving public B2B inquiry:\", error);\n      return res.status(500).json({\n        error: \"Unable to record your inquiry right now. Please try again shortly.\"\n      });\n    }\n  });\n\n  let sharedWorkshopSnapshot: any = null;\n\n  // API Route: Authenticated Agent Interaction proxy with Gemini\n  app.post(\"/api/agent/response\", rateLimiter, requireStudioOwner, async (req, res) => {\n    try {\n      const { role, context, history, state } = req.body;\n      if (!role || !context) {\n        return res.status(400).json({ error: \"Missing required fields: role and context are required.\" });\n      }\n      if (state && typeof state === \"object\") {\n        sharedWorkshopSnapshot = state;\n      }\n\n      const response = await getAgentResponseServer(role, context, history || [], state);\n      return res.json(response);\n    } catch (error: any) {\n      console.error(\"API error inside /api/agent/response:\", error);\n      return res.status(500).json({\n        error: \"External cognitive synchronization failure.\",\n        ...(process.env.NODE_ENV !== \"production\" ? { details: error?.message } : {})\n      });\n    }\n  });\n\n  // API Route: 2-Way Inter-App Intelligence Bridge (InterAppCapsule v1.0.0)\n  app.use(\n    \"/api/bridge\",\n    rateLimiter,\n    createBridgeRouter({\n      getDb: getFirestoreDb,\n      resolveOwnerUid,\n      requireStudioOwner,\n    }),\n  );\n\n  // API Route: LJWellness Storefront <-> StudioOS Connector (ljw-storefront-v1)\n  app.use(\n    \"/api/storefront\",\n    rateLimiter,\n    createStorefrontRouter({\n      getDb: getFirestoreDb,\n      resolveOwnerUid,\n      requireStudioOwner,\n      getWorkshopSnapshot: () => sharedWorkshopSnapshot,\n      setWorkshopSnapshot: (snap) => {\n        sharedWorkshopSnapshot = snap;\n      },\n    }),\n  );\n\n  // Unknown API endpoints return JSON 404 rather than HTML SPA fallback\n  app.use(\"/api\", (_req, res) => {\n    res.status(404).json({ error: \"API route not found.\" });\n  });\n\n  // Vite middleware for development (dynamically imported so production runtime does not require vite)\n  if (process.env.NODE_ENV !== \"production\") {\n    // Prevent the browser from caching development assets (index.html, chunk hashes, etc.)\n    app.use((req, res, next) => {\n      res.setHeader(\"Cache-Control\", \"no-store, no-cache, must-revalidate, proxy-revalidate\");\n      res.setHeader(\"Pragma\", \"no-cache\");\n      res.setHeader(\"Expires\", \"0\");\n      res.setHeader(\"Surrogate-Control\", \"no-store\");\n      next();\n    });\n\n    const { createServer: createViteServer } = await import(\"vite\");\n    const vite = await createViteServer({\n      server: { middlewareMode: true },\n      appType: \"spa\",\n    });\n    app.use(vite.middlewares);\n  } else {\n    const distPath = resolveDistDir();\n    app.use(express.static(distPath));\n    app.get(\"*\", (_req, res) => {\n      res.sendFile(path.join(distPath, \"index.html\"));\n    });\n  }\n\n  if (typeof PORT === \"string\") {\n    app.listen(PORT, () => {\n      console.log(`Artisan 2nd Brain listening on socket ${PORT}`);\n    });\n  } else {\n    app.listen(PORT, \"0.0.0.0\", () => {\n      console.log(`Artisan 2nd Brain running on http://localhost:${PORT}`);\n    });\n  }\n}\n\nstartServer();\n", "import { GoogleGenAI, Type, FunctionDeclaration } from \"@google/genai\";\nimport type { AgentRole, IncomingOrderQuote, Message } from \"../types.js\";\nimport {\n  auditStudioInventory,\n  buildSkuBomCatalog,\n  evaluateCollectionAndFormulationCogs,\n  evaluateIncomingOrderOrQuote,\n  STUDIO_PRICING_RULES,\n} from \"../lib/studioOperations.js\";\nimport { buildDefaultAgreementCatalog, type StorefrontAgreementCatalog } from \"../lib/storefrontBridge.js\";\n\n// Initialize Gemini on the server side with the telemetry User-Agent header\nconst ai = new GoogleGenAI({\n  apiKey: process.env.GEMINI_API_KEY || \"\",\n  httpOptions: {\n    headers: {\n      'User-Agent': 'aistudio-build',\n    }\n  }\n});\n\nexport function shouldUseGeminiForHeadlessIntake(\n  environment: IncomingOrderQuote[\"environment\"],\n  apiKey = process.env.GEMINI_API_KEY,\n  nodeEnvironment = process.env.NODE_ENV,\n): boolean {\n  return environment !== \"staging\" && Boolean(apiKey) && nodeEnvironment !== \"test\";\n}\n\nconst create_task: FunctionDeclaration = {\n  name: \"create_task\",\n  description: \"Create a new production task or directive in the workshop.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      title: { type: Type.STRING, description: \"Short title of the task\" },\n      description: { type: Type.STRING, description: \"Detailed description of what needs to be done\" },\n      assignedTo: { type: Type.STRING, enum: ['StudioLead', 'Formulator', 'Business', 'Marketing', 'NicheExpert', 'WealthAdvisor', 'Mentor'], description: \"The specialist to handle this task\" },\n      priority: { type: Type.STRING, enum: ['low', 'medium', 'high'], description: \"Task priority\" }\n    },\n    required: [\"title\", \"description\", \"assignedTo\", \"priority\"]\n  }\n};\n\nconst complete_task: FunctionDeclaration = {\n  name: \"complete_task\",\n  description: \"Mark a pending task or directive as completed in the workshop database after performing the work or generating the required output.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      taskId: { type: Type.STRING, description: \"The ID of the task to complete (e.g., 't1', 't2') or task title\" },\n      completionNotes: { type: Type.STRING, description: \"Summary of the completed work, formulations, or decisions\" },\n      actualOutcome: { type: Type.STRING, description: \"The tangible result produced (e.g. 'Formulation created and logged', 'Inventory restocked')\" }\n    },\n    required: [\"taskId\"]\n  }\n};\n\nconst batch_complete_tasks: FunctionDeclaration = {\n  name: \"batch_complete_tasks\",\n  description: \"Mark multiple or all pending tasks as completed when executing bulk directives or clearing the backlog.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      taskIds: { \n        type: Type.ARRAY, \n        items: { type: Type.STRING },\n        description: \"List of task IDs to complete (or leave empty if completing by role)\" \n      },\n      assignedTo: { \n        type: Type.STRING, \n        enum: ['all', 'StudioLead', 'Formulator', 'Business', 'Marketing', 'NicheExpert', 'WealthAdvisor', 'Mentor'],\n        description: \"Complete all pending tasks assigned to this specialist role, or 'all'\" \n      },\n      summaryNotes: { type: Type.STRING, description: \"Overall summary of work executed for these directives\" }\n    },\n    required: [\"summaryNotes\"]\n  }\n};\n\nconst update_task_status: FunctionDeclaration = {\n  name: \"update_task_status\",\n  description: \"Update the status of a specific task.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      taskId: { type: Type.STRING, description: \"The ID of the task\" },\n      status: { type: Type.STRING, enum: ['pending', 'in-progress', 'completed'], description: \"The new task status\" },\n      notes: { type: Type.STRING, description: \"Progress notes\" }\n    },\n    required: [\"taskId\", \"status\"]\n  }\n};\n\nconst update_inventory: FunctionDeclaration = {\n  name: \"update_inventory\",\n  description: \"Update the stock levels of raw materials or supplies in the workshop.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      item: { type: Type.STRING, description: \"Name of the material (e.g., Shea Butter, Lavender Oil)\" },\n      amount: { type: Type.NUMBER, description: \"The amount to add or remove\" },\n      action: { type: Type.STRING, enum: ['add', 'remove'], description: \"Whether to add to or remove from stock\" }\n    },\n    required: [\"item\", \"amount\", \"action\"]\n  }\n};\n\nconst create_asset: FunctionDeclaration = {\n  name: \"create_asset\",\n  description: \"Save a marketing campaign, strategy report, or branding guide. DO NOT use this for production recipes or formulations - use 'create_formulation' instead.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      title: { type: Type.STRING, description: \"Title of the asset\" },\n      content: { type: Type.STRING, description: \"The full content of the recipe, campaign, or report\" },\n      type: { type: Type.STRING, enum: ['recipe', 'marketing', 'strategy', 'legal', 'finance'], description: \"The category of the asset\" }\n    },\n    required: [\"title\", \"content\", \"type\"]\n  }\n};\n\nconst update_finance: FunctionDeclaration = {\n  name: \"update_finance\",\n  description: \"Record a financial transaction (income or expense) for the studio.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      amount: { type: Type.NUMBER, description: \"The dollar amount\" },\n      description: { type: Type.STRING, description: \"What the transaction was for\" },\n      type: { type: Type.STRING, enum: ['in', 'out'], description: \"Whether it's income (in) or an expense (out)\" }\n    },\n    required: [\"amount\", \"description\", \"type\"]\n  }\n};\n\nconst create_project: FunctionDeclaration = {\n  name: \"create_project\",\n  description: \"Initiate a new artisan series, collection, or product line.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      name: { type: Type.STRING, description: \"Name of the project/series\" },\n      stage: { type: Type.STRING, enum: ['Design', 'Formulation', 'Production', 'Marketing'], description: \"Initial stage\" },\n      health: { type: Type.STRING, enum: ['good', 'warning', 'danger'], description: \"Initial health status\" }\n    },\n    required: [\"name\", \"stage\", \"health\"]\n  }\n};\n\nconst create_wholesale_client: FunctionDeclaration = {\n  name: \"create_wholesale_client\",\n  description: \"Register a new B2B, wholesale, or white-label client.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      name: { type: Type.STRING, description: \"Business or client name\" },\n      type: { type: Type.STRING, enum: ['wholesale', 'white-label'], description: \"Partnership type\" },\n      contact: { type: Type.STRING, description: \"Contact email or phone\" },\n      status: { type: Type.STRING, enum: ['active', 'lead', 'inactive'], description: \"Initial status\" }\n    },\n    required: [\"name\", \"type\", \"contact\", \"status\"]\n  }\n};\n\nconst create_wholesale_order: FunctionDeclaration = {\n  name: \"create_wholesale_order\",\n  description: \"Process a new B2B or wholesale order for a client.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      clientId: { type: Type.STRING, description: \"The ID of the client (if known) or name\" },\n      items: {\n        type: Type.ARRAY,\n        items: {\n          type: Type.OBJECT,\n          properties: {\n            item: { type: Type.STRING, description: \"Product name\" },\n            quantity: { type: Type.NUMBER, description: \"Quantity ordered\" },\n            price: { type: Type.NUMBER, description: \"Unit price\" }\n          },\n          required: [\"item\", \"quantity\", \"price\"]\n        }\n      },\n      status: { type: Type.STRING, enum: ['pending', 'processing', 'shipped', 'delivered'], description: \"Order status\" }\n    },\n    required: [\"clientId\", \"items\", \"status\"]\n  }\n};\n\nconst create_prospect: FunctionDeclaration = {\n  name: \"create_prospect\",\n  description: \"Add a new potential client or business lead to the CRM.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      name: { type: Type.STRING, description: \"Contact name\" },\n      company: { type: Type.STRING, description: \"Company name (optional)\" },\n      source: { type: Type.STRING, description: \"Where the lead came from (e.g., Instagram, Referral)\" },\n      potentialValue: { type: Type.NUMBER, description: \"Estimated potential annual value\" },\n      notes: { type: Type.STRING, description: \"Initial notes or context\" }\n    },\n    required: [\"name\", \"source\", \"potentialValue\"]\n  }\n};\n\nconst add_event: FunctionDeclaration = {\n  name: \"add_event\",\n  description: \"Add a holiday, sale, market, or production deadline to the Studio Planner.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      title: { type: Type.STRING, description: \"Event name\" },\n      date: { type: Type.STRING, description: \"Date in YYYY-MM-DD format\" },\n      type: { \n        type: Type.STRING, \n        enum: [\"production\", \"marketing\", \"meeting\", \"holiday\", \"sale\", \"market\", \"workshop\", \"popup\", \"wholesale-deadline\"],\n        description: \"Type of event\" \n      },\n      category: {\n        type: Type.STRING,\n        enum: [\"Soap\", \"Candles\", \"Decor\", \"General\"],\n        description: \"Focus category\"\n      },\n      description: { type: Type.STRING, description: \"Details about the event\" }\n    },\n    required: [\"title\", \"date\", \"type\"]\n  }\n};\n\nconst delegate_to_agent: FunctionDeclaration = {\n  name: \"delegate_to_agent\",\n  description: \"Hand off the current task or specific inquiry to another specialist agent for deep analysis. Vital for collaborative studio operations.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      targetRole: { \n        type: Type.STRING, \n        enum: [\"StudioLead\", \"Formulator\", \"Business\", \"Marketing\", \"NicheExpert\", \"WealthAdvisor\", \"Mentor\"],\n        description: \"The role of the specialist to consult\" \n      },\n      reason: { type: Type.STRING, description: \"Why you are delegating (context for the next agent)\" }\n    },\n    required: [\"targetRole\", \"reason\"]\n  }\n};\n\nconst log_outreach: FunctionDeclaration = {\n  name: \"log_outreach\",\n  description: \"Record a contact attempt or meeting with a prospect.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      prospectId: { type: Type.STRING, description: \"The ID of the prospect\" },\n      method: { type: Type.STRING, enum: ['email', 'call', 'social', 'meeting'], description: \"Contact method\" },\n      notes: { type: Type.STRING, description: \"What was discussed\" },\n      outcome: { type: Type.STRING, description: \"The result of the outreach\" }\n    },\n    required: [\"prospectId\", \"method\", \"notes\", \"outcome\"]\n  }\n};\n\nconst update_prospect_status: FunctionDeclaration = {\n  name: \"update_prospect_status\",\n  description: \"Move a prospect through the sales funnel.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      prospectId: { type: Type.STRING, description: \"The ID of the prospect\" },\n      status: { type: Type.STRING, enum: ['cold', 'warm', 'hot', 'converted', 'lost'], description: \"New status\" }\n    },\n    required: [\"prospectId\", \"status\"]\n  }\n};\n\nconst create_campaign: FunctionDeclaration = {\n  name: \"create_campaign\",\n  description: \"Launch a new marketing campaign on a specific platform.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      name: { type: Type.STRING, description: \"Name of the campaign\" },\n      platform: { type: Type.STRING, enum: ['Instagram', 'TikTok', 'Email', 'Facebook', 'Pinterest', 'Other'], description: \"Target platform\" },\n      budget: { type: Type.NUMBER, description: \"Total budget for the campaign\" },\n      notes: { type: Type.STRING, description: \"Campaign goals or strategy\" },\n      content: { type: Type.STRING, description: \"Draft content or copy for the campaign\" }\n    },\n    required: [\"name\", \"platform\", \"budget\"]\n  }\n};\n\nconst update_campaign_budget: FunctionDeclaration = {\n  name: \"update_campaign_budget\",\n  description: \"Adjust the budget for an existing campaign. This will reflect as a cash outflow.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      campaignId: { type: Type.STRING, description: \"The ID of the campaign to update\" },\n      newBudget: { type: Type.NUMBER, description: \"The new total budget amount\" }\n    },\n    required: [\"campaignId\", \"newBudget\"]\n  }\n};\n\nconst analyze_market_trends: FunctionDeclaration = {\n  name: \"analyze_market_trends\",\n  description: \"Analyze current market trends for a specific niche or product type.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      niche: { type: Type.STRING, description: \"The niche to analyze (e.g., 'luxury candles', 'botanical skincare')\" },\n      focus: { type: Type.STRING, description: \"Specific focus (e.g., 'packaging', 'ingredients', 'pricing')\" }\n    },\n    required: [\"niche\"]\n  }\n};\n\nconst optimize_formula: FunctionDeclaration = {\n  name: \"optimize_formula\",\n  description: \"Suggest optimizations for a recipe or formula based on cost or safety.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      recipeId: { type: Type.STRING, description: \"The ID of the recipe to optimize\" },\n      goal: { type: Type.STRING, enum: ['cost', 'safety', 'performance'], description: \"The optimization goal\" }\n    },\n    required: [\"recipeId\", \"goal\"]\n  }\n};\n\nconst create_batch: FunctionDeclaration = {\n  name: \"create_batch\",\n  description: \"Record a new production batch for a specific recipe/collection.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      collectionId: { type: Type.STRING, description: \"The ID of the collection/product line\" },\n      recipeId: { type: Type.STRING, description: \"The ID of the recipe or name of the formulation used\" },\n      batchNumber: { type: Type.STRING, description: \"Unique batch identifier (e.g., LOT-2026-001)\" },\n      quantity: { type: Type.NUMBER, description: \"Total units produced\" },\n      notes: { type: Type.STRING, description: \"Production notes (e.g., temperature, humidity, deviations)\" }\n    },\n    required: [\"collectionId\", \"batchNumber\", \"quantity\"]\n  }\n};\n\nconst create_smart_note: FunctionDeclaration = {\n  name: \"create_smart_note\",\n  description: \"Create a structured SMART Notebook entry (Specific, Measurable, Achievable, Relevant, Time-Bound) for strategic planning, mindset breakthroughs, fears, 14-year milestone analysis, product vision, or launch readiness. Can automatically spawn studio directives.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      title: { type: Type.STRING, description: \"Descriptive title of the SMART note or breakthrough\" },\n      category: { \n        type: Type.STRING, \n        enum: ['Mindset & Fear', 'Product Strategy', 'Launch Readiness', 'Financial Breakthrough', 'Creative Vision', 'Operational Alignment', 'General'],\n        description: \"Strategic focus category\"\n      },\n      specific: { type: Type.STRING, description: \"Specific: The precise thought, blocker, fear, recurring pattern, or concept being articulated\" },\n      measurable: { type: Type.STRING, description: \"Measurable: The tangible metric, concrete verification test, or quantifiable standard of success\" },\n      achievable: { type: Type.STRING, description: \"Achievable: The realistic action path, specialist delegations, or method to dismantle the blocker\" },\n      relevant: { type: Type.STRING, description: \"Relevant: Why this is vital to the artisan's 14-year journey, legacy, brand prestige, and enterprise growth\" },\n      timeBound: { type: Type.STRING, description: \"Time-Bound: Target milestone or completion date in 2026 (e.g., 'Q3 2026', 'September 2026')\" },\n      insights: { type: Type.STRING, description: \"Deep psychological or strategic coach reflection\" },\n      actionPlan: { \n        type: Type.ARRAY, \n        items: { type: Type.STRING },\n        description: \"List of concrete step-by-step action items\"\n      },\n      tags: {\n        type: Type.ARRAY,\n        items: { type: Type.STRING },\n        description: \"Categorical tags for filtering (e.g. ['Breakthrough', 'Launch', '14-Year-Milestone'])\"\n      },\n      createDirectives: {\n        type: Type.BOOLEAN,\n        description: \"If true, automatically converts the action steps into pending studio tasks/directives assigned to relevant specialists\"\n      }\n    },\n    required: [\"title\", \"category\", \"specific\", \"measurable\", \"achievable\", \"relevant\", \"timeBound\"]\n  }\n};\n\nconst update_smart_note: FunctionDeclaration = {\n  name: \"update_smart_note\",\n  description: \"Update an existing SMART Note in the notebook (e.g. update status, refine action plan, add insights, or adjust 2026 timeline).\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      id: { type: Type.STRING, description: \"The ID or title of the note to update\" },\n      title: { type: Type.STRING, description: \"Updated title\" },\n      status: { \n        type: Type.STRING, \n        enum: ['draft', 'in-review', 'actionable', 'converted-to-directives', 'archived'],\n        description: \"Lifecycle status\"\n      },\n      category: { type: Type.STRING, description: \"Updated category\" },\n      specific: { type: Type.STRING, description: \"Updated Specific description\" },\n      measurable: { type: Type.STRING, description: \"Updated Measurable description\" },\n      achievable: { type: Type.STRING, description: \"Updated Achievable description\" },\n      relevant: { type: Type.STRING, description: \"Updated Relevant description\" },\n      timeBound: { type: Type.STRING, description: \"Updated Time-Bound target in 2026\" },\n      insights: { type: Type.STRING, description: \"Additional strategic coach reflections\" },\n      actionPlan: { \n        type: Type.ARRAY, \n        items: { type: Type.STRING },\n        description: \"Updated action items\" \n      },\n      tags: { \n        type: Type.ARRAY, \n        items: { type: Type.STRING },\n        description: \"Updated tags\" \n      }\n    },\n    required: [\"id\"]\n  }\n};\n\nconst delete_smart_note: FunctionDeclaration = {\n  name: \"delete_smart_note\",\n  description: \"Permanently delete a note from the SMART Notebook.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      id: { type: Type.STRING, description: \"The ID of the SMART note to remove\" }\n    },\n    required: [\"id\"]\n  }\n};\n\nconst convert_note_to_directives: FunctionDeclaration = {\n  name: \"convert_note_to_directives\",\n  description: \"Transform the action items of a SMART Note into official studio directives assigned to specialist agents.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      noteId: { type: Type.STRING, description: \"The ID of the SMART note\" },\n      assignedRole: { \n        type: Type.STRING, \n        enum: ['StudioLead', 'Formulator', 'Business', 'Marketing', 'NicheExpert', 'WealthAdvisor', 'Mentor'],\n        description: \"Default specialist to assign the generated directives to\"\n      }\n    },\n    required: [\"noteId\"]\n  }\n};\n\nconst create_formulation: FunctionDeclaration = {\n  name: \"create_formulation\",\n  description: \"Create a precision product formulation with specific ingredients and measurements. Use this for actual production recipes.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      name: { type: Type.STRING, description: \"Name of the formulation\" },\n      ingredients: { \n        type: Type.ARRAY, \n        items: {\n          type: Type.OBJECT,\n          properties: {\n            name: { type: Type.STRING, description: \"Ingredient name (must ideally match an inventory item)\" },\n            amount: { type: Type.NUMBER, description: \"Measurement amount\" },\n            unit: { type: Type.STRING, description: \"Measurement unit (e.g., g, ml, drops)\" }\n          },\n          required: [\"name\", \"amount\", \"unit\"]\n        }\n      },\n      instructions: { type: Type.STRING, description: \"Step-by-step crafting instructions\" },\n      curingTimeDays: { type: Type.NUMBER, description: \"Required curing or infusion time in days\" },\n      batchSize: { type: Type.NUMBER, description: \"Total expected yield quantity\" },\n      batchUnit: { type: Type.STRING, description: \"Yield unit (e.g., bars, bottles, g)\" }\n    },\n    required: [\"name\", \"ingredients\", \"instructions\", \"curingTimeDays\", \"batchSize\", \"batchUnit\"]\n  }\n};\n\nconst migrate_recipe_asset: FunctionDeclaration = {\n  name: \"migrate_recipe_asset\",\n  description: \"Move a misfiled recipe from 'Creative Notes' (assets) to 'Precision Formulas' (formulations).\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      assetId: { type: Type.STRING, description: \"The ID of the asset to migrate\" },\n      ingredients: { \n        type: Type.ARRAY, \n        items: {\n          type: Type.OBJECT,\n          properties: {\n            name: { type: Type.STRING, description: \"Ingredient name\" },\n            amount: { type: Type.NUMBER, description: \"Amount\" },\n            unit: { type: Type.STRING, description: \"Unit\" }\n          },\n          required: [\"name\", \"amount\", \"unit\"]\n        }\n      }\n    },\n    required: [\"assetId\", \"ingredients\"]\n  }\n};\n\nconst calculate_saponification: FunctionDeclaration = {\n  name: \"calculate_saponification\",\n  description: \"Calculate precise saponification values, NaOH/KOH lye requirement, water discount, and fatty acid profile (Hardness, Cleansing, Conditioning, Bubbly, Creamy, INS score) for any custom oil blend.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      soapName: { type: Type.STRING, description: \"Name of the soap recipe\" },\n      oils: {\n        type: Type.ARRAY,\n        items: {\n          type: Type.OBJECT,\n          properties: {\n            name: { type: Type.STRING, description: \"Oil/Fat name (e.g., Olive Oil, Coconut Oil 76 deg, Shea Butter, Castor Oil)\" },\n            grams: { type: Type.NUMBER, description: \"Weight in grams\" }\n          },\n          required: [\"name\", \"grams\"]\n        },\n        description: \"List of oils and their weights in grams\"\n      },\n      superfatPercent: { type: Type.NUMBER, description: \"Superfat/lye discount percentage (typically 5 to 8)\" },\n      waterLyeRatio: { type: Type.NUMBER, description: \"Water to lye ratio (e.g. 2.0 or 2.5)\" },\n      lyeType: { type: Type.STRING, enum: ['NaOH', 'KOH', 'Dual_90_10'], description: \"Lye type (NaOH for solid bars, KOH for liquid soap)\" }\n    },\n    required: [\"soapName\", \"oils\", \"superfatPercent\", \"waterLyeRatio\", \"lyeType\"]\n  }\n};\n\nconst audit_formulation_safety: FunctionDeclaration = {\n  name: \"audit_formulation_safety\",\n  description: \"Audit formulation for IFRA dermal compliance limits, antioxidant protection against rancidity (e.g., Tocopherol/ROCO2), pH range, and microbial preservation.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      productName: { type: Type.STRING, description: \"Name of the product formulation\" },\n      productType: { \n        type: Type.STRING, \n        enum: ['leave_on_serum', 'leave_on_butter', 'rinse_off_soap', 'emulsified_lotion', 'bath_soak'], \n        description: \"Category of cosmetic product\" \n      },\n      preservativeSystem: { type: Type.STRING, description: \"Preservative or self-preserving anhydrous matrix\" },\n      fragrancePercent: { type: Type.NUMBER, description: \"Total essential oil or fragrance concentration percentage\" },\n      shelfLifeEstimateMonths: { type: Type.NUMBER, description: \"Estimated shelf stability in months\" }\n    },\n    required: [\"productName\", \"productType\", \"preservativeSystem\", \"fragrancePercent\", \"shelfLifeEstimateMonths\"]\n  }\n};\n\nconst scale_formulation: FunctionDeclaration = {\n  name: \"scale_formulation\",\n  description: \"Scale a formulation's batch size proportionally while preserving precise ingredient percentages, lye ratios, and phase distributions.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      formulationName: { type: Type.STRING, description: \"Name or ID of the formulation to scale\" },\n      currentBatchSize: { type: Type.NUMBER, description: \"Current batch size\" },\n      targetBatchSize: { type: Type.NUMBER, description: \"Target batch size\" },\n      unit: { type: Type.STRING, description: \"Unit of measurement (e.g., g, kg, bars, bottles)\" }\n    },\n    required: [\"formulationName\", \"currentBatchSize\", \"targetBatchSize\", \"unit\"]\n  }\n};\n\nconst delete_record: FunctionDeclaration = {\n  name: \"delete_record\",\n  description: \"Permanently remove a record from the hub (task, prospect, campaign, formulation, asset, inventory, order, collection, etc.). Use with extreme caution.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      recordType: { \n        type: Type.STRING, \n        enum: [\"task\", \"prospect\", \"campaign\", \"formulation\", \"asset\", \"inventory\", \"order\", \"collection\"], \n        description: \"The type of record to delete\" \n      },\n      id: { type: Type.STRING, description: \"The ID of the record to remove\" }\n    },\n    required: [\"recordType\", \"id\"]\n  }\n};\n\nconst create_corporate_account: FunctionDeclaration = {\n  name: \"create_corporate_account\",\n  description: \"Register a new B2B commercial account (Luxury Builder, Condo Developer, Rental Developer, Realtor, or Brokerage) in the Builders & Realtors CRM.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      companyName: { type: Type.STRING, description: \"Company or brokerage name\" },\n      contactPerson: { type: Type.STRING, description: \"Primary decision-maker name\" },\n      email: { type: Type.STRING, description: \"Business email address\" },\n      phone: { type: Type.STRING, description: \"Business phone number (optional)\" },\n      accountType: {\n        type: Type.STRING,\n        enum: [\"Luxury Builder\", \"Condo Developer\", \"Rental Developer\", \"Realtor\", \"Architecture / Design\", \"Corporate Gifting\", \"Luxury Hospitality\", \"Boutique Retail\"],\n        description: \"Target B2B vertical\"\n      },\n      nicheFocus: { type: Type.STRING, description: \"Project niche or gifting scope (optional)\" },\n      annualBudgetPotential: { type: Type.NUMBER, description: \"Estimated annual B2B contract value in CAD/USD (optional)\" },\n      notes: { type: Type.STRING, description: \"Account notes or handover timeline (optional)\" }\n    },\n    required: [\"companyName\", \"contactPerson\", \"email\", \"accountType\"]\n  }\n};\n\nconst create_development_portal: FunctionDeclaration = {\n  name: \"create_development_portal\",\n  description: \"Create a public QR development handover portal and A3 binder specification for a condo development, rental tower, or custom home builder project.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      developmentName: { type: Type.STRING, description: \"Name of the residential building or estate project\" },\n      developerName: { type: Type.STRING, description: \"Name of the builder or developer company\" },\n      addressOrLocation: { type: Type.STRING, description: \"City, neighborhood, or street address\" },\n      unitCount: { type: Type.NUMBER, description: \"Total units/lots in the project (optional)\" },\n      boxEdition: {\n        type: Type.STRING,\n        enum: [\"Uniform Development QR\", \"Custom Single-Buyer\", \"Builder Wholesale Run\"],\n        description: \"Kit packaging and binder format\"\n      },\n      audienceMode: {\n        type: Type.STRING,\n        enum: [\"homeowner\", \"renter\"],\n        description: \"Use 'homeowner' for condo buyers/estates or 'renter' for luxury rental tower tenants\"\n      },\n      scentProfile: { type: Type.STRING, description: \"Botanical scent profile paired with the project (optional)\" },\n      published: { type: Type.BOOLEAN, description: \"Whether to publish immediately for QR scans (optional)\" }\n    },\n    required: [\"developmentName\", \"developerName\", \"addressOrLocation\"]\n  }\n};\n\nconst generate_french_compliance_pack: FunctionDeclaration = {\n  name: \"generate_french_compliance_pack\",\n  description: \"Generate a complete Quebec Loi 96 / OQLF & Health Canada bilingual label pack, French care card, and B2B French commercial quote clause, and save it in Documents Hub.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      productType: {\n        type: Type.STRING,\n        enum: [\"soap\", \"candle\", \"serum\", \"box\"],\n        description: \"Product category for statutory bilingual warnings\"\n      },\n      productNameFr: { type: Type.STRING, description: \"French product title\" },\n      productNameEn: { type: Type.STRING, description: \"English product title\" },\n      netWeight: { type: Type.STRING, description: \"Metric net weight/volume (e.g., '120 g', '220 g / 7.7 oz')\" },\n      scentNotesFr: { type: Type.STRING, description: \"French botanical scent notes\" },\n      scentNotesEn: { type: Type.STRING, description: \"English botanical scent notes\" },\n      inciList: { type: Type.STRING, description: \"Descending INCI ingredient declaration\" },\n      companyAndAddress: { type: Type.STRING, description: \"Canadian manufacturer/dealer name and Montreal/Quebec address\" }\n    },\n    required: [\"productType\", \"productNameFr\", \"productNameEn\", \"netWeight\", \"scentNotesFr\", \"scentNotesEn\", \"inciList\", \"companyAndAddress\"]\n  }\n};\n\nconst evaluate_order_quote_cogs: FunctionDeclaration = {\n  name: \"evaluate_order_quote_cogs\",\n  description: \"Run an internal COGS, finished stock vs production gap, 50% B2B deposit & cash-flow coverage check, material shortfall audit, and curing lead-time feasibility check on an incoming order/quote or custom line items.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      incomingOrderId: { type: Type.STRING, description: \"ID or referenceCode of an existing incoming order/quote (optional)\" },\n      sku: { type: Type.STRING, description: \"SKU to evaluate if evaluating ad-hoc (optional)\" },\n      quantity: { type: Type.NUMBER, description: \"Quantity of kits/units (optional)\" },\n      province: { type: Type.STRING, description: \"Canadian province code (e.g., QC, ON) for tax & Loi 96 check\" },\n      requestedDeliveryDate: { type: Type.STRING, description: \"Target YYYY-MM-DD delivery date (optional)\" },\n      coBrandingOptions: {\n        type: Type.ARRAY,\n        items: { type: Type.STRING },\n        description: \"Optional add-on slugs (e.g., monogram-linen-band, embossed-arch-card, jesmonite-color-match)\"\n      }\n    }\n  }\n};\n\nconst check_sku_bom_and_stock: FunctionDeclaration = {\n  name: \"check_sku_bom_and_stock\",\n  description: \"Explode a Catalog SKU + quantity into exact raw ingredients and packaging BOM components and check current normalized inventory for shortfalls.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      sku: { type: Type.STRING, description: \"Canonical SKU or product name (e.g. LJW-B2B-ARC-02, LJW-ECZ-BALM-100)\" },\n      quantity: { type: Type.NUMBER, description: \"Number of units/boxes to check\" }\n    },\n    required: [\"sku\", \"quantity\"]\n  }\n};\n\nconst stage_outbound_deliverable: FunctionDeclaration = {\n  name: \"stage_outbound_deliverable\",\n  description: \"Stage an INTERNAL-ONLY deliverable (quote dossier, procurement restock alert, or portal/Loi 96 fulfillment pack) in the studio's Outbound Review Queue for Myrna's 1-click inspection. NEVER sends emails or messages externally.\",\n  parameters: {\n    type: Type.OBJECT,\n    properties: {\n      kind: {\n        type: Type.STRING,\n        enum: [\"quote_proposal_ready\", \"procurement_shortfall\", \"portal_and_compliance_ready\"],\n        description: \"Type of internal staging item\"\n      },\n      referenceCode: { type: Type.STRING, description: \"Reference code (e.g., LJW-B2B-9F2A1C)\" },\n      title: { type: Type.STRING, description: \"Short internal title\" },\n      summary: { type: Type.STRING, description: \"Concise internal summary\" },\n      markdownContent: { type: Type.STRING, description: \"Full internal Markdown dossier or procurement shopping list\" }\n    },\n    required: [\"kind\", \"referenceCode\", \"title\", \"summary\"]\n  }\n};\n\nconst ARTY_INTERNAL_OFFICE_GUARDRAILS = `\nHARD OFFICE & PRODUCTION GUARDRAILS (NON-NEGOTIABLE):\n1. STRICTLY INTERNAL ONLY \u2014 ZERO EXTERNAL CONTACT: You MUST NEVER send emails, SMS, webhooks, Stripe invoices, or external client replies. All quotes, dossiers, compliance packs, and procurement alerts are internal working artifacts staged exclusively for Myrna's review.\n2. STAGING QUARANTINE: Any event or query tagged 'environment: staging' runs strictly in simulation/sandbox mode and MUST NEVER deduct real inventory, finished stock, or live accounting ledgers.\n3. SPLIT QUOTE vs. PAID ORDER & HITL DISCIPLINE:\n   - On quote_request / b2b_inquiry / b2b_sample_request / retail_preorder: Review stock & BOM, compute landed COGS & gross margin (70%+ floor), verify 50% B2B deposit & cash-flow coverage against direct materials+packaging COGS, verify cure lead-time, draft internal dossier & tentative dates \u2014 NEVER deduct inventory and NEVER record revenue.\n   - On paid_order / retail_paid_order (verified only): Stage internal dossier, procurement shortfalls, and batch/deduction proposals for Myrna's HITL approval before committing physical stock deductions or production pours.\n4. FULL COGS & ALL-COLLECTION FLUENCY: Always inspect the live Workshop Reference Tables (Catalog SKU -> Formulation & Packaging BOM Map, Standardized Inventory with unit costs & reorder floors, Pricing/Deposit/Margin/Cure Rules, and all collections: B2B, Eczema, Menopause/Say It Plain, Celestial). Never guess numbers when exact table figures are in context.`;\n\nconst AGENT_PROMPTS: Record<AgentRole, string> = {\n  StudioLead: `You are the Lead Studio Director & Autonomous Office/Production Orchestrator for LJWellness, a B2B luxury botanical & architectural closing-gift atelier (serving builders, condo developers, realtors) plus specialized Eczema and Menopause (Say It Plain) botanical skincare lines.\n\n  TEMPORAL CONTEXT: Current year is 2026.\n\n  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}\n\n  THE 12 LJWELLNESS STUDIO ROOMS & HUBS:\n  1. Master Orchestration Room ('workshop')\n  2. Task Room / Deliverables Board ('tasks')\n  3. Studio Planner & Calendar ('planner')\n  4. Formulation Lab & Recipe Library ('recipes')\n  5. COGS & Financial Hub ('cogs' / 'ledger')\n  6. Wholesale & Builders CRM ('wholesale' / 'corporate-accounts')\n  7. Documents Hub ('documents-hub')\n  8. Inventory & Materials Hub ('supplies' / 'inventory')\n  9. Production Hub ('production')\n  10. Collections Hub ('collections')\n  11. Compliance Hub ('compliance' \u2014 Quebec Loi 96 / OQLF + Health Canada CNF)\n  12. Storefront & Outbound Staging Queue ('storefront' \u2014 incoming orders/quotes & internal outbound review queue)\n\n  OFFICE & PRODUCTION INTAKE WORKFLOW:\n  Whenever reviewing an incoming order, quote request, or production request:\n  1. Call 'evaluate_order_quote_cogs' or 'check_sku_bom_and_stock' to verify finished stock vs. production gap, raw+packaging BOM shortfalls, exact COGS, 50% B2B deposit & cash-flow coverage, and backward cure dates.\n  2. Call 'create_asset' & 'stage_outbound_deliverable' (kind: 'quote_proposal_ready') with the complete internal Production & Costing Dossier Markdown for Myrna's #admin review.\n  3. If raw botanicals, vessels, or packaging are short, create a procurement task ('create_task' assigned to Business/Formulator) and call 'stage_outbound_deliverable' (kind: 'procurement_shortfall').\n  4. If province is QC or locale is fr/bilingual, ensure Quebec Loi 96 bilingual pack is staged via 'generate_french_compliance_pack'; if B2B development run (10+ units or condo/rental/builder), stage portal planning via 'create_development_portal'.\n  5. Call 'add_event' to pencil cure milestones & earliest feasible ship dates onto Studio Planner.\n  6. Call 'complete_task' when resolving pending tasks.\n  CRITICAL: If the user is simply greeting you, greet them warmly without calling tools.`,\n\n  Formulator: `You are the Master Artisan Formulator & Cosmetic Chemist (Calyx) for LJWellness.\n  TEMPORAL CONTEXT: Current year is 2026.\n  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}\n\n  AUTONOMOUS PRODUCTION & LAB DIRECTIVES:\n  - Inspect exact ingredient weights (g/ml), cure windows (35-56d cold-process/stone-cast, 14d wax melts, 5-14d serums/balms), and standardized inventory stock/reorder floors in Workshop State.\n  - When reviewing an order or scaling a batch: use 'check_sku_bom_and_stock', 'scale_formulation', 'calculate_saponification', or 'audit_formulation_safety'.\n  - If raw botanicals or vessels/packaging are short, log a 'create_task' (tagged [PROCUREMENT]) and 'stage_outbound_deliverable' (kind: 'procurement_shortfall') rather than deducting unapproved stock.\n  - When locale is fr/bilingual or province is QC, invoke 'generate_french_compliance_pack' (Quebec Loi 96 / OQLF + Health Canada INCI).\n  - Always schedule cure completion dates with 'add_event' and record formulation sheets with 'create_asset'.`,\n\n  Business: `You are the Commercial Director & B2B Procurement Lead for LJWellness.\n  TEMPORAL CONTEXT: Current year is 2026.\n  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}\n\n  AUTONOMOUS COMMERCIAL & PROCUREMENT DIRECTIVES:\n  - Oversee B2B Builder/Developer/Realtor accounts, quote feasibility, volume tier rules (1\u20139, 10\u201324, 25\u201349, 50+), 50% B2B upfront deposit + $95 custom Jesmonite setup fee, and packaging/raw material restock vendor lead times.\n  - For quote requests: log/review account ('create_corporate_account'), stage internal quote dossier ('create_asset' + 'stage_outbound_deliverable'), schedule tentative handover deadlines ('add_event'), and generate procurement restock shopping lists if any packaging or botanical SKU is short. NEVER email clients directly.`,\n\n  Marketing: `You are the B2B Luxury Brand Storyteller & Bilingual Positioning Strategist for LJWellness.\n  TEMPORAL CONTEXT: Current year is 2026.\n  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}\n  - Craft architectural homeowner handover storytelling, QR development welcome copy, A3 binder briefs, and collection positioning across B2B, Eczema, and Menopause (Say It Plain) lines \u2014 saved internally via 'create_asset', 'create_campaign', or 'create_development_portal'. Never transmit externally.`,\n\n  NicheExpert: `You are the Luxury Real Estate Gifting, Architectural Sensory & B2B Curation Specialist for LJWellness.\n  TEMPORAL CONTEXT: Current year is 2026.\n  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}\n  - Design box editions (Uniform Development QR, Custom Single-Buyer, Builder Wholesale Run), Jesmonite vessel & scent pairings, and homeowner vs renter audience positioning with accurate BOM & COGS awareness via 'create_asset' and 'create_development_portal'.`,\n\n  WealthAdvisor: `You are the Studio Profitability & COGS Finance Analyst (Vesper) for LJWellness.\n  TEMPORAL CONTEXT: Current year is 2026.\n  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}\n\n  COSTING, MARGIN & 50% DEPOSIT MANDATES:\n  - Calculate exact landed Unit COGS (raw materials + vessels/packaging + co-branding add-ons + $35/hr direct labor + studio overhead + payment processing awareness), Total COGS, Net Revenue, Gross Profit ($), and Gross Margin (%) across ALL tracks (B2B, Eczema, Menopause, Celestial).\n  - Enforce the **70%+ gross margin floor** (75% target on custom B2B) and alert immediately if a coupon or tier discount compresses margin below 70%.\n  - On B2B quotes/orders: compute exact **50% B2B deposit** (including $95 custom Jesmonite setup fee when applicable + Canadian provincial tax preview: QC 5% TPS + 9.975% TVQ, ON 13% HST, etc.) AND explicitly verify whether the 50% deposit covers 100% of direct raw materials & packaging COGS.\n  - NEVER record revenue ('update_finance') on quote requests or staging simulations! Always save internal financial dossiers using 'create_asset' / 'evaluate_order_quote_cogs'.`,\n\n  Mentor: `You are the B2B Brand Advisor & Craft Mentor for LJWellness.\n  TEMPORAL CONTEXT: Current year is 2026.\n  ${ARTY_INTERNAL_OFFICE_GUARDRAILS}\n  - Protect margin discipline, sustainable curing lead-times, and burnout-free batch pacing across all 12 rooms. Capture strategic frameworks in 'create_smart_note' and 'create_asset'.`,\n\n  System: `You are the LJWellness Studio Intelligence System Layer enforcing strict internal-only operation, staging sandbox isolation, idempotency, and HITL stock/accounting guardrails.`\n};\n\nexport function buildWorkshopStateSummary(\n  state: any,\n  agreedCatalog?: StorefrontAgreementCatalog,\n): string {\n  if (!state) return '';\n  const catalog = agreedCatalog || buildDefaultAgreementCatalog();\n  const tasksList = Array.isArray(state.tasks) ? state.tasks : [];\n  const pendingTasks = tasksList.filter((t: any) => t.status !== 'completed');\n  const smartNotesList = Array.isArray(state.smartNotes) ? state.smartNotes : [];\n  const eventsList = Array.isArray(state.planner?.events) ? state.planner.events : [];\n  const corporateAccountsList = Array.isArray(state.corporateAccounts) ? state.corporateAccounts : [];\n  const portalsList = Array.isArray(state.developmentPortals) ? state.developmentPortals : [];\n  const incomingOrdersList = Array.isArray(state.incomingOrders) ? state.incomingOrders : [];\n  const outboundQueueList = Array.isArray(state.outboundQueue) ? state.outboundQueue : [];\n\n  const stdInventory = auditStudioInventory(Array.isArray(state.inventory) ? state.inventory : []);\n  const skuBoms = buildSkuBomCatalog(catalog, Array.isArray(state.formulations) ? state.formulations : []);\n  const cogsSummary = evaluateCollectionAndFormulationCogs(state, catalog);\n\n  return `\nCurrent Workshop State (Live Year: 2026 | INTERNAL STUDIO OFFICE ONLY):\n- Artisan: ${state.profile?.artisan?.name || 'Master Formulator'} (${state.profile?.artisan?.experience || '14 Years'})\n- Studio: ${state.profile?.name || 'LJWellness'} (${state.profile?.niche || 'B2B Luxury Botanical & Skincare Atelier'})\n- Finances: Balance $${state.finances?.balance || 0} | Revenue $${state.finances?.revenue || 0} | Expenses $${state.finances?.expenses || 0} | Target Margin: ${state.profile?.targetMargin || 75}%\n\nLOOKUP TABLE 1 \u2014 STANDARDIZED INVENTORY WITH UNIT COSTS & REORDER FLOORS (${stdInventory.length} items):\n${stdInventory.map((i) => `  * [${i.category}] ${i.item}: ${i.normalizedStock} ${i.normalizedUnit} (orig: ${i.originalStock} ${i.originalUnit}) | Cost: $${i.costPerNormalizedUnit}/${i.normalizedUnit} ($${i.costPerOriginalUnit}/${i.originalUnit}) | Reorder Floor: ${i.reorderThreshold} ${i.normalizedUnit}${i.lowStock ? ' [LOW STOCK]' : ''}`).join('\\n') || '  (Inventory empty)'}\n\nLOOKUP TABLE 2 \u2014 FORMULATIONS WITH EXACT WEIGHTS, CURE WINDOWS & UNIT RAW COSTS (${cogsSummary.formulations.length} formulas):\n${(state.formulations || []).map((f: any) => {\n  const cogsRow = cogsSummary.formulations.find((r) => r.id === f.id || r.name === f.name);\n  const ingText = (f.ingredients || []).map((ing: any) => `${ing.name} (${ing.amount}${ing.unit})`).join(', ');\n  return `  * [ID: ${f.id}] ${f.name} | Cure: ${f.curingTimeDays}d | Yield: ${f.batchSize}${f.batchUnit} | Est. Unit Raw Cost: $${cogsRow?.estimatedUnitRawCostCad ?? 0} CAD | Ingredients: ${ingText}`;\n}).join('\\n') || '  (No formulations stored)'}\n\nLOOKUP TABLE 3 \u2014 CATALOG SKU -> FORMULATION, PACKAGING BOM, COGS & 50% B2B DEPOSIT MATRIX (${skuBoms.length} SKUs):\n${skuBoms.slice(0, 26).map((b) => {\n  const cogs = cogsSummary.skus.find((s) => s.sku === b.sku);\n  const pkgTxt = b.packagingBom.map((pk) => `${pk.quantityPerUnit}x ${pk.itemName}`).join(' + ');\n  const rawTxt = b.rawBom.map((r) => `${r.amountPerUnit}${r.unit} ${r.itemName}`).join(', ');\n  return `  * ${b.sku} [${b.track.toUpperCase()}] ${b.productName} (${b.finishedUnitWeight}) | Cure: ${b.cureTimeDays}d | Price: $${cogs?.priceCad ?? b.defaultUnitPriceCad} (70% Floor Price: $${cogs?.recommendedPrice70PctCad ?? 0}) | Unit COGS: $${cogs?.unitTotalCogsCad ?? 0} (Raw $${cogs?.unitRawCostCad ?? 0} + Pkg $${cogs?.unitPackagingCostCad ?? 0} + Labor/OH $${cogs?.unitLaborOverheadCad ?? 0}) | Margin: ${cogs?.grossMarginPct ?? 0}% | 50% Deposit: $${cogs?.b2b50PctDepositPerUnitCad ?? 0}/unit | Pkg BOM: [${pkgTxt}] | Raw BOM: [${rawTxt}]`;\n}).join('\\n')}\n\nSTUDIO PRICING, DEPOSIT & LEAD-TIME RULES:\n- Currency: CAD | B2B Upfront Deposit: ${STUDIO_PRICING_RULES.b2bDepositPct}% (must verify if deposit covers 100% of direct raw+pkg COGS; +$95 setup fee for jesmonite-color-match)\n- Gross Margin Floor: ${STUDIO_PRICING_RULES.grossMarginFloorPct}% (Custom Target: ${STUDIO_PRICING_RULES.customTargetMarginPct}%) | Direct Labor: $${STUDIO_PRICING_RULES.hourlyLaborRateCad}/hr (${STUDIO_PRICING_RULES.defaultMinutesPerUnit} min/unit) + $${STUDIO_PRICING_RULES.allocatedOverheadPerUnitCad}/unit studio overhead\n- Volume Tiers: ${STUDIO_PRICING_RULES.volumeTiers.map((t) => `${t.label}: ${t.discountPctOffBase}% off, target ${t.targetMarginPct}% margin (${t.boxEdition})`).join(' | ')}\n- Cure Windows: Cold-Process ${STUDIO_PRICING_RULES.cureWindowsDays.coldProcessSoap}d | Stone-Cast ${STUDIO_PRICING_RULES.cureWindowsDays.stoneCastSoap}d | Soy Melts ${STUDIO_PRICING_RULES.cureWindowsDays.botanicalWaxMelts}d | Serums/Balms ${STUDIO_PRICING_RULES.cureWindowsDays.serumsAndBalms}d | Fulfillment Pack Buffer +${STUDIO_PRICING_RULES.packagingAndFulfillmentBufferDays}d\n\nACTIVE COLLECTIONS & COGS SNAPSHOT:\n${(state.collections || []).map((c: any) => `  * ${c.name} (${c.stage}) \u2014 ${(c.products || []).map((p: any) => `${p.name}: $${p.price} (Stock: ${p.stock})`).join(', ')}`).join('\\n') || '  (N/A)'}\n\nLIVE INCOMING ORDERS & QUOTES QUEUE (${incomingOrdersList.length} records):\n${incomingOrdersList.slice(0, 15).map((o: IncomingOrderQuote) => `  * [${o.environment.toUpperCase()} | ${o.requestType} | ${o.status}] ${o.referenceCode} \u2014 ${o.client.companyName} (${o.province || 'CA'}, ${o.locale}) | Subtotal: $${o.evaluation?.netRevenueCad ?? o.payment?.subtotal ?? 0} | COGS: $${o.evaluation?.totalCogsCad ?? 0} (${o.evaluation?.grossMarginPct ?? 0}% margin) | 50% Deposit: $${o.evaluation?.b2bDepositRequiredCad ?? 0} (Covers Direct COGS: ${o.evaluation?.b2bDepositCoversDirectCogs ? 'YES' : 'NO'}) | Shortfalls: ${o.evaluation?.shortfalls?.length ?? 0} | Earliest Ship: ${o.evaluation?.earliestPossibleDeliveryDate || 'TBD'}`).join('\\n') || '  (No incoming storefront orders/quotes yet)'}\n\nINTERNAL OUTBOUND REVIEW QUEUE \u2014 ZERO EXTERNAL SEND (${outboundQueueList.length} items):\n${outboundQueueList.slice(0, 10).map((q: any) => `  * [${q.kind} | ${q.status}] ${q.referenceCode}: ${q.title}`).join('\\n') || '  (Queue empty)'}\n\n- Tasks & Directives (${pendingTasks.length} Pending, ${tasksList.length} Total):\n${tasksList.slice(0, 20).map((t: any) => `  * [ID: ${t.id}] ${t.title} (Assigned: ${t.assignedTo}, Priority: ${t.priority}, Status: ${t.status}) - ${t.description}`).join('\\n') || '  (None)'}\n- Studio Planner Schedule (${eventsList.length} Scheduled Events):\n${eventsList.slice(0, 12).map((e: any) => `  * [${e.date}] ${e.title} (${e.type || 'production'})`).join('\\n') || '  (None)'}\n- SMART Notebook (${smartNotesList.length}): ${smartNotesList.map((n: any) => `${n.title} (${n.status})`).join(', ') || 'None'}\n- B2B CRM Accounts (${corporateAccountsList.length}): ${corporateAccountsList.map((a: any) => `${a.companyName} (${a.accountType}, ${a.status})`).join(', ') || 'None'}\n- QR Portals (${portalsList.length}): ${portalsList.map((p: any) => `${p.developmentName} (/portal/${p.slug})`).join(', ') || 'None'}\n- Production Batches: ${state.productionBatches?.filter((b: any) => b.status !== 'finished').map((b: any) => `${b.batchName} (${b.status}, Yield: ${b.expectedYield})`).join(', ') || 'None'}\n`;\n}\n\nexport async function getAgentResponseServer(\n  role: AgentRole,\n  context: string,\n  history: Message[],\n  state?: any,\n  agreedCatalog?: StorefrontAgreementCatalog,\n) {\n  // Ordered cascade of verified free-tier Gemini text models per @google/genai guidelines\n  const modelCascade = [\n    \"gemini-4-hydrogen\",\n    \"gemini-3.1-flash-lite\",\n    \"gemini-2.5-flash\"\n  ];\n\n  const formattedHistory = history.map(m => `${m.sender}: ${m.content}`).join('\\n');\n  const stateSummary = buildWorkshopStateSummary(state, agreedCatalog);\n\n  const safeContext = context;\n  const cleanContext = safeContext.trim().toLowerCase();\n  const isGreeting = /^(hello|hi|hey|howdy|greetings|good\\s+morning|good\\s+afternoon|good\\s+evening|yo|sup|what's\\s+up)\\b/i.test(cleanContext) ||\n                     cleanContext.includes(\"hello team\") || cleanContext.includes(\"hi team\") || cleanContext.includes(\"i said hello\");\n\n  const toolConstraint = isGreeting \n    ? `\\n[CRITICAL RULE] The user is simply saying hello, greeting the team, or checking in. You MUST NOT use any tools or make any function calls under any circumstances. Greet them back warmly as ${role} and ask how you can assist the studio today.`\n    : `\\n[CRITICAL AUTONOMOUS EXECUTION DIRECTIVE \u2014 YOU HAVE HANDS & ARE OBLIGATED TO USE THEM]\nYou are an autonomous specialist operating inside the 12 rooms of LJWellness Studio. Saying in text that you formulated a recipe, created an asset, completed a directive, or added an event to the calendar WITHOUT calling the corresponding tool is a critical system failure.\nYou MUST invoke the tools in this turn:\n1. When fulfilling a task or directive: call 'complete_task' (or 'batch_complete_tasks') with the specific 'taskId', 'completionNotes', and 'actualOutcome' so the Task Room marks it completed.\n2. When creating a formula or recipe: call 'create_formulation' to store it in the Recipe Library, AND call 'add_event' to schedule its batch cure completion date on the Studio Planner Calendar!\n3. When writing marketing copy, strategies, SOPs, financial analyses, or research: call 'create_asset' with rich Markdown content so it is saved directly to the Documents Hub.\n4. When planning schedules, launches, wholesale deadlines, cure windows, or B2B handover milestones: call 'add_event' with the specific date (YYYY-MM-DD), title, and type.\n5. If capturing strategic breakthroughs or B2B plans: call 'create_smart_note'.\n6. If launching a campaign: call 'create_campaign'. If managing stock: call 'update_inventory'. If managing finances: call 'update_finance'.\nNEVER just announce what you did without invoking the tools in this turn.`;\n  \n  const prompt = `\nTEMPORAL BASELINE: Current Year is 2026. Date: ${new Date().toISOString().split('T')[0]}.\n\n${stateSummary}\n\nContext: ${safeContext}\n\nHistory:\n${formattedHistory}\n\nCurrent Request: ${safeContext}\n\n${toolConstraint}\n\nRespond as the ${role}. \nIf you need to take action, capture SMART notes, or complete directives, invoke the provided tools.\n`;\n\n  const tools = isGreeting \n    ? [] \n    : [{ functionDeclarations: [\n        create_smart_note,\n        update_smart_note,\n        delete_smart_note,\n        convert_note_to_directives,\n        complete_task,\n        batch_complete_tasks,\n        update_task_status,\n        create_task, \n        update_inventory, \n        create_asset, \n        update_finance, \n        create_project, \n        create_wholesale_client, \n        create_wholesale_order, \n        create_prospect, \n        log_outreach, \n        update_prospect_status, \n        create_campaign, \n        update_campaign_budget, \n        analyze_market_trends, \n        optimize_formula, \n        create_batch,\n        create_formulation,\n        calculate_saponification,\n        audit_formulation_safety,\n        scale_formulation,\n        migrate_recipe_asset,\n        add_event,\n        delegate_to_agent,\n        delete_record,\n        create_corporate_account,\n        create_development_portal,\n        generate_french_compliance_pack,\n        evaluate_order_quote_cogs,\n        check_sku_bom_and_stock,\n        stage_outbound_deliverable\n      ] }];\n\n  for (let i = 0; i < modelCascade.length; i++) {\n    const currentModel = modelCascade[i];\n    // Attempt with retry on transient network 503\n    for (let attempt = 0; attempt < 2; attempt++) {\n      try {\n        const response = await ai.models.generateContent({\n          model: currentModel,\n          contents: prompt,\n          config: {\n            systemInstruction: AGENT_PROMPTS[role],\n            tools: tools\n          }\n        });\n        \n        let text = response.text || \"\";\n        const rawFunctionCalls = response.functionCalls || [];\n\n        if (!text && rawFunctionCalls.length > 0) {\n          text = `Executing: ${rawFunctionCalls.map((f: any) => f.name.replace(/_/g, ' ')).join(', ')}. Your workshop state has been updated.`;\n        } else if (!text) {\n          text = \"I'm processing your request.\";\n        }\n        \n        return { \n          text, \n          functionCalls: rawFunctionCalls.length > 0 ? rawFunctionCalls : undefined,\n          isFallback: false,\n          model: currentModel\n        };\n      } catch (error: any) {\n        const isTransient = error?.message?.includes('503') || error?.message?.includes('UNAVAILABLE') || error?.message?.includes('high demand');\n        if (attempt === 0 && isTransient) {\n          await new Promise(resolve => setTimeout(resolve, 350));\n          continue;\n        }\n        console.warn(`[Artisan Engine] Model ${currentModel} (attempt ${attempt + 1}) encountered an issue. Transitioning to next candidate...`);\n        break;\n      }\n    }\n  }\n\n  // Graceful conversational response if all cloud endpoints are momentarily saturated\n  const fallback = generateContextualArtisanFallback(role, safeContext, state);\n  return {\n    text: fallback.text,\n    functionCalls: fallback.functionCalls,\n    isFallback: true\n  };\n}\n\nfunction generateContextualArtisanFallback(role: AgentRole, context: string, state?: any): { text: string; functionCalls?: any[] } {\n  const query = context.toLowerCase();\n  const tasksList = state?.tasks && Array.isArray(state.tasks) ? state.tasks : [];\n  \n  // Check if this was a directive execution prompt\n  const taskMatch = context.match(/EXECUTE DIRECTIVE NOW:\\s*\"([^\"]+)\"/i) || context.match(/directive:\\s*\"([^\"]+)\"/i);\n  let matchedTask = taskMatch ? tasksList.find((t: any) => t.title.toLowerCase().includes(taskMatch[1].toLowerCase())) : null;\n  if (!matchedTask) {\n    matchedTask = tasksList.find((t: any) => t.assignedTo === role && t.status !== 'completed') || tasksList.find((t: any) => t.status !== 'completed');\n  }\n\n  const isExecutionRequest = /execute|directive|fulfill|task|formulate|calculate|scale|recipe/i.test(query);\n\n  if (role === 'Formulator' || /foundation|seasalt|brine|serum|butter|formula|recipe|ingredient|soap|saponif/i.test(query)) {\n    const text = `### \uD83E\uDDEA Master Formulation Specification: The Foundation Collection\n*Formulated by Master Cosmetic Chemist & Botanical Formulator*\n\n#### 1. Seasalt & Pacific Brine Cold Process Bar (1,000g Batch)\n- **Saponification Matrix (8% Superfat | 2.2:1 Water:Lye):**\n  - Organic Extra Virgin Olive Oil: 400g (40%)\n  - Raw Unrefined Coconut Oil: 250g (25%)\n  - Fair-Trade Shea Butter: 200g (20%)\n  - Cold-Pressed Castor Oil: 100g (10%)\n  - Golden Jojoba Oil: 50g (5%)\n- **Lye Solution:** 137g Pure Sodium Hydroxide (NaOH) dissolved in 300g Mineral Ocean Brine / Distilled Water.\n- **Trace Additives:** 150g Ultra-Fine Pacific Grey Sea Salt, 20g French Green Clay, 30g Essential Oil Chord (Atlantic Cedarwood, Sweet Marjoram, Wild Lavender).\n- **INS Hardness Rating:** 148 | **Conditioning:** 54 | **Cure Time:** 35 Days.\n\n#### 2. Restorative Botanical Lipid Body Serum (500ml Batch)\n- **Phase A (Active Botanical Lipid Base - 85%):**\n  - Plant-Derived Olive Squalane: 225ml (45%)\n  - Cold-Pressed Organic Rosehip Seed Oil (High Linoleic): 125ml (25%)\n  - Golden Jojoba Esters: 75ml (15%)\n- **Phase B (Active Botanical Phyto-Nutrients - 12%):**\n  - Sea Buckthorn Fruit CO2 Extract: 30ml (6%)\n  - Bakuchiol Phyto-Retinol Active: 15ml (3%)\n  - Evening Primrose Seed Oil: 15ml (3%)\n- **Phase C (Antioxidant & Scent Chord - 3%):**\n  - Non-GMO Mixed Tocopherols (Vitamin E): 5ml (1%)\n  - Artisan Botanical Essence (Bergamot FCF, Frankincense, Blue Tansy): 10ml (2%)\n\n#### 3. Whipped Kokum & Nilotica Body Butter (800g Batch)\n- **Phase A (Heated Anhydrous Lipid Matrix):**\n  - Raw Indian Kokum Butter (High Stearic/Hardness): 320g (40%)\n  - East African Nilotica Shea Butter (Silky/High Oleic): 280g (35%)\n  - Sweet Almond Carrier Oil: 144g (18%)\n- **Phase B (Cool Down Whipping Matrix at 32\u00B0C):**\n  - Organic Arrowroot Powder (Matte Silk Finish): 32g (4%)\n  - Rosemary Leaf CO2 Extract (Antioxidant): 8g (1%)\n  - Neroli & Santalum Essential Oil: 16g (2%)\n- **Process:** Melt to 70\u00B0C, rapid cool in ice bath to 25\u00B0C, high-shear whip for 12 mins until double volume cloud texture.\n\n*Note: All precision formulas have been structured with full INCI compliance, safety margins, and batch scaling specs.*`;\n\n    const functionCalls: any[] = [];\n    if (isExecutionRequest && matchedTask) {\n      functionCalls.push({\n        name: 'complete_task',\n        args: {\n          taskId: matchedTask.id,\n          actualOutcome: text,\n          completionNotes: 'Formulations drafted, verified with full INCI compliance, and scheduled onto calendar.'\n        }\n      });\n      functionCalls.push({\n        name: 'create_asset',\n        args: {\n          title: `Master Formulation: ${matchedTask.title}`,\n          content: text,\n          type: 'recipe',\n          author: 'Formulator'\n        }\n      });\n    }\n\n    functionCalls.push({\n      name: 'create_formulation',\n      args: {\n        name: 'Seasalt & Pacific Brine Bar (Bespoke Formula)',\n        ingredients: [\n          { name: 'Organic Extra Virgin Olive Oil', amount: 400, unit: 'g' },\n          { name: 'Raw Unrefined Coconut Oil', amount: 250, unit: 'g' },\n          { name: 'Fair-Trade Shea Butter', amount: 200, unit: 'g' },\n          { name: 'Cold-Pressed Castor Oil', amount: 100, unit: 'g' },\n          { name: 'Golden Jojoba Oil', amount: 50, unit: 'g' },\n          { name: 'Ultra-Fine Pacific Grey Sea Salt', amount: 150, unit: 'g' },\n          { name: 'Sodium Hydroxide (NaOH)', amount: 137, unit: 'g' },\n          { name: 'Mineral Ocean Brine / Pure Water', amount: 300, unit: 'g' }\n        ],\n        instructions: 'Dissolve NaOH into cold ocean brine. Melt shea butter and plant oils at 105\u00B0F. Pulse with stick blender to light trace. Fold in fine Pacific sea salt and aromatic accords. Pour into silicone individual cavity molds. Unmold within 14 hours and cure for 35 days.',\n        curingTimeDays: 35,\n        batchSize: 1000,\n        batchUnit: 'g'\n      }\n    });\n\n    functionCalls.push({\n      name: 'add_event',\n      args: {\n        title: 'Seasalt & Brine Bar - Batch Cure Complete',\n        date: new Date(Date.now() + 35 * 86400000).toISOString().split('T')[0],\n        type: 'production',\n        category: 'Soap',\n        description: 'Full 35-day cold process bar cure window complete. Ready for pH verification, packaging, and fulfillment.'\n      }\n    });\n\n    return { text, functionCalls: functionCalls.length > 0 ? functionCalls : undefined };\n  }\n\n  if (/marketing|campaign|instagram|social|story|launch|audience/i.test(query)) {\n    const text = `### \uD83D\uDCE3 Campaign Strategy & Storytelling\n**Focus Directive:** ${context}\n\n**Suggested 3-Phase Rollout:**\n1. **Teaser / Behind the Craft (Days 1\u20133):** Short-form video highlighting raw botanical sourcing and small-batch pouring.\n2. **Collection Drop / Early Access (Day 4):** Direct email blast to VIP and wholesale partners offering complimentary sampling.\n3. **Community Validation (Days 5\u20137):** Share behind-the-scenes curing logs and limited edition batch counters.`;\n\n    const functionCalls: any[] = [];\n    if (isExecutionRequest && matchedTask) {\n      functionCalls.push({\n        name: 'complete_task',\n        args: {\n          taskId: matchedTask.id,\n          actualOutcome: text,\n          completionNotes: 'Campaign strategy documented and staged for release.'\n        }\n      });\n      functionCalls.push({\n        name: 'create_asset',\n        args: {\n          title: `Marketing Strategy: ${matchedTask.title}`,\n          content: text,\n          type: 'marketing',\n          author: role\n        }\n      });\n    }\n\n    functionCalls.push({\n      name: 'create_campaign',\n      args: {\n        name: matchedTask ? matchedTask.title : 'Slow Botanicals Autumn Campaign',\n        platform: 'Instagram',\n        budget: 500,\n        notes: 'Omni-channel sensory storytelling drop.',\n        content: text\n      }\n    });\n\n    functionCalls.push({\n      name: 'add_event',\n      args: {\n        title: `Campaign Launch Drop: ${matchedTask ? matchedTask.title : 'Autumn Botanical Collection'}`,\n        date: new Date(Date.now() + 7 * 86400000).toISOString().split('T')[0],\n        type: 'marketing',\n        category: 'General',\n        description: 'Public release and VIP newsletter dispatch scheduled on Studio Planner.'\n      }\n    });\n\n    return { text, functionCalls: functionCalls.length > 0 ? functionCalls : undefined };\n  }\n\n  if (/cost|price|profit|margin|finance|wholesale|b2b/i.test(query)) {\n    const margin = state?.profile?.targetMargin || 65;\n    const text = `### \uD83D\uDC8E Profitability & Unit Economics Analysis\n**Financial Parameter Check:**\n- **Target Studio Gross Margin:** ${margin}%\n- **Wholesale Price Standard:** 50% of MSRP (ensuring 2.0x keystone pricing)\n- **Direct Material Buffer:** Add 10\u201312% overhead for eco-luxe packaging and compliance labels.\n\n*Recommendation:* Review supplier raw-material tier pricing for bulk savings on your highest volume inputs.`;\n\n    const functionCalls: any[] = [];\n    if (isExecutionRequest && matchedTask) {\n      functionCalls.push({\n        name: 'complete_task',\n        args: {\n          taskId: matchedTask.id,\n          actualOutcome: text,\n          completionNotes: 'Financial analysis verified against studio target margins.'\n        }\n      });\n      functionCalls.push({\n        name: 'create_asset',\n        args: {\n          title: `Financial Analysis: ${matchedTask.title}`,\n          content: text,\n          type: 'finance',\n          author: 'WealthAdvisor'\n        }\n      });\n    }\n\n    return { text, functionCalls: functionCalls.length > 0 ? functionCalls : undefined };\n  }\n\n  const defaultText = `Hello! I'm here as ${role} for ${state?.profile?.name || 'the studio'}. I've reviewed your note regarding \"${context}\". \n\nLet's collaborate on your recipes, inventory planning, campaigns, or calendar scheduling. Feel free to give me a specific directive or ask me to draft a new formulation!`;\n\n  const defaultCalls: any[] = [];\n  if (isExecutionRequest && matchedTask) {\n    defaultCalls.push({\n      name: 'complete_task',\n      args: {\n        taskId: matchedTask.id,\n        actualOutcome: defaultText,\n        completionNotes: `Directive resolved and recorded by ${role}.`\n      }\n    });\n    defaultCalls.push({\n      name: 'create_asset',\n      args: {\n        title: `${matchedTask.title} (Execution Record)`,\n        content: defaultText,\n        type: 'strategy',\n        author: role\n      }\n    });\n  }\n\n  return { text: defaultText, functionCalls: defaultCalls.length > 0 ? defaultCalls : undefined };\n}\n\n/**\n * Headless StudioLead \"Wake-Up\" Orchestrator invoked automatically on webhook receipt or 1-click re-run.\n * Combines deterministic COGS/BOM/50%-deposit/cure math with optional Gemini StudioLead executive narrative.\n * Strictly internal-only: NEVER sends emails, SMS, webhooks, or external invoices.\n */\nexport async function runHeadlessStudioLeadIntake(\n  order: IncomingOrderQuote,\n  stateSnapshot?: any,\n  agreedCatalog?: StorefrontAgreementCatalog,\n): Promise<{\n  evaluation: ReturnType<typeof evaluateIncomingOrderOrQuote>;\n  agentNarrative: string;\n  model?: string;\n  toolsSuggested: Array<{ name: string; args: Record<string, any> }>;\n}> {\n  const evaluation = evaluateIncomingOrderOrQuote(order, stateSnapshot, agreedCatalog);\n  const catalog = agreedCatalog || buildDefaultAgreementCatalog();\n  const stateWithOrder = {\n    ...(stateSnapshot || {}),\n    incomingOrders: [order, ...((stateSnapshot?.incomingOrders || []).filter((o: any) => o.id !== order.id))],\n  };\n\n  let agentNarrative = [\n    `[StudioLead Internal Dossier \u2014 ${order.referenceCode}]`,\n    `Mode: ${order.environment === 'staging' ? 'STAGING SANDBOX' : order.requestType.toUpperCase()}`,\n    `Net Revenue: $${evaluation.netRevenueCad?.toFixed(2)} CAD | Total COGS: $${evaluation.totalCogsCad.toFixed(2)} CAD | Margin: ${evaluation.grossMarginPct.toFixed(1)}%`,\n    `Required ${evaluation.depositPct}% Deposit: $${evaluation.b2bDepositRequiredCad.toFixed(2)} CAD (Covers 100% Direct Raw+Pkg COGS: ${evaluation.b2bDepositCoversDirectCogs ? 'YES' : 'NO'})`,\n    `Shortfalls: ${evaluation.shortfalls.length} item(s) | Earliest Safe Ship Date: ${evaluation.earliestPossibleDeliveryDate}`,\n    `Notice: Internal dossier staged for Myrna's review. Zero external emails or client replies sent.`,\n  ].join('\\n');\n\n  let usedModel: string | undefined = 'deterministic-studio-engine';\n  const toolsSuggested: Array<{ name: string; args: Record<string, any> }> = [];\n\n  if (shouldUseGeminiForHeadlessIntake(order.environment)) {\n    const promptText = [\n      `HEADLESS ARTY WAKE-UP INTAKE: Analyze inbound ${order.environment} ${order.requestType} [${order.referenceCode}].`,\n      `Client: ${order.client.companyName} (${order.client.contactPerson}, ${order.client.province || 'CA'}, Locale: ${order.locale}).`,\n      `Line Items: ${order.lineItems.map((l) => `${l.quantity}x ${l.sku} ${l.productName} ($${l.unitPrice || 0})`).join('; ')}.`,\n      `Deterministic Evaluation Snapshot:`,\n      `- Dossier Status: ${evaluation.dossierStatus}`,\n      `- Finished Ready: ${evaluation.totalFinishedStockAvailable} units | Pour Needed: ${evaluation.totalUnitsToProduce} units`,\n      `- Total COGS: $${evaluation.totalCogsCad.toFixed(2)} (Direct Materials+Pkg: $${evaluation.directMaterialsAndPackagingCogsCad?.toFixed(2)})`,\n      `- Net Revenue: $${evaluation.netRevenueCad?.toFixed(2)} | Margin: ${evaluation.grossMarginPct.toFixed(1)}% (Floor 70%: ${evaluation.meetsMarginFloor ? 'PASS' : 'LOW'})`,\n      `- B2B ${evaluation.depositPct}% Deposit: $${evaluation.b2bDepositRequiredCad.toFixed(2)} | Covers 100% Direct COGS: ${evaluation.b2bDepositCoversDirectCogs ? 'YES' : 'SHORT by $' + evaluation.depositCashFlowGapCad}`,\n      `- Shortfalls: ${evaluation.shortfalls.map((s) => `${s.itemName}: short ${s.shortfallQty}${s.unit}`).join('; ') || 'None'}`,\n      `- Cure / Earliest Ship Date: ${evaluation.earliestPossibleDeliveryDate} (Requested: ${evaluation.requestedDeliveryDate || 'None'}; Feasible: ${evaluation.cureFeasible})`,\n      `Provide a concise 4-bullet internal executive briefing for Myrna ONLY (never draft an external send action). Do not contradict the deterministic figures above.`,\n    ].join('\\n');\n\n    try {\n      const geminiRes = await getAgentResponseServer('StudioLead', promptText, [], stateWithOrder, catalog);\n      if (geminiRes?.text && !geminiRes.isFallback) {\n        agentNarrative = geminiRes.text;\n        usedModel = geminiRes.model;\n      }\n      if (Array.isArray(geminiRes?.functionCalls)) {\n        for (const fc of geminiRes.functionCalls) {\n          if (fc?.name && !/email|send_external|notify_client/i.test(fc.name)) {\n            toolsSuggested.push({ name: fc.name, args: fc.args || {} });\n          }\n        }\n      }\n    } catch (err) {\n      console.warn('[StudioLead Headless] Falling back to deterministic internal briefing:', err);\n    }\n  }\n\n  return {\n    evaluation,\n    agentNarrative,\n    model: usedModel,\n    toolsSuggested,\n  };\n}\n\n", "import crypto from 'crypto';\n\n/**\n * Computes HMAC-SHA256 signature formatted as `sha256=<hex>`.\n */\nexport function computeHmacSha256Signature(rawBody: string | Buffer, secret: string): string {\n  const digest = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');\n  return `sha256=${digest}`;\n}\n\n/**\n * Verifies `X-Bridge-Signature: sha256=<hex>` using constant-time comparison.\n */\nexport function verifyHmacSha256Signature(\n  rawBody: string | Buffer,\n  signatureHeader: string | undefined,\n  secret: string,\n): boolean {\n  if (!signatureHeader || !secret) return false;\n  const trimmed = signatureHeader.trim();\n  const normalizedIncoming = trimmed.toLowerCase().startsWith('sha256=')\n    ? trimmed.slice(7).trim().toLowerCase()\n    : trimmed.toLowerCase();\n\n  if (!/^[a-f0-9]{64}$/.test(normalizedIncoming)) {\n    return false;\n  }\n\n  const expectedHex = crypto\n    .createHmac('sha256', secret)\n    .update(rawBody)\n    .digest('hex')\n    .toLowerCase();\n\n  return crypto.timingSafeEqual(\n    Buffer.from(normalizedIncoming, 'hex'),\n    Buffer.from(expectedHex, 'hex'),\n  );\n}\n\n/**\n * Extracts bridge key from `X-Bridge-Key` or `Authorization: Bearer <token>`.\n */\nexport function extractBridgeToken(\n  headers: Record<string, string | string[] | undefined>,\n): string | null {\n  const lowerMap: Record<string, string> = {};\n  for (const [k, v] of Object.entries(headers)) {\n    if (typeof v === 'string') lowerMap[k.toLowerCase()] = v;\n    else if (Array.isArray(v) && v[0]) lowerMap[k.toLowerCase()] = v[0];\n  }\n\n  const xKey = lowerMap['x-bridge-key']?.trim();\n  if (xKey) return xKey;\n\n  const auth = lowerMap['authorization']?.trim();\n  if (auth && auth.toLowerCase().startsWith('bearer ')) {\n    const token = auth.slice(7).trim();\n    if (token) return token;\n  }\n\n  return null;\n}\n\n/**\n * Constant-time token comparison via SHA-256 hash equalization so token lengths never leak.\n */\nexport function tokensMatchConstantTime(provided: string | null, expected: string): boolean {\n  if (!provided || !expected) return false;\n  const a = crypto.createHash('sha256').update(provided).digest();\n  const b = crypto.createHash('sha256').update(expected).digest();\n  return crypto.timingSafeEqual(a, b);\n}\n\n/**\n * Sanitizes a capsule ID into a Firestore-safe document identifier (`^[a-zA-Z0-9_-]{1,120}$`).\n */\nexport function sanitizeFirestoreDocId(rawId: string): string {\n  const cleaned = rawId.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 100);\n  if (cleaned.length >= 3) return cleaned;\n  return crypto.createHash('sha256').update(rawId).digest('hex').slice(0, 32);\n}\n", "import {\n  computeHmacSha256Signature,\n  verifyHmacSha256Signature,\n} from './bridgeSecurity.js';\nimport type { IncomingOrderQuote } from '../types.js';\n\nexport type StorefrontEnvironment = 'staging' | 'production';\nexport type StorefrontTrack = 'b2b' | 'eczema' | 'menopause' | 'purity';\nexport type StorefrontSkuKind = 'kit' | 'addon' | 'sample' | 'product' | 'bundle';\nexport type StorefrontAvailabilityStatus =\n  | 'preorder'\n  | 'sample_only'\n  | 'in_development'\n  | 'in_stock'\n  | 'sold_out';\n\nexport type StorefrontEventType =\n  | 'b2b_inquiry'\n  | 'b2b_sample_request'\n  | 'retail_preorder'\n  | 'retail_paid_order'\n  | 'ping';\n\nexport interface AgreedCatalogSku {\n  sku: string;\n  storefrontSlug: string;\n  variantKey: string;\n  track: StorefrontTrack;\n  kind: StorefrontSkuKind;\n  nameEn: string;\n  nameFr: string;\n  formatLabel: string;\n  priceCad: number;\n  status: StorefrontAvailabilityStatus;\n  stockAvailable: number;\n  cureLeadDays: number;\n  cureReadyDate: string | null;\n  moq: number;\n  unitCogsCad: number;\n  deductsMaterials: boolean;\n  activeOnStorefront: boolean;\n}\n\nexport interface StorefrontAgreementCatalog {\n  schemaVersion: '1.0.0';\n  catalogVersion: number;\n  updatedAt: string;\n  brandPositioning: {\n    primaryFace: 'b2b';\n    secondaryTracks: Array<'eczema' | 'menopause'>;\n    currency: 'CAD';\n    b2bPriorityNote: string;\n    taxMode: 'estimated_canadian_provincial';\n  };\n  products: AgreedCatalogSku[];\n}\n\nexport interface StorefrontInboundLineItem {\n  sku?: string;\n  storefrontSlug: string;\n  variantKey: string;\n  name: string;\n  qty: number;\n  unitPriceCad: number;\n}\n\nexport interface StorefrontInboundEvent {\n  schemaVersion: 'ljw-storefront-v1';\n  idempotencyKey: string;\n  environment: StorefrontEnvironment;\n  eventType: StorefrontEventType;\n  track: 'b2b' | 'eczema' | 'menopause';\n  referenceCode: string;\n  occurredAt: string;\n  locale: 'en' | 'fr' | 'bilingual';\n  province?: string;\n  fulfillmentPreference?: 'bulk_studio' | 'direct_homeowner';\n  targetDeliveryWindow?: string;\n  contact: {\n    firmName?: string;\n    contactName: string;\n    email: string;\n    phone?: string;\n    partnerRole?: string;\n  };\n  lineItems: StorefrontInboundLineItem[];\n  subtotalCad: number;\n  discountCad: number;\n  taxBreakdown: {\n    tpsCad: number;\n    tvqCad: number;\n    hstCad: number;\n    totalTaxCad: number;\n    estimated: boolean;\n  };\n  totalCad: number;\n  coBrandingOptions: string[];\n  requestSampleKit: boolean;\n  appliedCouponCode?: string;\n  sanitizedNotes: string;\n  healthNotesRedacted: boolean;\n  paymentVerification?: {\n    provider: 'stripe';\n    paymentIntentId: string;\n    verifiedOnStorefrontServer: boolean;\n    amountPaidCad: number;\n  } | null;\n  requestType?: 'quote_request' | 'paid_order';\n  client?: {\n    companyName?: string;\n    contactPerson?: string;\n    email?: string;\n    phone?: string;\n    accountType?: string;\n    province?: string;\n    city?: string;\n  };\n  projectDetails?: {\n    developmentName?: string;\n    addressOrLocation?: string;\n    unitCount?: number;\n    audienceMode?: 'homeowner' | 'renter';\n    scentProfile?: string;\n  };\n  timeline?: {\n    requestedDeliveryDate?: string;\n    targetDeliveryWindow?: string;\n  };\n  payment?: {\n    subtotal: number;\n    depositAmount: number;\n    status: 'unpaid' | 'quote_only' | 'deposit_paid' | 'paid_verified';\n    paymentIntentId?: string;\n    verifiedOnServer?: boolean;\n  };\n}\n\nexport interface StorefrontValidationResult {\n  valid: boolean;\n  error?: string;\n  issues?: string[];\n  event?: StorefrontInboundEvent;\n}\n\nconst MAX_REPLAY_SKEW_SECONDS = 300; // +/- 5 minutes\n\n/**\n * Signs a raw JSON payload using `<timestamp>.<rawBody>` so every webhook carries replay protection.\n */\nexport function signTimestampedPayload(\n  rawBody: string | Buffer,\n  secret: string,\n  timestampSec: number = Math.floor(Date.now() / 1000),\n): { timestamp: string; signature: string } {\n  const ts = String(Math.floor(timestampSec));\n  const bodyStr = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : rawBody;\n  const canonical = `${ts}.${bodyStr}`;\n  return {\n    timestamp: ts,\n    signature: computeHmacSha256Signature(canonical, secret),\n  };\n}\n\n/**\n * Verifies `X-Bridge-Timestamp` (+/- 5 min) + `X-Bridge-Signature: sha256=<hex>` over `<ts>.<rawBody>`.\n */\nexport function verifyTimestampedHmacSignature(params: {\n  rawBody: string | Buffer;\n  signatureHeader?: string;\n  timestampHeader?: string;\n  secret: string;\n  maxSkewSeconds?: number;\n  nowMs?: number;\n}): { ok: boolean; reason?: string } {\n  const {\n    rawBody,\n    signatureHeader,\n    timestampHeader,\n    secret,\n    maxSkewSeconds = MAX_REPLAY_SKEW_SECONDS,\n    nowMs = Date.now(),\n  } = params;\n\n  if (!secret) {\n    return { ok: false, reason: 'HMAC secret is not configured.' };\n  }\n  if (!timestampHeader || !timestampHeader.trim()) {\n    return { ok: false, reason: 'Missing X-Bridge-Timestamp header for replay protection.' };\n  }\n  const parsedTs = Number(timestampHeader.trim());\n  if (!Number.isFinite(parsedTs) || parsedTs <= 0) {\n    return { ok: false, reason: 'Invalid X-Bridge-Timestamp header.' };\n  }\n\n  // Accept either epoch seconds (10 digits) or epoch ms (13 digits) safely\n  const tsMs = parsedTs > 1e12 ? parsedTs : parsedTs * 1000;\n  const tsSecNormalized = Math.floor(tsMs / 1000);\n  const skewSeconds = Math.abs(nowMs - tsMs) / 1000;\n  if (skewSeconds > maxSkewSeconds) {\n    return {\n      ok: false,\n      reason: `Request timestamp outside +/-${maxSkewSeconds}s replay window.`,\n    };\n  }\n\n  if (!signatureHeader || !signatureHeader.trim()) {\n    return { ok: false, reason: 'Missing X-Bridge-Signature header.' };\n  }\n\n  const bodyStr = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : rawBody;\n  const canonical = `${tsSecNormalized}.${bodyStr}`;\n  const valid = verifyHmacSha256Signature(canonical, signatureHeader, secret);\n\n  // Also check raw timestampHeader string verbatim in case sender signed epoch ms directly\n  if (!valid && timestampHeader.trim() !== String(tsSecNormalized)) {\n    const verbatimCanonical = `${timestampHeader.trim()}.${bodyStr}`;\n    if (verifyHmacSha256Signature(verbatimCanonical, signatureHeader, secret)) {\n      return { ok: true };\n    }\n  }\n\n  return valid\n    ? { ok: true }\n    : { ok: false, reason: 'Invalid X-Bridge-Signature HMAC-SHA256 digest.' };\n}\n\n/**\n * Blocks SSRF targets (loopback, link-local, metadata, RFC1918 private IPs, .local/.internal).\n * Requires HTTPS for all remote Storefront bridge traffic.\n */\nexport function validateSafeStorefrontUrl(rawUrl: string): {\n  valid: boolean;\n  normalizedUrl?: string;\n  error?: string;\n} {\n  const trimmed = String(rawUrl || '').trim().replace(/\\/+$/, '');\n  if (!trimmed) {\n    return { valid: false, error: 'Storefront URL is required.' };\n  }\n\n  let parsed: URL;\n  try {\n    parsed = new URL(trimmed);\n  } catch {\n    return { valid: false, error: 'Invalid Storefront URL format.' };\n  }\n\n  if (parsed.protocol !== 'https:') {\n    return { valid: false, error: 'Storefront URL must use https://.' };\n  }\n\n  const host = parsed.hostname.toLowerCase();\n  if (!host) {\n    return { valid: false, error: 'Storefront URL hostname is missing.' };\n  }\n\n  const blockedHosts = new Set([\n    'localhost',\n    '127.0.0.1',\n    '::1',\n    '[::1]',\n    '0.0.0.0',\n    'metadata.google.internal',\n    '169.254.169.254',\n  ]);\n\n  if (\n    blockedHosts.has(host) ||\n    host.endsWith('.local') ||\n    host.endsWith('.internal') ||\n    host.endsWith('.localhost')\n  ) {\n    return { valid: false, error: 'Private or loopback Storefront URLs are not permitted.' };\n  }\n\n  // Block RFC1918 & link-local IPv4 ranges\n  const ipv4Match = host.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n  if (ipv4Match) {\n    const [_, aStr, bStr] = ipv4Match;\n    const a = Number(aStr);\n    const b = Number(bStr);\n    if (\n      a === 10 ||\n      a === 127 ||\n      a === 0 ||\n      (a === 169 && b === 254) ||\n      (a === 172 && b >= 16 && b <= 31) ||\n      (a === 192 && b === 168)\n    ) {\n      return { valid: false, error: 'Private IPv4 Storefront URLs are blocked.' };\n    }\n  }\n\n  return { valid: true, normalizedUrl: `${parsed.origin}${parsed.pathname === '/' ? '' : parsed.pathname}` };\n}\n\n/**\n * Computes Quebec/Canadian tax estimates truthfully in CAD.\n */\nexport function computeCanadianTaxes(subtotalCad: number, province?: string): {\n  tpsCad: number;\n  tvqCad: number;\n  hstCad: number;\n  totalTaxCad: number;\n  estimated: boolean;\n} {\n  const safeSubtotal = Math.max(0, Number(subtotalCad) || 0);\n  const prov = (province || '').trim().toUpperCase();\n  const round = (v: number) => Number(v.toFixed(2));\n\n  if (prov === 'QC' || prov === 'QUEBEC' || prov === 'QU\u00C9BEC') {\n    const tpsCad = round(safeSubtotal * 0.05);\n    const tvqCad = round(safeSubtotal * 0.09975);\n    return {\n      tpsCad,\n      tvqCad,\n      hstCad: 0,\n      totalTaxCad: round(tpsCad + tvqCad),\n      estimated: true,\n    };\n  }\n\n  if (prov === 'ON' || prov === 'ONTARIO') {\n    const hstCad = round(safeSubtotal * 0.13);\n    return { tpsCad: 0, tvqCad: 0, hstCad, totalTaxCad: hstCad, estimated: true };\n  }\n\n  if (['NB', 'NL', 'NS', 'PE'].includes(prov)) {\n    const hstCad = round(safeSubtotal * 0.15);\n    return { tpsCad: 0, tvqCad: 0, hstCad, totalTaxCad: hstCad, estimated: true };\n  }\n\n  // Default Canadian GST 5%\n  const tpsCad = round(safeSubtotal * 0.05);\n  return { tpsCad, tvqCad: 0, hstCad: 0, totalTaxCad: tpsCad, estimated: true };\n}\n\n/**\n * Minimizes sensitive personal health/skin free-text on retail Eczema & Menopause tracks.\n */\nexport function sanitizeHealthAndInquiryNotes(\n  rawText: unknown,\n  track: 'b2b' | 'eczema' | 'menopause',\n): { sanitizedNotes: string; healthNotesRedacted: boolean } {\n  const text = String(rawText || '')\n    .replace(/<[^>]*>/g, ' ')\n    .replace(/[\\u0000-\\u001F\\u007F]/g, ' ')\n    .replace(/\\s+/g, ' ')\n    .trim();\n\n  if (!text) {\n    return { sanitizedNotes: '', healthNotesRedacted: false };\n  }\n\n  if (track === 'eczema' || track === 'menopause') {\n    return {\n      sanitizedNotes:\n        '[Health & ritual free-text redacted by PII minimization policy; see structured lineItems only.]',\n      healthNotesRedacted: true,\n    };\n  }\n\n  return {\n    sanitizedNotes: text.slice(0, 1200),\n    healthNotesRedacted: false,\n  };\n}\n\n/**\n * Validates incoming Storefront event payloads with strict Staging/Production separation\n * and zero trust on client-asserted \"paid\" statuses without server payment verification.\n */\nexport function validateStorefrontInboundEvent(raw: unknown): StorefrontValidationResult {\n  const issues: string[] = [];\n  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n    return { valid: false, error: 'Payload must be a JSON object.', issues: ['Payload is not an object'] };\n  }\n\n  const obj = raw as Record<string, any>;\n\n  const environment = obj.environment;\n  if (environment !== 'staging' && environment !== 'production') {\n    issues.push(\"environment must explicitly be 'staging' or 'production' (never infer from delivery stagingMode).\");\n  }\n\n  const track = obj.track;\n  if (track !== 'b2b' && track !== 'eczema' && track !== 'menopause') {\n    issues.push(\"track must be 'b2b', 'eczema', or 'menopause'.\");\n  }\n\n  const allowedEventTypes: StorefrontEventType[] = [\n    'b2b_inquiry',\n    'b2b_sample_request',\n    'retail_preorder',\n    'retail_paid_order',\n    'ping',\n  ];\n  const inferredEventType: StorefrontEventType | undefined =\n    !obj.eventType && (obj.requestType === 'quote_request' || obj.requestType === 'paid_order')\n      ? obj.requestType === 'paid_order'\n        ? 'retail_paid_order'\n        : track === 'b2b'\n          ? 'b2b_inquiry'\n          : 'retail_preorder'\n      : undefined;\n  const eventType = (obj.eventType || inferredEventType) as StorefrontEventType;\n  if (!allowedEventTypes.includes(eventType)) {\n    issues.push(`eventType must be one of: ${allowedEventTypes.join(', ')}.`);\n  }\n\n  const idempotencyKey = String(\n    obj.idempotencyKey || obj.externalOrderId || obj.emailMessageId || '',\n  ).trim();\n  if (idempotencyKey.length < 8 || idempotencyKey.length > 128) {\n    issues.push('idempotencyKey (or externalOrderId / emailMessageId) must be 8\u2013128 characters.');\n  }\n\n  const contactRaw =\n    obj.contact && typeof obj.contact === 'object'\n      ? obj.contact\n      : obj.client && typeof obj.client === 'object'\n        ? obj.client\n        : {};\n  const clientRaw = obj.client && typeof obj.client === 'object' ? obj.client : {};\n  const contactName = String(\n    contactRaw.contactName || contactRaw.contactPerson || contactRaw.name || clientRaw.contactPerson || '',\n  )\n    .trim()\n    .slice(0, 160);\n  const email = String(contactRaw.email || clientRaw.email || '').trim().slice(0, 200);\n  if (eventType !== 'ping') {\n    if (!contactName) issues.push('contact.contactName is required.');\n    if (!email || !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) {\n      issues.push('contact.email must be a valid email address.');\n    }\n  }\n\n  const rawItems = Array.isArray(obj.lineItems) ? obj.lineItems : [];\n  if (eventType !== 'ping' && eventType !== 'b2b_sample_request' && rawItems.length === 0) {\n    issues.push('lineItems must contain at least one item for orders or inquiries.');\n  }\n\n  const lineItems: StorefrontInboundLineItem[] = rawItems.slice(0, 50).map((item: any, idx: number) => {\n    const rawName = String(item?.name || item?.productName || '').trim().slice(0, 200);\n    const derivedSlug = rawName\n      ? rawName.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 100)\n      : '';\n    const storefrontSlug = String(item?.storefrontSlug || item?.productId || derivedSlug || '').trim().slice(0, 100);\n    const variantKey = String(item?.variantKey || item?.variantLabel || item?.boxEdition || 'default').trim().slice(0, 60);\n    const name = rawName || storefrontSlug || `Item ${idx + 1}`;\n    const qty = Math.max(1, Math.min(10000, Math.round(Number(item?.qty ?? item?.quantity) || 1)));\n    const unitPriceCad = Math.max(0, Number(Number(item?.unitPriceCad ?? item?.unitPrice ?? item?.priceCad ?? 0).toFixed(2)));\n    const sku = item?.sku ? String(item.sku).trim().slice(0, 80) : undefined;\n\n    if (!storefrontSlug) {\n      issues.push(`lineItems[${idx}].storefrontSlug is required.`);\n    }\n    return { sku, storefrontSlug, variantKey, name, qty, unitPriceCad };\n  });\n\n  const requestedType =\n    obj.requestType === 'paid_order' || eventType === 'retail_paid_order'\n      ? 'paid_order'\n      : 'quote_request';\n\n  if (eventType === 'retail_paid_order' || obj.requestType === 'paid_order') {\n    const pv = obj.paymentVerification;\n    const payObj = obj.payment;\n    const hasVerifiedStripe =\n      pv &&\n      pv.provider === 'stripe' &&\n      pv.verifiedOnStorefrontServer === true &&\n      typeof pv.paymentIntentId === 'string' &&\n      pv.paymentIntentId.trim().length >= 6 &&\n      Number(pv.amountPaidCad) > 0;\n    const hasVerifiedPaymentObj =\n      payObj &&\n      payObj.verifiedOnServer === true &&\n      (payObj.status === 'paid_verified' || payObj.status === 'deposit_paid') &&\n      (Number(payObj.depositAmount) > 0 || Number(payObj.subtotal) > 0);\n\n    if (!hasVerifiedStripe && !hasVerifiedPaymentObj) {\n      issues.push(\n        'retail_paid_order requires verified Stripe paymentVerification (verifiedOnStorefrontServer: true, paymentIntentId, positive amountPaidCad).',\n      );\n    }\n  }\n\n  if (issues.length > 0) {\n    return {\n      valid: false,\n      error: issues[0],\n      issues,\n    };\n  }\n\n  const computedSubtotal = Number(\n    lineItems.reduce((sum, li) => sum + li.unitPriceCad * li.qty, 0).toFixed(2),\n  );\n  const subtotalCad =\n    Number.isFinite(Number(obj.subtotalCad)) && Number(obj.subtotalCad) >= 0\n      ? Number(Number(obj.subtotalCad).toFixed(2))\n      : computedSubtotal;\n  const discountCad = Math.max(0, Number(Number(obj.discountCad || 0).toFixed(2)));\n  const province = obj.province ? String(obj.province).trim().toUpperCase().slice(0, 20) : undefined;\n  const taxableBase = Math.max(0, Number((subtotalCad - discountCad).toFixed(2)));\n  const taxBreakdown =\n    obj.taxBreakdown && typeof obj.taxBreakdown === 'object'\n      ? {\n          tpsCad: Math.max(0, Number(Number(obj.taxBreakdown.tpsCad || 0).toFixed(2))),\n          tvqCad: Math.max(0, Number(Number(obj.taxBreakdown.tvqCad || 0).toFixed(2))),\n          hstCad: Math.max(0, Number(Number(obj.taxBreakdown.hstCad || 0).toFixed(2))),\n          totalTaxCad: Math.max(0, Number(Number(obj.taxBreakdown.totalTaxCad || 0).toFixed(2))),\n          estimated: Boolean(obj.taxBreakdown.estimated ?? true),\n        }\n      : computeCanadianTaxes(taxableBase, province);\n\n  const totalCad =\n    Number.isFinite(Number(obj.totalCad)) && Number(obj.totalCad) >= 0\n      ? Number(Number(obj.totalCad).toFixed(2))\n      : Number((taxableBase + taxBreakdown.totalTaxCad).toFixed(2));\n\n  const { sanitizedNotes, healthNotesRedacted } = sanitizeHealthAndInquiryNotes(\n    obj.notes ?? obj.sanitizedNotes,\n    track,\n  );\n\n  const locale: 'en' | 'fr' | 'bilingual' =\n    obj.locale === 'fr' || obj.locale === 'bilingual' ? obj.locale : 'en';\n\n  const fulfillmentPreference: 'bulk_studio' | 'direct_homeowner' | undefined =\n    obj.fulfillmentPreference === 'bulk_studio' || obj.fulfillmentPreference === 'direct_homeowner'\n      ? obj.fulfillmentPreference\n      : undefined;\n\n  const requestedDeliveryDate =\n    typeof obj.timeline?.requestedDeliveryDate === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(obj.timeline.requestedDeliveryDate)\n      ? obj.timeline.requestedDeliveryDate.slice(0, 10)\n      : undefined;\n\n  const projectDetails =\n    obj.projectDetails && typeof obj.projectDetails === 'object'\n      ? {\n          ...(obj.projectDetails.developmentName ? { developmentName: String(obj.projectDetails.developmentName).trim().slice(0, 160) } : {}),\n          ...(obj.projectDetails.addressOrLocation ? { addressOrLocation: String(obj.projectDetails.addressOrLocation).trim().slice(0, 200) } : {}),\n          ...(Number(obj.projectDetails.unitCount) > 0 ? { unitCount: Math.round(Number(obj.projectDetails.unitCount)) } : {}),\n          ...(obj.projectDetails.audienceMode === 'homeowner' || obj.projectDetails.audienceMode === 'renter'\n            ? { audienceMode: obj.projectDetails.audienceMode }\n            : {}),\n          ...(obj.projectDetails.scentProfile ? { scentProfile: String(obj.projectDetails.scentProfile).trim().slice(0, 160) } : {}),\n        }\n      : undefined;\n\n  const event: StorefrontInboundEvent = {\n    schemaVersion: 'ljw-storefront-v1',\n    idempotencyKey,\n    environment,\n    eventType,\n    track,\n    referenceCode: String(obj.referenceCode || `LJW-${idempotencyKey.slice(0, 8).toUpperCase()}`)\n      .trim()\n      .slice(0, 80),\n    occurredAt:\n      typeof obj.occurredAt === 'string' && !Number.isNaN(Date.parse(obj.occurredAt))\n        ? obj.occurredAt\n        : new Date().toISOString(),\n    locale,\n    ...(province ? { province } : {}),\n    ...(fulfillmentPreference ? { fulfillmentPreference } : {}),\n    ...(obj.targetDeliveryWindow\n      ? { targetDeliveryWindow: String(obj.targetDeliveryWindow).trim().slice(0, 80) }\n      : {}),\n    contact: {\n      ...(contactRaw.firmName || clientRaw.companyName\n        ? { firmName: String(contactRaw.firmName || clientRaw.companyName).trim().slice(0, 200) }\n        : {}),\n      contactName: contactName || 'Ping Check',\n      email: email || 'system@ljwellness.net',\n      ...(contactRaw.phone || clientRaw.phone\n        ? { phone: String(contactRaw.phone || clientRaw.phone).trim().slice(0, 60) }\n        : {}),\n      ...(contactRaw.partnerRole || clientRaw.accountType\n        ? { partnerRole: String(contactRaw.partnerRole || clientRaw.accountType).trim().slice(0, 80) }\n        : {}),\n    },\n    lineItems,\n    subtotalCad,\n    discountCad,\n    taxBreakdown,\n    totalCad,\n    coBrandingOptions: Array.isArray(obj.coBrandingOptions)\n      ? obj.coBrandingOptions.slice(0, 10).map((s: unknown) => String(s).trim().slice(0, 80))\n      : [],\n    requestSampleKit: Boolean(obj.requestSampleKit),\n    ...(obj.appliedCouponCode\n      ? { appliedCouponCode: String(obj.appliedCouponCode).trim().slice(0, 40) }\n      : {}),\n    sanitizedNotes,\n    healthNotesRedacted,\n    paymentVerification: obj.paymentVerification\n      ? {\n          provider: 'stripe',\n          paymentIntentId: String(obj.paymentVerification.paymentIntentId).trim().slice(0, 120),\n          verifiedOnStorefrontServer: Boolean(obj.paymentVerification.verifiedOnStorefrontServer),\n          amountPaidCad: Number(Number(obj.paymentVerification.amountPaidCad).toFixed(2)),\n        }\n      : null,\n    requestType: requestedType,\n    client: {\n      ...(contactRaw.firmName || clientRaw.companyName\n        ? { companyName: String(contactRaw.firmName || clientRaw.companyName).trim().slice(0, 200) }\n        : {}),\n      contactPerson: contactName || 'Ping Check',\n      email: email || 'system@ljwellness.net',\n      ...(contactRaw.phone || clientRaw.phone\n        ? { phone: String(contactRaw.phone || clientRaw.phone).trim().slice(0, 60) }\n        : {}),\n      ...(contactRaw.partnerRole || clientRaw.accountType\n        ? { accountType: String(contactRaw.partnerRole || clientRaw.accountType).trim().slice(0, 80) }\n        : {}),\n      ...(province || clientRaw.province ? { province: province || String(clientRaw.province).trim().toUpperCase() } : {}),\n      ...(clientRaw.city ? { city: String(clientRaw.city).trim().slice(0, 100) } : {}),\n    },\n    ...(projectDetails ? { projectDetails } : {}),\n    timeline: {\n      ...(requestedDeliveryDate ? { requestedDeliveryDate } : {}),\n      ...(obj.targetDeliveryWindow || obj.timeline?.targetDeliveryWindow\n        ? { targetDeliveryWindow: String(obj.timeline?.targetDeliveryWindow || obj.targetDeliveryWindow).trim().slice(0, 80) }\n        : {}),\n    },\n    ...(obj.payment && typeof obj.payment === 'object'\n      ? {\n          payment: {\n            subtotal: Number(Number(obj.payment.subtotal ?? subtotalCad).toFixed(2)),\n            depositAmount: Number(Number(obj.payment.depositAmount ?? 0).toFixed(2)),\n            status: ['unpaid', 'quote_only', 'deposit_paid', 'paid_verified'].includes(obj.payment.status)\n              ? obj.payment.status\n              : 'quote_only',\n            ...(obj.payment.paymentIntentId ? { paymentIntentId: String(obj.payment.paymentIntentId) } : {}),\n            ...(obj.payment.verifiedOnServer !== undefined ? { verifiedOnServer: Boolean(obj.payment.verifiedOnServer) } : {}),\n          },\n        }\n      : {}),\n  };\n\n  return { valid: true, event };\n}\n\n/**\n * Converts a validated StorefrontInboundEvent into an IncomingOrderQuote operational dossier record.\n */\nexport function inboundEventToIncomingOrderQuote(\n  event: StorefrontInboundEvent,\n  docId: string,\n): IncomingOrderQuote & { coBrandingOptions?: string[]; discountCad?: number } {\n  const isPaid =\n    event.eventType === 'retail_paid_order' ||\n    (event.requestType === 'paid_order' && Boolean(event.paymentVerification?.verifiedOnStorefrontServer || event.payment?.verifiedOnServer));\n  const requestType: 'quote_request' | 'paid_order' = isPaid ? 'paid_order' : 'quote_request';\n\n  const accountType =\n    event.client?.accountType ||\n    event.contact.partnerRole ||\n    (event.track === 'b2b' ? 'Luxury Builder' : 'Retail');\n\n  return {\n    id: docId,\n    idempotencyKey: event.idempotencyKey,\n    source: 'storefront',\n    environment: event.environment,\n    requestType,\n    status: event.environment === 'staging' ? 'sandbox_isolated' : 'pending_review',\n    referenceCode: event.referenceCode,\n    receivedAt: event.occurredAt || new Date().toISOString(),\n    locale: event.locale,\n    ...(event.province || event.client?.province ? { province: event.province || event.client?.province } : {}),\n    client: {\n      companyName: event.client?.companyName || event.contact.firmName || event.contact.contactName,\n      contactPerson: event.client?.contactPerson || event.contact.contactName,\n      email: event.client?.email || event.contact.email,\n      ...(event.client?.phone || event.contact.phone ? { phone: event.client?.phone || event.contact.phone } : {}),\n      accountType,\n      ...(event.province || event.client?.province ? { province: event.province || event.client?.province } : {}),\n      ...(event.client?.city ? { city: event.client.city } : {}),\n    },\n    lineItems: event.lineItems.map((li) => ({\n      sku: li.sku || li.storefrontSlug.toUpperCase(),\n      productName: li.name,\n      storefrontSlug: li.storefrontSlug,\n      variantKey: li.variantKey,\n      boxEdition:\n        event.fulfillmentPreference === 'bulk_studio'\n          ? 'Uniform Development QR'\n          : li.variantKey === 'default'\n            ? 'Builder Wholesale Run'\n            : li.variantKey,\n      quantity: li.qty,\n      unitPrice: li.unitPriceCad,\n    })),\n    ...(event.projectDetails ? { projectDetails: event.projectDetails } : {}),\n    ...(event.timeline ? { timeline: event.timeline } : {}),\n    payment: {\n      subtotal: event.subtotalCad,\n      depositAmount: event.payment?.depositAmount ?? (event.paymentVerification?.amountPaidCad ?? 0),\n      total: event.totalCad,\n      status: isPaid\n        ? 'paid_verified'\n        : event.eventType === 'retail_preorder'\n          ? 'unpaid'\n          : 'quote_only',\n      ...(event.paymentVerification?.paymentIntentId\n        ? { paymentIntentId: event.paymentVerification.paymentIntentId }\n        : {}),\n      verifiedOnServer: Boolean(event.paymentVerification?.verifiedOnStorefrontServer || event.payment?.verifiedOnServer),\n    },\n    ...(event.sanitizedNotes ? { notes: event.sanitizedNotes } : {}),\n    coBrandingOptions: event.coBrandingOptions,\n    discountCad: event.discountCad,\n  };\n}\n\n/**\n * Reconciled default catalog aligning ljwellness-vs3 Storefront slugs with canonical StudioOS SKUs.\n * B2B is positioned as the flagship storefront face, while supporting multi-product Eczema & Menopause tracks.\n * Truthful launch posture: zero fake in-stock inventory until owner toggles real finished batches.\n */\nexport function buildDefaultAgreementCatalog(): StorefrontAgreementCatalog {\n  return {\n    schemaVersion: '1.0.0',\n    catalogVersion: 1,\n    updatedAt: new Date().toISOString(),\n    brandPositioning: {\n      primaryFace: 'b2b',\n      secondaryTracks: ['eczema', 'menopause'],\n      currency: 'CAD',\n      b2bPriorityNote:\n        'B2B Luxury Builders, Architects & Developers remain the primary storefront flagship. Eczema & Menopause lines scale as curated multi-product botanical collections.',\n      taxMode: 'estimated_canadian_provincial',\n    },\n    products: [\n      // === B2B FLAGSHIP CLOSING KITS ===\n      {\n        sku: 'LJW-B2B-RES-01',\n        storefrontSlug: 'residence-welcome',\n        variantKey: 'default',\n        track: 'b2b',\n        kind: 'kit',\n        nameEn: '01. The Residence Welcome',\n        nameFr: '01. Coffret Accueil R\u00E9sidence',\n        formatLabel: '4-pc Architect Box (8 oz candle + 6-cube melts + 50 ml balm + purity card)',\n        priceCad: 98,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 10,\n        cureReadyDate: null,\n        moq: 5,\n        unitCogsCad: 34,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-B2B-ARC-02',\n        storefrontSlug: 'architectural-sanctuary',\n        variantKey: 'default',\n        track: 'b2b',\n        kind: 'kit',\n        nameEn: '02. The Architectural Sanctuary',\n        nameFr: '02. Coffret Sanctuaire Architectural',\n        formatLabel: '5-pc Box (12 oz + 6 oz candles + oval tray + 12-cube melts + 100 ml balm + dossier)',\n        priceCad: 165,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 14,\n        cureReadyDate: null,\n        moq: 5,\n        unitCogsCad: 54,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-B2B-BES-03',\n        storefrontSlug: 'bespoke-estate',\n        variantKey: 'default',\n        track: 'b2b',\n        kind: 'kit',\n        nameEn: '03. The Bespoke Estate Box',\n        nameFr: '03. Malle Domaine Sur Mesure',\n        formatLabel: 'Multi-pc Trunk (3 candles + fluted tray/coasters + warmer + 18-cube melts + hand set)',\n        priceCad: 245,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 21,\n        cureReadyDate: null,\n        moq: 5,\n        unitCogsCad: 82,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-B2B-SMP-00',\n        storefrontSlug: 'studio-material-sample-box',\n        variantKey: 'default',\n        track: 'b2b',\n        kind: 'sample',\n        nameEn: 'Paid Studio Material Sample Box',\n        nameFr: 'Coffret \u00C9chantillon Mat\u00E9riaux Atelier',\n        formatLabel: 'Jesmonite disc + unscented votive + 600gsm card swatch + barrier balm ($55 credited @ 10+)',\n        priceCad: 55,\n        status: 'sample_only',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 19,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      // === B2B CO-BRANDING ADD-ONS ===\n      {\n        sku: 'LJW-B2B-ADD-LINEN',\n        storefrontSlug: 'monogram-linen-band',\n        variantKey: 'per-box',\n        track: 'b2b',\n        kind: 'addon',\n        nameEn: 'Monogrammed Linen Belly Band',\n        nameFr: 'Bandeau de Lin Monogramm\u00E9',\n        formatLabel: 'Per-box architectural linen belly band (+$6/box)',\n        priceCad: 6,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 5,\n        unitCogsCad: 1.8,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-B2B-ADD-CARD',\n        storefrontSlug: 'embossed-arch-card',\n        variantKey: 'per-box',\n        track: 'b2b',\n        kind: 'addon',\n        nameEn: 'Embossed Architectural Welcome Card',\n        nameFr: 'Carte d\u2019Accueil Architecturale Emboss\u00E9e',\n        formatLabel: '600gsm embossed developer/architect card (+$4/box)',\n        priceCad: 4,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 5,\n        unitCogsCad: 1.25,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-B2B-ADD-COLOR',\n        storefrontSlug: 'jesmonite-color-match',\n        variantKey: 'per-box',\n        track: 'b2b',\n        kind: 'addon',\n        nameEn: 'Jesmonite Vessel Color Match',\n        nameFr: 'Teinte Jesmonite Sur Mesure',\n        formatLabel: 'Custom mineral pigment match (+$12/box, $95 setup, MOQ 10)',\n        priceCad: 12,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 21,\n        cureReadyDate: null,\n        moq: 10,\n        unitCogsCad: 4.5,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-B2B-ADD-DOSSIER',\n        storefrontSlug: 'custom-estate-insert',\n        variantKey: 'per-box',\n        track: 'b2b',\n        kind: 'addon',\n        nameEn: 'Custom Residence Care Dossier',\n        nameFr: 'Dossier d\u2019Entretien R\u00E9sidence Personnalis\u00E9',\n        formatLabel: 'Printed home finish care insert & QR sheet (+$5/box)',\n        priceCad: 5,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 10,\n        cureReadyDate: null,\n        moq: 5,\n        unitCogsCad: 1.75,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-B2B-ADD-WHITEGLOVE',\n        storefrontSlug: 'priority-white-glove',\n        variantKey: 'per-box',\n        track: 'b2b',\n        kind: 'addon',\n        nameEn: 'Priority Closing-Date Staging',\n        nameFr: 'Coordination Prioritaire Date de Remise',\n        formatLabel: 'Scheduled handover staging per closing date (+$9/box)',\n        priceCad: 9,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 5,\n        cureReadyDate: null,\n        moq: 5,\n        unitCogsCad: 3,\n        deductsMaterials: false,\n        activeOnStorefront: true,\n      },\n\n      // === ECZEMA / SENSITIVE SKIN MULTI-PRODUCT LINE ===\n      {\n        sku: 'LJW-ECZ-BALM-050',\n        storefrontSlug: 'oat-borage-barrier-balm',\n        variantKey: '50ml',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Colloidal Oat & Borage Flare Barrier Balm (50 ml)',\n        nameFr: 'Baume Barri\u00E8re Avoine Collo\u00EFdale & Bourrache (50 ml)',\n        formatLabel: '50 ml Travel / Patch-Test Jar',\n        priceCad: 28,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 7.5,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-BALM-100',\n        storefrontSlug: 'oat-borage-barrier-balm',\n        variantKey: '100ml',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Colloidal Oat & Borage Flare Barrier Balm (100 ml)',\n        nameFr: 'Baume Barri\u00E8re Avoine Collo\u00EFdale & Bourrache (100 ml)',\n        formatLabel: '100 ml Full Studio Jar',\n        priceCad: 48,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 12.2,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-BALM-200',\n        storefrontSlug: 'oat-borage-barrier-balm',\n        variantKey: '200ml',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Colloidal Oat & Borage Flare Barrier Balm (200 ml)',\n        nameFr: 'Baume Barri\u00E8re Avoine Collo\u00EFdale & Bourrache (200 ml)',\n        formatLabel: '200 ml Family Refill Jar',\n        priceCad: 82,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 20.5,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-WASH-250',\n        storefrontSlug: 'amino-lipid-gentle-wash',\n        variantKey: '250ml',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Fragrance-Free Oat Amino Calm Wash (250 ml)',\n        nameFr: 'Nettoyant Doux Avoine & Acides Amin\u00E9s Sans Parfum (250 ml)',\n        formatLabel: '250 ml Amber Glass Pump',\n        priceCad: 34,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 9.2,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-WASH-500',\n        storefrontSlug: 'amino-lipid-gentle-wash',\n        variantKey: '500ml',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Fragrance-Free Oat Amino Calm Wash (500 ml)',\n        nameFr: 'Nettoyant Doux Avoine & Acides Amin\u00E9s Sans Parfum (500 ml)',\n        formatLabel: '500 ml Studio Refill Bottle',\n        priceCad: 58,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 15.8,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-STICK-01',\n        storefrontSlug: 'pocket-crease-flare-stick',\n        variantKey: 'single',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Pocket Hand & Crease Shield Stick (Single)',\n        nameFr: 'B\u00E2ton Protecteur Mains & Plis Cutan\u00E9s (Unit\u00E9)',\n        formatLabel: 'Single 30 g Pocket Stick',\n        priceCad: 26,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 5,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 6.4,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-STICK-02',\n        storefrontSlug: 'pocket-crease-flare-stick',\n        variantKey: 'duo',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Pocket Hand & Crease Shield Stick (2-Pack Duo)',\n        nameFr: 'B\u00E2ton Protecteur Mains & Plis Cutan\u00E9s (Duo)',\n        formatLabel: '2-Pack Desk & Bag Duo',\n        priceCad: 46,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 5,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 12.1,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-MIST-100',\n        storefrontSlug: 'microbiome-recovery-mist',\n        variantKey: '100ml-waitlist',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Post-Flare Colloidal Hydro-Calm Mist',\n        nameFr: 'Brume Apaisante Post-Crise Avoine Collo\u00EFdale',\n        formatLabel: '100 ml First-Batch Reservation',\n        priceCad: 36,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 14,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 8.8,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-SOAK-400',\n        storefrontSlug: 'unscented-bath-soak',\n        variantKey: '400g-waitlist',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Silky Colloidal Oat & Marshmallow Bath Soak',\n        nameFr: 'Bain Apaisant Avoine Collo\u00EFdale & Guimauve',\n        formatLabel: '400 g Pouch First-Batch Reservation',\n        priceCad: 32,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 7.4,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-MELT-12',\n        storefrontSlug: 'home-air-safe-melt-set',\n        variantKey: '12-cube-waitlist',\n        track: 'eczema',\n        kind: 'product',\n        nameEn: 'Sanctuary Bedroom Unscented Botanical Melts',\n        nameFr: 'Fondants Botaniques Sans Parfum Chambre Sanctuaire',\n        formatLabel: '12-cube set',\n        priceCad: 28,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 10,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 6.9,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-BND-TRIO',\n        storefrontSlug: 'calm-barrier-trio',\n        variantKey: 'bundle',\n        track: 'eczema',\n        kind: 'bundle',\n        nameEn: 'The Complete Calm Barrier Trio',\n        nameFr: 'Trio Barri\u00E8re Apaisante Complet',\n        formatLabel: '250 ml wash + 100 ml balm + 30 g stick',\n        priceCad: 96,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 27.8,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-BND-DAILY',\n        storefrontSlug: 'daily-reactive-cleanse',\n        variantKey: 'bundle',\n        track: 'eczema',\n        kind: 'bundle',\n        nameEn: 'Daily Reactive Wash & Balm Pair',\n        nameFr: 'Duo Quotidien Peau R\u00E9active',\n        formatLabel: '250 ml wash + 100 ml balm',\n        priceCad: 74,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 21.4,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-ECZ-BND-TRAVEL',\n        storefrontSlug: 'travel-flare-shield',\n        variantKey: 'bundle',\n        track: 'eczema',\n        kind: 'bundle',\n        nameEn: 'Pocket Flare Shield & Mini Balm Duo',\n        nameFr: 'Duo Nomade Bouclier & Mini Baume',\n        formatLabel: '30 g stick + 50 ml balm',\n        priceCad: 48,\n        status: 'preorder',\n        stockAvailable: 0,\n        cureLeadDays: 7,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 13.9,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n\n      // === MENOPAUSE / SAY IT PLAIN MULTI-PRODUCT LINE ===\n      {\n        sku: 'LJW-MEN-MIST-100',\n        storefrontSlug: 'peri-cooling-mist',\n        variantKey: '100ml',\n        track: 'menopause',\n        kind: 'product',\n        nameEn: 'Thermal Calm Mineral Facial & Neck Mist',\n        nameFr: 'Brume Min\u00E9rale Rafra\u00EEchissante Visage & Cou',\n        formatLabel: '100 ml (Sync Say It Plain price)',\n        priceCad: 0,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 14,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 0,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-MEN-CAND-10Z',\n        storefrontSlug: 'peri-night-candle',\n        variantKey: '10oz',\n        track: 'menopause',\n        kind: 'product',\n        nameEn: 'Restorative Dusk Unscented Jesmonite Candle',\n        nameFr: 'Bougie R\u00E9paratrice Cr\u00E9puscule Jesmonite Sans Parfum',\n        formatLabel: '10 oz Jesmonite vessel',\n        priceCad: 0,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 14,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 0,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-MEN-BALM-150',\n        storefrontSlug: 'meno-night-balm',\n        variantKey: '150ml',\n        track: 'menopause',\n        kind: 'product',\n        nameEn: 'Deep Moisture Lipid Renewal Body Butter',\n        nameFr: 'Beurre Corporel Renouvellement Lipidique Intense',\n        formatLabel: '150 ml rich butter jar',\n        priceCad: 0,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 14,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 0,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-MEN-MELT-12',\n        storefrontSlug: 'meno-wax-melts',\n        variantKey: '12-cube',\n        track: 'menopause',\n        kind: 'product',\n        nameEn: 'Sanctuary Unscented Clean Wax Melts',\n        nameFr: 'Fondants Purs Sans Parfum Sanctuaire',\n        formatLabel: '12-cube set',\n        priceCad: 0,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 10,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 0,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-MEN-ELIX-050',\n        storefrontSlug: 'post-barrier-elixir',\n        variantKey: '50ml',\n        track: 'menopause',\n        kind: 'product',\n        nameEn: 'Cellular Radiance Unscented Facial Elixir',\n        nameFr: '\u00C9lixir Facial \u00C9clat Cellulaire Sans Parfum',\n        formatLabel: '50 ml botanical facial oil',\n        priceCad: 0,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 14,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 0,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n      {\n        sku: 'LJW-MEN-DUO-01',\n        storefrontSlug: 'post-hearth-duo',\n        variantKey: 'duo',\n        track: 'menopause',\n        kind: 'bundle',\n        nameEn: 'Morning Stillness Vessel & Hand Ritual',\n        nameFr: 'Rituel Matinal Bougeoir & Soin des Mains',\n        formatLabel: 'Jesmonite candle + 100 ml hand balm',\n        priceCad: 0,\n        status: 'in_development',\n        stockAvailable: 0,\n        cureLeadDays: 14,\n        cureReadyDate: null,\n        moq: 1,\n        unitCogsCad: 0,\n        deductsMaterials: true,\n        activeOnStorefront: true,\n      },\n    ],\n  };\n}\n\n/**\n * Validates and normalizes an updated agreement catalog saved from StudioOS UI.\n */\nexport function normalizeAgreementCatalogInput(raw: unknown): {\n  valid: boolean;\n  catalog?: StorefrontAgreementCatalog;\n  error?: string;\n} {\n  if (!raw || typeof raw !== 'object') {\n    return { valid: false, error: 'Catalog payload must be an object.' };\n  }\n  const obj = raw as Record<string, any>;\n  if (!Array.isArray(obj.products)) {\n    return { valid: false, error: 'Catalog products array is required.' };\n  }\n\n  const allowedTracks: StorefrontTrack[] = ['b2b', 'eczema', 'menopause', 'purity'];\n  const allowedKinds: StorefrontSkuKind[] = ['kit', 'addon', 'sample', 'product', 'bundle'];\n  const allowedStatuses: StorefrontAvailabilityStatus[] = [\n    'preorder',\n    'sample_only',\n    'in_development',\n    'in_stock',\n    'sold_out',\n  ];\n\n  const seenSkus = new Set<string>();\n  const normalizedProducts: AgreedCatalogSku[] = [];\n\n  for (let i = 0; i < obj.products.length; i += 1) {\n    const item = obj.products[i] || {};\n    const sku = String(item.sku || '').trim().toUpperCase().slice(0, 64);\n    const storefrontSlug = String(item.storefrontSlug || '').trim().toLowerCase().slice(0, 100);\n    const variantKey = String(item.variantKey || 'default').trim().slice(0, 60);\n\n    if (!sku || !/^[A-Z0-9_-]{3,64}$/.test(sku)) {\n      return { valid: false, error: `Row ${i + 1}: SKU must be 3-64 alphanumeric/hyphen/underscore chars.` };\n    }\n    if (seenSkus.has(sku)) {\n      return { valid: false, error: `Duplicate SKU detected: ${sku}` };\n    }\n    seenSkus.add(sku);\n\n    if (!storefrontSlug || !/^[a-z0-9_-]{2,100}$/.test(storefrontSlug)) {\n      return { valid: false, error: `SKU ${sku}: storefrontSlug must be lowercase alphanumeric/hyphen.` };\n    }\n\n    const track: StorefrontTrack = allowedTracks.includes(item.track) ? item.track : 'b2b';\n    const kind: StorefrontSkuKind = allowedKinds.includes(item.kind) ? item.kind : 'product';\n    const status: StorefrontAvailabilityStatus = allowedStatuses.includes(item.status)\n      ? item.status\n      : 'in_development';\n\n    normalizedProducts.push({\n      sku,\n      storefrontSlug,\n      variantKey,\n      track,\n      kind,\n      nameEn: String(item.nameEn || sku).trim().slice(0, 200),\n      nameFr: String(item.nameFr || item.nameEn || sku).trim().slice(0, 200),\n      formatLabel: String(item.formatLabel || '').trim().slice(0, 240),\n      priceCad: Math.max(0, Number(Number(item.priceCad || 0).toFixed(2))),\n      status,\n      stockAvailable: Math.max(0, Math.round(Number(item.stockAvailable) || 0)),\n      cureLeadDays: Math.max(0, Math.min(365, Math.round(Number(item.cureLeadDays) || 0))),\n      cureReadyDate: item.cureReadyDate ? String(item.cureReadyDate).trim().slice(0, 40) : null,\n      moq: Math.max(1, Math.min(10000, Math.round(Number(item.moq) || 1))),\n      unitCogsCad: Math.max(0, Number(Number(item.unitCogsCad || 0).toFixed(2))),\n      deductsMaterials: Boolean(item.deductsMaterials ?? true),\n      activeOnStorefront: Boolean(item.activeOnStorefront ?? true),\n    });\n  }\n\n  const prevVersion = Math.max(1, Math.round(Number(obj.catalogVersion) || 1));\n\n  return {\n    valid: true,\n    catalog: {\n      schemaVersion: '1.0.0',\n      catalogVersion: prevVersion,\n      updatedAt: new Date().toISOString(),\n      brandPositioning: {\n        primaryFace: 'b2b',\n        secondaryTracks: ['eczema', 'menopause'],\n        currency: 'CAD',\n        b2bPriorityNote:\n          String(\n            obj.brandPositioning?.b2bPriorityNote ||\n              'B2B Luxury Builders, Architects & Developers remain the primary storefront flagship. Eczema & Menopause lines scale as curated multi-product botanical collections.',\n          ).slice(0, 500),\n        taxMode: 'estimated_canadian_provincial',\n      },\n      products: normalizedProducts,\n    },\n  };\n}\n", "/**\n * Shared unit normalization and unit-economics helpers for formulations,\n * batch inventory deduction, and COGS analysis.\n */\n\nconst MASS_TO_GRAMS: Record<string, number> = {\n  mg: 0.001,\n  milligram: 0.001,\n  milligrams: 0.001,\n  g: 1,\n  gram: 1,\n  grams: 1,\n  kg: 1000,\n  kilo: 1000,\n  kilos: 1000,\n  kilogram: 1000,\n  kilograms: 1000,\n  oz: 28.3495,\n  ounce: 28.3495,\n  ounces: 28.3495,\n  lb: 453.592,\n  lbs: 453.592,\n  pound: 453.592,\n  pounds: 453.592,\n};\n\nconst VOLUME_TO_ML: Record<string, number> = {\n  ml: 1,\n  milliliter: 1,\n  milliliters: 1,\n  millilitre: 1,\n  millilitres: 1,\n  l: 1000,\n  liter: 1000,\n  liters: 1000,\n  litre: 1000,\n  litres: 1000,\n  'fl oz': 29.5735,\n  floz: 29.5735,\n};\n\nexport function normalizeUnit(unit?: string): string {\n  return (unit || 'g').toLowerCase().trim();\n}\n\n/**\n * Converts a quantity from `fromUnit` into `toUnit`.\n * Supports mass conversions (mg/g/kg/oz/lb) and volume conversions (ml/L/fl oz).\n * Falls back to returning the original amount when units are identical or incompatible.\n */\nexport function convertUnit(amount: number, fromUnit?: string, toUnit?: string): number {\n  if (!Number.isFinite(amount)) return 0;\n  const from = normalizeUnit(fromUnit);\n  const to = normalizeUnit(toUnit);\n\n  if (from === to) return amount;\n\n  if (from in MASS_TO_GRAMS && to in MASS_TO_GRAMS) {\n    return (amount * MASS_TO_GRAMS[from]) / MASS_TO_GRAMS[to];\n  }\n\n  if (from in VOLUME_TO_ML && to in VOLUME_TO_ML) {\n    return (amount * VOLUME_TO_ML[from]) / VOLUME_TO_ML[to];\n  }\n\n  // Approximate 1:1 g <-> ml density fallback for cosmetic carrier oils/liquids\n  // when recipe uses g and inventory tracks L (or vice-versa).\n  if (from in MASS_TO_GRAMS && to in VOLUME_TO_ML) {\n    const grams = amount * MASS_TO_GRAMS[from];\n    return grams / VOLUME_TO_ML[to];\n  }\n  if (from in VOLUME_TO_ML && to in MASS_TO_GRAMS) {\n    const ml = amount * VOLUME_TO_ML[from];\n    return ml / MASS_TO_GRAMS[to];\n  }\n\n  return amount;\n}\n\nexport interface CostStructureBreakdown {\n  unitRawCost: number;\n  unitPackagingCost: number;\n  unitLaborCost: number;\n  unitOverheadCost: number;\n  totalUnitCogs: number;\n  shares: {\n    name: string;\n    value: number;\n    amount: number;\n    color: string;\n  }[];\n}\n\nexport function computeUnitCostStructure(params: {\n  batchRawCost: number;\n  estimatedYield: number;\n  packagingCostPerUnit: number;\n  hourlyLaborRate: number;\n  batchLaborHours?: number;\n  monthlyFixedOverhead: number;\n  estimatedMonthlyUnits: number;\n}): CostStructureBreakdown {\n  const safeYield = Math.max(1, params.estimatedYield || 1);\n  const batchLaborHours = params.batchLaborHours ?? 0.25;\n  const monthlyUnits = Math.max(1, params.estimatedMonthlyUnits || 1);\n\n  const unitRawCost = Number((params.batchRawCost / safeYield).toFixed(2));\n  const unitPackagingCost = Number(Math.max(0, params.packagingCostPerUnit).toFixed(2));\n  const unitLaborCost = Number(((Math.max(0, params.hourlyLaborRate) * batchLaborHours) / safeYield).toFixed(2));\n  const unitOverheadCost = Number((Math.max(0, params.monthlyFixedOverhead) / monthlyUnits).toFixed(2));\n  const totalUnitCogs = Number((unitRawCost + unitPackagingCost + unitLaborCost + unitOverheadCost).toFixed(2));\n\n  const denominator = totalUnitCogs > 0 ? totalUnitCogs : 1;\n  const pct = (val: number) => Number(((val / denominator) * 100).toFixed(1));\n\n  return {\n    unitRawCost,\n    unitPackagingCost,\n    unitLaborCost,\n    unitOverheadCost,\n    totalUnitCogs,\n    shares: [\n      { name: 'Raw Botanicals & Oils', value: pct(unitRawCost), amount: unitRawCost, color: '#D4AF37' },\n      { name: 'Luxury B2B Packaging', value: pct(unitPackagingCost), amount: unitPackagingCost, color: '#CD7F32' },\n      { name: `Artisan Labor ($${params.hourlyLaborRate}/hr)`, value: pct(unitLaborCost), amount: unitLaborCost, color: '#8B4513' },\n      { name: 'Allocated Studio Overhead', value: pct(unitOverheadCost), amount: unitOverheadCost, color: '#141414' },\n    ],\n  };\n}\n", "import type {\n  BusinessState,\n  Formulation,\n  IncomingOrderLineItem,\n  IncomingOrderQuote,\n  InventoryItem,\n  OrderEvaluationReport,\n  OrderLineEvaluation,\n  OrderMaterialShortfall,\n  SkuBomEntry,\n  SkuBomPackagingComponent,\n  SkuBomRawComponent,\n  StandardizedInventoryItem,\n  StudioPricingRules,\n} from '../types.js';\nimport {\n  buildDefaultAgreementCatalog,\n  computeCanadianTaxes,\n  type StorefrontAgreementCatalog,\n} from './storefrontBridge.js';\nimport { convertUnit, normalizeUnit } from './units.js';\n\nexport const STUDIO_PRICING_RULES: StudioPricingRules = {\n  currency: 'CAD',\n  b2bDepositPct: 50,\n  grossMarginFloorPct: 70,\n  customTargetMarginPct: 75,\n  hourlyLaborRateCad: 35,\n  defaultMinutesPerUnit: 8,\n  allocatedOverheadPerUnitCad: 3.5,\n  cardProcessingFeePct: 2.9,\n  packagingAndFulfillmentBufferDays: 3,\n  volumeTiers: [\n    {\n      id: 'tier-1-9',\n      label: '1\u20139 Units (Custom Single-Buyer / Sample)',\n      minUnits: 1,\n      maxUnits: 9,\n      discountPctOffBase: 0,\n      targetMarginPct: 75,\n      boxEdition: 'Custom Single-Buyer',\n    },\n    {\n      id: 'tier-10-24',\n      label: '10\u201324 Units (Boutique Builder Wholesale)',\n      minUnits: 10,\n      maxUnits: 24,\n      discountPctOffBase: 5,\n      targetMarginPct: 72,\n      boxEdition: 'Builder Wholesale Run',\n    },\n    {\n      id: 'tier-25-49',\n      label: '25\u201349 Units (Multi-Phase Builder Run)',\n      minUnits: 25,\n      maxUnits: 49,\n      discountPctOffBase: 10,\n      targetMarginPct: 70,\n      boxEdition: 'Builder Wholesale Run',\n    },\n    {\n      id: 'tier-50-plus',\n      label: '50+ Units (Uniform Condo / Rental QR Suite)',\n      minUnits: 50,\n      maxUnits: null,\n      discountPctOffBase: 15,\n      targetMarginPct: 70,\n      boxEdition: 'Uniform Development QR',\n    },\n  ],\n  cureWindowsDays: {\n    coldProcessSoap: 35,\n    stoneCastSoap: 56,\n    botanicalWaxMelts: 14,\n    serumsAndBalms: 5,\n    b2bClosingBoxes: 14,\n  },\n};\n\nexport interface CoBrandingAddonSpec {\n  slug: string;\n  label: string;\n  unitCostCad: number;\n  unitPriceCad: number;\n  setupFeeCad: number;\n  extraLeadDays: number;\n  rawComponents: SkuBomRawComponent[];\n  packagingComponents: SkuBomPackagingComponent[];\n}\n\nexport const CO_BRANDING_ADDONS: Record<string, CoBrandingAddonSpec> = {\n  'monogram-linen-band': {\n    slug: 'monogram-linen-band',\n    label: 'Monogrammed Linen Belly Band',\n    unitCostCad: 1.8,\n    unitPriceCad: 6,\n    setupFeeCad: 0,\n    extraLeadDays: 2,\n    rawComponents: [],\n    packagingComponents: [\n      { itemName: 'Monogrammed Linen Belly Band', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.8 },\n    ],\n  },\n  'embossed-arch-card': {\n    slug: 'embossed-arch-card',\n    label: 'Embossed 600gsm Architectural Card',\n    unitCostCad: 1.25,\n    unitPriceCad: 4,\n    setupFeeCad: 0,\n    extraLeadDays: 2,\n    rawComponents: [],\n    packagingComponents: [\n      { itemName: '600gsm Embossed Architectural Card', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.25 },\n    ],\n  },\n  'jesmonite-color-match': {\n    slug: 'jesmonite-color-match',\n    label: 'Jesmonite Vessel Color Match',\n    unitCostCad: 4.5,\n    unitPriceCad: 12,\n    setupFeeCad: 95,\n    extraLeadDays: 7,\n    rawComponents: [\n      { itemName: 'Custom Mineral Pigment Blend', amountPerUnit: 12, unit: 'g', estimatedCostPerBaseUnitCad: 180 },\n      { itemName: 'Jesmonite AC100 Stone Composite', amountPerUnit: 180, unit: 'g', estimatedCostPerBaseUnitCad: 14 },\n    ],\n    packagingComponents: [],\n  },\n  'custom-estate-insert': {\n    slug: 'custom-estate-insert',\n    label: 'Custom Residence Care Dossier & QR Insert',\n    unitCostCad: 1.75,\n    unitPriceCad: 5,\n    setupFeeCad: 0,\n    extraLeadDays: 2,\n    rawComponents: [],\n    packagingComponents: [\n      { itemName: 'Printed Home Finish Care Insert & QR Sheet', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.75 },\n    ],\n  },\n  'priority-white-glove': {\n    slug: 'priority-white-glove',\n    label: 'Priority Closing-Date White-Glove Staging',\n    unitCostCad: 3,\n    unitPriceCad: 9,\n    setupFeeCad: 0,\n    extraLeadDays: 0,\n    rawComponents: [],\n    packagingComponents: [],\n  },\n};\n\nfunction round2(value: number): number {\n  if (!Number.isFinite(value)) return 0;\n  return Number(value.toFixed(2));\n}\n\nfunction round4(value: number): number {\n  if (!Number.isFinite(value)) return 0;\n  return Number(value.toFixed(4));\n}\n\nfunction inferCategory(item: InventoryItem): 'materials' | 'packaging' | 'equipment' | 'other' {\n  if (item.category) return item.category;\n  const lower = item.item.toLowerCase();\n  if (/(box|tuckbox|binder|card|qr|label|bottle|dropper|jar|tube|pouch|ribbon|band|insert|vessel|lid)/.test(lower)) {\n    return 'packaging';\n  }\n  if (/(mold|mixer|scale|thermometer|cutter|equipment)/.test(lower)) {\n    return 'equipment';\n  }\n  return 'materials';\n}\n\nfunction inferNormalizedMetricForAmbiguousUnit(itemName: string): 'g' | 'ml' | 'pcs' {\n  const lower = itemName.toLowerCase();\n  if (/(box|tuckbox|binder|card|qr|label|bottle|dropper|jar|tube|pouch|ribbon|band|insert|lid|wick|stick)/.test(lower)) {\n    return 'pcs';\n  }\n  if (/(oil|squalane|serum|mist|water|brine|extract|wash|hydrosol|essence|tocopherol)/.test(lower)) {\n    return 'ml';\n  }\n  if (/(butter|salt|clay|wax|lye|naoh|hydroxide|starch|oat|jesmonite|pigment|powder|petal|resin)/.test(lower)) {\n    return 'g';\n  }\n  return 'pcs';\n}\n\n/**\n * Standardizes any studio inventory item into consistent g / ml / pcs metrics,\n * resolving ambiguous \"units\" strings and exposing costPerNormalizedUnit + reorderThreshold.\n */\nexport function standardizeInventoryItem(item: InventoryItem): StandardizedInventoryItem {\n  const originalUnit = (item.unit || 'pcs').trim();\n  const unitLower = normalizeUnit(originalUnit);\n  const category = inferCategory(item);\n  const originalStock = Math.max(0, Number(item.stock) || 0);\n  const costPerOriginalUnit = Math.max(0, Number(item.costPerUnit) || 0);\n  const rawThreshold = Number(item.minLevel ?? item.minStock ?? 0);\n\n  let normalizedUnit: 'g' | 'ml' | 'pcs' = 'pcs';\n  let normalizedStock = originalStock;\n  let costPerNormalizedUnit = costPerOriginalUnit;\n  let normalizedThreshold = rawThreshold;\n  let wasAmbiguousUnitNormalized = false;\n\n  if (['mg', 'milligram', 'milligrams', 'g', 'gram', 'grams', 'kg', 'kilo', 'kilos', 'kilogram', 'kilograms', 'oz', 'ounce', 'ounces', 'lb', 'lbs', 'pound', 'pounds'].includes(unitLower)) {\n    normalizedUnit = 'g';\n    normalizedStock = round2(convertUnit(originalStock, unitLower, 'g'));\n    normalizedThreshold = round2(convertUnit(rawThreshold > 0 ? rawThreshold : 500, rawThreshold > 0 ? unitLower : 'g', 'g'));\n    const gramsPerOrig = convertUnit(1, unitLower, 'g') || 1;\n    costPerNormalizedUnit = round4(costPerOriginalUnit / gramsPerOrig);\n  } else if (['ml', 'milliliter', 'milliliters', 'millilitre', 'millilitres', 'l', 'liter', 'liters', 'litre', 'litres', 'fl oz', 'floz'].includes(unitLower)) {\n    normalizedUnit = 'ml';\n    normalizedStock = round2(convertUnit(originalStock, unitLower, 'ml'));\n    normalizedThreshold = round2(convertUnit(rawThreshold > 0 ? rawThreshold : 250, rawThreshold > 0 ? unitLower : 'ml', 'ml'));\n    const mlPerOrig = convertUnit(1, unitLower, 'ml') || 1;\n    costPerNormalizedUnit = round4(costPerOriginalUnit / mlPerOrig);\n  } else if (['unit', 'units', 'ea', 'each', ''].includes(unitLower)) {\n    wasAmbiguousUnitNormalized = true;\n    normalizedUnit = inferNormalizedMetricForAmbiguousUnit(item.item);\n    normalizedStock = round2(originalStock);\n    normalizedThreshold = rawThreshold > 0 ? rawThreshold : normalizedUnit === 'pcs' ? 50 : 500;\n    // Heuristic: if bulk cost was entered per kg/L while labeled \"units\" and stock >= 1000, adjust carefully only if > $1/g doesn't make sense\n    costPerNormalizedUnit = round4(costPerOriginalUnit);\n  } else {\n    normalizedUnit = 'pcs';\n    normalizedStock = round2(originalStock);\n    normalizedThreshold = rawThreshold > 0 ? rawThreshold : 50;\n    costPerNormalizedUnit = round4(costPerOriginalUnit);\n  }\n\n  return {\n    id: item.id,\n    item: item.item,\n    category,\n    originalStock,\n    originalUnit,\n    normalizedStock,\n    normalizedUnit,\n    costPerOriginalUnit,\n    costPerNormalizedUnit,\n    reorderThreshold: round2(normalizedThreshold),\n    lowStock: normalizedStock <= normalizedThreshold,\n    wasAmbiguousUnitNormalized,\n  };\n}\n\nexport function auditStudioInventory(inventory: InventoryItem[] = []): StandardizedInventoryItem[] {\n  return inventory.map(standardizeInventoryItem);\n}\n\n/**\n * Default BOM specifications mapped to Storefront Agreement SKUs + Studio Formulations.\n */\nconst DEFAULT_SKU_BOM_SPECS: Record<\n  string,\n  {\n    formulationHint: string;\n    finishedUnitWeight: string;\n    cureTimeDays: number;\n    packagingBom: SkuBomPackagingComponent[];\n    rawBom: SkuBomRawComponent[];\n  }\n> = {\n  'LJW-B2B-RES-01': {\n    formulationHint: 'Seasalt & Pacific Brine Bar',\n    finishedUnitWeight: '4-pc Closing Kit (220g candle + 60g melts + 50ml balm + card)',\n    cureTimeDays: 14,\n    packagingBom: [\n      { itemName: 'Architect Rigid Specimen Box', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 8.5 },\n      { itemName: 'Amber Apothecary Jar (50ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.1 },\n      { itemName: 'QR Portal & Purity Care Card', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.25 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.9 },\n    ],\n    rawBom: [\n      { itemName: 'Jesmonite AC100 Stone Composite', amountPerUnit: 220, unit: 'g', estimatedCostPerBaseUnitCad: 14 },\n      { itemName: 'Botanical Soy Wax', amountPerUnit: 280, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Organic Shea Butter', amountPerUnit: 35, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 15, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n      { itemName: 'Bulgarian Lavender Oil', amountPerUnit: 8, unit: 'ml', estimatedCostPerBaseUnitCad: 85 },\n    ],\n  },\n  'LJW-B2B-ARC-02': {\n    formulationHint: 'Seasalt & Pacific Brine Bar',\n    finishedUnitWeight: '5-pc Suite (2x candles + oval tray + 12 melts + 100ml balm + A3 dossier)',\n    cureTimeDays: 14,\n    packagingBom: [\n      { itemName: 'Architect Rigid Specimen Box', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 9.5 },\n      { itemName: 'Wholesale A3 Homeowner Binder', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 11 },\n      { itemName: 'Amber Apothecary Jar (100ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.6 },\n      { itemName: 'QR Portal & Purity Care Card', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.25 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.1 },\n    ],\n    rawBom: [\n      { itemName: 'Jesmonite AC100 Stone Composite', amountPerUnit: 520, unit: 'g', estimatedCostPerBaseUnitCad: 14 },\n      { itemName: 'Botanical Soy Wax', amountPerUnit: 520, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Organic Shea Butter', amountPerUnit: 65, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 35, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n      { itemName: 'Bulgarian Lavender Oil', amountPerUnit: 15, unit: 'ml', estimatedCostPerBaseUnitCad: 85 },\n    ],\n  },\n  'LJW-B2B-BES-03': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: 'Estate Trunk (3 candles + tray/coasters + warmer + 18 melts + hand set)',\n    cureTimeDays: 21,\n    packagingBom: [\n      { itemName: 'Bespoke Estate Linen Trunk Box', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 18 },\n      { itemName: 'Personalized Single-Buyer A3 Binder', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 16 },\n      { itemName: 'Amber Apothecary Bottle & Dropper', quantityPerUnit: 2, unit: 'pcs', estimatedUnitCostCad: 3.1 },\n      { itemName: 'QR Portal & Purity Care Card', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.5 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n    ],\n    rawBom: [\n      { itemName: 'Jesmonite AC100 Stone Composite', amountPerUnit: 850, unit: 'g', estimatedCostPerBaseUnitCad: 14 },\n      { itemName: 'Botanical Soy Wax', amountPerUnit: 780, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Organic Shea Butter', amountPerUnit: 140, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 80, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n      { itemName: 'Bulgarian Lavender Oil', amountPerUnit: 24, unit: 'ml', estimatedCostPerBaseUnitCad: 85 },\n    ],\n  },\n  'LJW-B2B-SMP-00': {\n    formulationHint: 'Midnight Lavender Soap',\n    finishedUnitWeight: 'Sample Specimen Kit (Jesmonite disc + votive + 600gsm swatch + 30ml balm)',\n    cureTimeDays: 7,\n    packagingBom: [\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n      { itemName: '600gsm Card Swatch & QR Sheet', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.25 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.7 },\n    ],\n    rawBom: [\n      { itemName: 'Jesmonite AC100 Stone Composite', amountPerUnit: 140, unit: 'g', estimatedCostPerBaseUnitCad: 14 },\n      { itemName: 'Botanical Soy Wax', amountPerUnit: 90, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Organic Shea Butter', amountPerUnit: 25, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n    ],\n  },\n  'LJW-ECZ-BALM-050': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: '50 ml Jar',\n    cureTimeDays: 7,\n    packagingBom: [\n      { itemName: 'Amber Apothecary Jar (50ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.1 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.65 },\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 35, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Colloidal Oat Flour', amountPerUnit: 8, unit: 'g', estimatedCostPerBaseUnitCad: 24 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 10, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-ECZ-BALM-100': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: '100 ml Studio Jar',\n    cureTimeDays: 7,\n    packagingBom: [\n      { itemName: 'Amber Apothecary Jar (100ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.6 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 70, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Colloidal Oat Flour', amountPerUnit: 15, unit: 'g', estimatedCostPerBaseUnitCad: 24 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 20, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-ECZ-BALM-200': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: '200 ml Family Refill Jar',\n    cureTimeDays: 7,\n    packagingBom: [\n      { itemName: 'Amber Apothecary Jar (200ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 3.4 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.85 },\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 140, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Colloidal Oat Flour', amountPerUnit: 30, unit: 'g', estimatedCostPerBaseUnitCad: 24 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 40, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-ECZ-WASH-250': {\n    formulationHint: 'Seasalt & Pacific Brine Bar',\n    finishedUnitWeight: '250 ml Amber Glass Pump',\n    cureTimeDays: 7,\n    packagingBom: [\n      { itemName: 'Amber Glass Pump Bottle (250ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.85 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n    ],\n    rawBom: [\n      { itemName: 'Colloidal Oat Flour', amountPerUnit: 25, unit: 'g', estimatedCostPerBaseUnitCad: 24 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 40, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-ECZ-WASH-500': {\n    formulationHint: 'Seasalt & Pacific Brine Bar',\n    finishedUnitWeight: '500 ml Refill Bottle',\n    cureTimeDays: 7,\n    packagingBom: [\n      { itemName: 'Amber Refill Bottle (500ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 3.5 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n    ],\n    rawBom: [\n      { itemName: 'Colloidal Oat Flour', amountPerUnit: 50, unit: 'g', estimatedCostPerBaseUnitCad: 24 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 80, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-ECZ-STICK-01': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: '30 g Pocket Stick',\n    cureTimeDays: 5,\n    packagingBom: [\n      { itemName: 'Eco Kraft Twist Tube (30g)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.35 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.5 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 22, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 6, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-ECZ-STICK-02': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: '2x 30 g Duo Pack',\n    cureTimeDays: 5,\n    packagingBom: [\n      { itemName: 'Eco Kraft Twist Tube (30g)', quantityPerUnit: 2, unit: 'pcs', estimatedUnitCostCad: 1.35 },\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 2, unit: 'pcs', estimatedUnitCostCad: 0.5 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 44, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 12, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-ECZ-MIST-100': {\n    formulationHint: 'Restorative Botanical Lipid Body Serum',\n    finishedUnitWeight: '100 ml Fine-Mist Bottle',\n    cureTimeDays: 14,\n    packagingBom: [\n      { itemName: 'Violet Glass Mist Bottle (100ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.95 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n    ],\n    rawBom: [\n      { itemName: 'Colloidal Oat Flour', amountPerUnit: 10, unit: 'g', estimatedCostPerBaseUnitCad: 24 },\n      { itemName: 'Plant-Derived Olive Squalane', amountPerUnit: 20, unit: 'ml', estimatedCostPerBaseUnitCad: 95 },\n    ],\n  },\n  'LJW-ECZ-BND-TRIO': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: '250 ml wash + 100 ml balm + 30 g stick',\n    cureTimeDays: 7,\n    packagingBom: [\n      { itemName: 'Amber Glass Pump Bottle (250ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.85 },\n      { itemName: 'Amber Apothecary Jar (100ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.6 },\n      { itemName: 'Eco Kraft Twist Tube (30g)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.35 },\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 3, unit: 'pcs', estimatedUnitCostCad: 0.65 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 92, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Colloidal Oat Flour', amountPerUnit: 40, unit: 'g', estimatedCostPerBaseUnitCad: 24 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 66, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-MEN-MIST-100': {\n    formulationHint: 'Restorative Botanical Lipid Body Serum',\n    finishedUnitWeight: '100 ml Cooling Mineral Mist',\n    cureTimeDays: 14,\n    packagingBom: [\n      { itemName: 'Violet Glass Mist Bottle (100ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.95 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n    ],\n    rawBom: [\n      { itemName: 'Plant-Derived Olive Squalane', amountPerUnit: 15, unit: 'ml', estimatedCostPerBaseUnitCad: 95 },\n      { itemName: 'Bulgarian Lavender Oil', amountPerUnit: 2, unit: 'ml', estimatedCostPerBaseUnitCad: 85 },\n    ],\n  },\n  'LJW-MEN-CAND-10Z': {\n    formulationHint: 'Midnight Lavender Soap',\n    finishedUnitWeight: '10 oz Unscented Jesmonite Candle',\n    cureTimeDays: 14,\n    packagingBom: [\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n    ],\n    rawBom: [\n      { itemName: 'Jesmonite AC100 Stone Composite', amountPerUnit: 260, unit: 'g', estimatedCostPerBaseUnitCad: 14 },\n      { itemName: 'Botanical Soy Wax', amountPerUnit: 285, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n    ],\n  },\n  'LJW-MEN-BALM-150': {\n    formulationHint: 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: '150 ml Body Butter Jar',\n    cureTimeDays: 14,\n    packagingBom: [\n      { itemName: 'Amber Apothecary Jar (150ml)', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 2.95 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 105, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 30, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  },\n  'LJW-MEN-ELIX-050': {\n    formulationHint: 'Restorative Botanical Lipid Body Serum',\n    finishedUnitWeight: '50 ml Violet Dropper Bottle',\n    cureTimeDays: 14,\n    packagingBom: [\n      { itemName: 'Amber Apothecary Bottle & Dropper', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 3.1 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n    ],\n    rawBom: [\n      { itemName: 'Plant-Derived Olive Squalane', amountPerUnit: 28, unit: 'ml', estimatedCostPerBaseUnitCad: 95 },\n      { itemName: 'Organic Rosehip Seed Oil (Cold-Pressed)', amountPerUnit: 15, unit: 'ml', estimatedCostPerBaseUnitCad: 88 },\n    ],\n  },\n};\n\nfunction findBestFormulationMatch(\n  formulations: Formulation[],\n  hint: string,\n  sku: string,\n): Formulation | undefined {\n  if (!formulations.length) return undefined;\n  const h = hint.toLowerCase();\n  const s = sku.toLowerCase();\n  return (\n    formulations.find((f) => f.name.toLowerCase().includes(h) || h.includes(f.name.toLowerCase())) ||\n    formulations.find((f) => {\n      const fn = f.name.toLowerCase();\n      if (s.includes('serum') || s.includes('elix') || s.includes('mist')) return fn.includes('serum');\n      if (s.includes('balm') || s.includes('butter') || s.includes('stick')) return fn.includes('butter');\n      if (s.includes('soap') || s.includes('bar') || s.includes('wash')) return fn.includes('seasalt') || fn.includes('lavender');\n      return false;\n    })\n  );\n}\n\n/**\n * Builds Lookup Table #1: Catalog SKU -> Formulation & Packaging BOM Map.\n */\nexport function buildSkuBomCatalog(\n  catalog?: StorefrontAgreementCatalog,\n  formulations: Formulation[] = [],\n): SkuBomEntry[] {\n  const effectiveCatalog = catalog && Array.isArray(catalog.products) && catalog.products.length > 0\n    ? catalog\n    : buildDefaultAgreementCatalog();\n\n  return effectiveCatalog.products.map((p) => {\n    const spec = DEFAULT_SKU_BOM_SPECS[p.sku];\n    const matchedFormulation = findBestFormulationMatch(\n      formulations,\n      spec?.formulationHint || p.nameEn,\n      p.sku,\n    );\n\n    const packagingBom: SkuBomPackagingComponent[] =\n      spec?.packagingBom ||\n      (p.kind === 'addon'\n        ? CO_BRANDING_ADDONS[p.storefrontSlug]?.packagingComponents || [\n            { itemName: p.nameEn, quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: p.unitCogsCad || 1.5 },\n          ]\n        : [\n            { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n            { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.75 },\n          ]);\n\n    const rawBom: SkuBomRawComponent[] =\n      spec?.rawBom ||\n      (p.kind === 'addon'\n        ? CO_BRANDING_ADDONS[p.storefrontSlug]?.rawComponents || []\n        : [\n            { itemName: 'Organic Shea Butter', amountPerUnit: 60, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n            { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 25, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n          ]);\n\n    return {\n      sku: p.sku,\n      storefrontSlug: p.storefrontSlug,\n      variantKey: p.variantKey,\n      track: p.track,\n      productName: p.nameEn,\n      ...(matchedFormulation ? { formulationId: matchedFormulation.id } : {}),\n      formulationName: matchedFormulation?.name || spec?.formulationHint || p.nameEn,\n      finishedUnitWeight: spec?.finishedUnitWeight || p.formatLabel || 'Standard Studio Unit',\n      cureTimeDays: Math.max(spec?.cureTimeDays ?? 0, p.cureLeadDays || 0, matchedFormulation?.curingTimeDays ?? 0),\n      defaultUnitPriceCad: p.priceCad,\n      packagingBom,\n      rawBom,\n    };\n  });\n}\n\nfunction findMatchingInventory(\n  targetName: string,\n  standardizedInventory: StandardizedInventoryItem[],\n): StandardizedInventoryItem | undefined {\n  const needle = targetName.toLowerCase().replace(/[^a-z0-9\\s]/g, ' ').trim();\n  if (!needle) return undefined;\n\n  const exact = standardizedInventory.find((i) => i.item.toLowerCase().trim() === targetName.toLowerCase().trim());\n  if (exact) return exact;\n\n  const contains = standardizedInventory.find((i) => {\n    const hay = i.item.toLowerCase().replace(/[^a-z0-9\\s]/g, ' ').trim();\n    return hay.includes(needle) || needle.includes(hay);\n  });\n  if (contains) return contains;\n\n  // Token overlap matching (e.g., \"Shea Butter\" matches \"Organic Shea Butter\")\n  const needleWords = needle.split(/\\s+/).filter((w) => w.length >= 4 && !['organic', 'pure', 'cold', 'pressed', 'raw', 'dried', 'extra', 'virgin'].includes(w));\n  if (needleWords.length === 0) return undefined;\n\n  return standardizedInventory.find((i) => {\n    const hay = i.item.toLowerCase();\n    return needleWords.every((w) => hay.includes(w));\n  });\n}\n\nfunction computeBaseCostCadForComponent(\n  amountInComponentUnit: number,\n  componentUnit: 'g' | 'ml' | 'pcs',\n  estimatedCostPerBaseUnitCad: number,\n  invMatch?: StandardizedInventoryItem,\n): number {\n  if (invMatch && invMatch.costPerNormalizedUnit > 0) {\n    const qtyInInvUnit =\n      componentUnit === invMatch.normalizedUnit\n        ? amountInComponentUnit\n        : convertUnit(amountInComponentUnit, componentUnit, invMatch.normalizedUnit);\n    return qtyInInvUnit * invMatch.costPerNormalizedUnit;\n  }\n  if (componentUnit === 'pcs') {\n    return amountInComponentUnit * estimatedCostPerBaseUnitCad;\n  }\n  // Base estimatedCostPerBaseUnitCad is per kg or L (1000 g/ml)\n  return (amountInComponentUnit / 1000) * estimatedCostPerBaseUnitCad;\n}\n\nexport interface CollectionAndFormulationCogsSummary {\n  formulations: Array<{\n    id: string;\n    name: string;\n    curingTimeDays: number;\n    batchSize: number;\n    batchUnit: string;\n    estimatedBatchRawCostCad: number;\n    estimatedUnitRawCostCad: number;\n  }>;\n  skus: Array<{\n    sku: string;\n    track: string;\n    name: string;\n    cureTimeDays: number;\n    unitRawCostCad: number;\n    unitPackagingCostCad: number;\n    unitLaborOverheadCad: number;\n    unitTotalCogsCad: number;\n    priceCad: number;\n    recommendedPrice70PctCad: number;\n    grossMarginPct: number;\n    b2b50PctDepositPerUnitCad: number;\n  }>;\n  collections: Array<{\n    collectionName: string;\n    productName: string;\n    priceCad: number;\n    stock: number;\n    estimatedCogsCad: number;\n    grossMarginPct: number;\n  }>;\n}\n\nexport function evaluateCollectionAndFormulationCogs(\n  state?: Partial<BusinessState> | null,\n  agreedCatalog?: StorefrontAgreementCatalog,\n): CollectionAndFormulationCogsSummary {\n  const stdInventory = auditStudioInventory(state?.inventory || []);\n  const formulations = state?.formulations || [];\n  const bomList = buildSkuBomCatalog(agreedCatalog, formulations);\n  const laborPerUnit = round2(\n    (STUDIO_PRICING_RULES.hourlyLaborRateCad * (STUDIO_PRICING_RULES.defaultMinutesPerUnit / 60)) +\n      STUDIO_PRICING_RULES.allocatedOverheadPerUnitCad,\n  );\n\n  const formulationRows = formulations.map((f) => {\n    let rawCost = 0;\n    for (const ing of f.ingredients || []) {\n      const inv = stdInventory.find((i) => i.id === ing.inventoryId) || findMatchingInventory(ing.name, stdInventory);\n      if (inv && inv.costPerNormalizedUnit > 0) {\n        const qtyNorm = convertUnit(Number(ing.amount) || 0, ing.unit || 'g', inv.normalizedUnit);\n        rawCost += qtyNorm * inv.costPerNormalizedUnit;\n      } else {\n        // Fallback botanical cost $18/kg\n        const grams = convertUnit(Number(ing.amount) || 0, ing.unit || 'g', 'g');\n        rawCost += (grams / 1000) * 18;\n      }\n    }\n    const yieldUnits = Math.max(1, f.batchUnit === 'g' || f.batchUnit === 'ml' ? Math.round((f.batchSize || 1000) / 100) : f.batchSize || 10);\n    return {\n      id: f.id,\n      name: f.name,\n      curingTimeDays: f.curingTimeDays || 0,\n      batchSize: f.batchSize || 0,\n      batchUnit: f.batchUnit || 'g',\n      estimatedBatchRawCostCad: round2(rawCost),\n      estimatedUnitRawCostCad: round2(rawCost / yieldUnits),\n    };\n  });\n\n  const skuRows = bomList.map((bom) => {\n    const rawCost = bom.rawBom.reduce((sum, r) => {\n      const inv = findMatchingInventory(r.itemName, stdInventory);\n      return sum + computeBaseCostCadForComponent(r.amountPerUnit, r.unit, r.estimatedCostPerBaseUnitCad, inv);\n    }, 0);\n    const pkgCost = bom.packagingBom.reduce((sum, pk) => {\n      const inv = findMatchingInventory(pk.itemName, stdInventory);\n      const unitCost = inv && inv.costPerNormalizedUnit > 0 ? inv.costPerNormalizedUnit : pk.estimatedUnitCostCad;\n      return sum + unitCost * pk.quantityPerUnit;\n    }, 0);\n\n    const totalCogs = round2(rawCost + pkgCost + laborPerUnit);\n    const floorPrice = round2(totalCogs / (1 - STUDIO_PRICING_RULES.grossMarginFloorPct / 100));\n    const effectivePrice = bom.defaultUnitPriceCad > 0 ? bom.defaultUnitPriceCad : floorPrice;\n    const marginPct = effectivePrice > 0 ? round2(((effectivePrice - totalCogs) / effectivePrice) * 100) : 0;\n\n    return {\n      sku: bom.sku,\n      track: bom.track,\n      name: bom.productName,\n      cureTimeDays: bom.cureTimeDays,\n      unitRawCostCad: round2(rawCost),\n      unitPackagingCostCad: round2(pkgCost),\n      unitLaborOverheadCad: laborPerUnit,\n      unitTotalCogsCad: totalCogs,\n      priceCad: effectivePrice,\n      recommendedPrice70PctCad: floorPrice,\n      grossMarginPct: marginPct,\n      b2b50PctDepositPerUnitCad: round2(effectivePrice * 0.5),\n    };\n  });\n\n  const collectionRows: CollectionAndFormulationCogsSummary['collections'] = [];\n  for (const col of state?.collections || []) {\n    for (const prod of col.products || []) {\n      const estCogs = round2(Math.max(4.2, prod.price * 0.25));\n      const margin = prod.price > 0 ? round2(((prod.price - estCogs) / prod.price) * 100) : 0;\n      collectionRows.push({\n        collectionName: col.name,\n        productName: prod.name,\n        priceCad: prod.price,\n        stock: prod.stock,\n        estimatedCogsCad: estCogs,\n        grossMarginPct: margin,\n      });\n    }\n  }\n\n  return {\n    formulations: formulationRows,\n    skus: skuRows,\n    collections: collectionRows,\n  };\n}\n\nfunction matchBomEntry(\n  line: IncomingOrderLineItem,\n  bomCatalog: SkuBomEntry[],\n): SkuBomEntry {\n  const skuUpper = (line.sku || '').trim().toUpperCase();\n  const slugLower = (line.storefrontSlug || '').trim().toLowerCase();\n  const variantLower = (line.variantKey || '').trim().toLowerCase();\n  const nameLower = (line.productName || '').trim().toLowerCase();\n\n  const match =\n    bomCatalog.find((b) => skuUpper && b.sku === skuUpper) ||\n    bomCatalog.find(\n      (b) =>\n        slugLower &&\n        b.storefrontSlug === slugLower &&\n        (!variantLower || b.variantKey.toLowerCase() === variantLower),\n    ) ||\n    bomCatalog.find((b) => slugLower && b.storefrontSlug === slugLower) ||\n    bomCatalog.find(\n      (b) =>\n        nameLower &&\n        (b.productName.toLowerCase().includes(nameLower) || nameLower.includes(b.productName.toLowerCase())),\n    );\n\n  if (match) return match;\n\n  // Fallback synthetic BOM for bespoke/custom SKUs\n  const isSoap = /soap|bar|monolith|stone/i.test(line.productName || '');\n  const isMelt = /melt|candle|wax/i.test(line.productName || '');\n  return {\n    sku: skuUpper || 'LJW-CUSTOM-01',\n    storefrontSlug: slugLower || 'custom-studio-product',\n    variantKey: variantLower || 'default',\n    track: /b2b|closing|estate|residence|sanctuary|architect/i.test(line.productName || '') ? 'b2b' : 'eczema',\n    productName: line.productName || line.sku || 'Custom Studio Formulation',\n    formulationName: isSoap ? 'Seasalt & Pacific Brine Bar' : isMelt ? 'Botanical Soy Wax Blend' : 'Whipped Kokum & Nilotica Body Butter',\n    finishedUnitWeight: isSoap ? '120 g Bar' : '100 ml Studio Unit',\n    cureTimeDays: isSoap ? STUDIO_PRICING_RULES.cureWindowsDays.coldProcessSoap : isMelt ? 14 : 7,\n    defaultUnitPriceCad: line.unitPrice || 48,\n    packagingBom: [\n      { itemName: 'Gold-Foil Hotstamp Tuckboxes', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 1.4 },\n      { itemName: 'Bilingual Loi 96 Label Set', quantityPerUnit: 1, unit: 'pcs', estimatedUnitCostCad: 0.8 },\n    ],\n    rawBom: [\n      { itemName: 'Organic Shea Butter', amountPerUnit: 65, unit: 'g', estimatedCostPerBaseUnitCad: 12 },\n      { itemName: 'Cold-Pressed Coconut Oil', amountPerUnit: 25, unit: 'ml', estimatedCostPerBaseUnitCad: 6.5 },\n    ],\n  };\n}\n\nfunction parseDeliveryDate(timeline?: IncomingOrderQuote['timeline'], now: Date = new Date()): string | undefined {\n  if (timeline?.requestedDeliveryDate && /^\\d{4}-\\d{2}-\\d{2}/.test(timeline.requestedDeliveryDate)) {\n    return timeline.requestedDeliveryDate.slice(0, 10);\n  }\n  const windowStr = (timeline?.targetDeliveryWindow || '').toLowerCase();\n  const daysMatch = windowStr.match(/next\\s+(\\d+)\\s+days?/);\n  if (daysMatch) {\n    const target = new Date(now.getTime() + Number(daysMatch[1]) * 86400000);\n    return target.toISOString().split('T')[0];\n  }\n  return undefined;\n}\n\nfunction resolveSuggestedVendor(itemName: string, category: 'materials' | 'packaging' | 'equipment' | 'other', state?: Partial<BusinessState> | null): { vendor: string; leadDays: number } {\n  const vendors = state?.sourcing?.vendors || [];\n  if (category === 'packaging') {\n    const pkgVendor = vendors.find((v) => v.category === 'Packaging') || vendors[0];\n    return {\n      vendor: pkgVendor?.name || 'Sustained Woods & Containers',\n      leadDays: 5,\n    };\n  }\n  const rawVendor = vendors.find((v) => v.category === 'Raw Materials') || vendors[0];\n  const isCustomPigment = /pigment|jesmonite/i.test(itemName);\n  return {\n    vendor: rawVendor?.name || 'Botanical Imports Co',\n    leadDays: isCustomPigment ? 10 : 7,\n  };\n}\n\n/**\n * Full deterministic Arty office/production/COGS evaluation engine.\n * Never sends external communications and never mutates inventory/ledger directly.\n */\nexport function evaluateIncomingOrderOrQuote(\n  order: IncomingOrderQuote,\n  state?: Partial<BusinessState> | null,\n  agreedCatalog?: StorefrontAgreementCatalog,\n  now: Date = new Date(),\n): OrderEvaluationReport {\n  const effectiveCatalog = agreedCatalog || buildDefaultAgreementCatalog();\n  const formulations = state?.formulations || [];\n  const stdInventory = auditStudioInventory(state?.inventory || []);\n  const bomCatalog = buildSkuBomCatalog(effectiveCatalog, formulations);\n  const coBrandingOptions: string[] = Array.isArray((order as any).coBrandingOptions)\n    ? (order as any).coBrandingOptions\n    : [];\n\n  const laborOverheadPerUnit = round2(\n    STUDIO_PRICING_RULES.hourlyLaborRateCad * (STUDIO_PRICING_RULES.defaultMinutesPerUnit / 60) +\n      STUDIO_PRICING_RULES.allocatedOverheadPerUnitCad,\n  );\n\n  // Build available finished stock pool per SKU/product from agreedCatalog & collections (respecting staging truthfulness)\n  const finishedStockBySku = new Map<string, number>();\n  for (const skuItem of effectiveCatalog.products) {\n    finishedStockBySku.set(skuItem.sku, Math.max(0, Number(skuItem.stockAvailable) || 0));\n  }\n  for (const col of state?.collections || []) {\n    for (const prod of col.products || []) {\n      const prodSku = prod.sku ? prod.sku.trim().toUpperCase() : '';\n      const matchedBom = bomCatalog.find(\n        (b) =>\n          (prodSku && b.sku === prodSku) ||\n          b.productName.toLowerCase().includes(prod.name.toLowerCase()) ||\n          prod.name.toLowerCase().includes(b.productName.toLowerCase()),\n      );\n      if (matchedBom) {\n        const cur = finishedStockBySku.get(matchedBom.sku) || 0;\n        if (cur === 0 && prod.stock > 0) {\n          finishedStockBySku.set(matchedBom.sku, prod.stock);\n        }\n      }\n    }\n  }\n\n  // Track aggregated material demand only for units that actually must be poured/formulated + packaging for all units\n  const demandMap = new Map<\n    string,\n    {\n      itemName: string;\n      category: 'materials' | 'packaging' | 'equipment' | 'other';\n      requiredQty: number;\n      unit: 'g' | 'ml' | 'pcs';\n      estCostPerBaseUnitCad: number;\n    }\n  >();\n\n  const addDemand = (\n    itemName: string,\n    category: 'materials' | 'packaging' | 'equipment' | 'other',\n    qty: number,\n    unit: 'g' | 'ml' | 'pcs',\n    estCostPerBaseUnitCad: number,\n  ) => {\n    if (qty <= 0) return;\n    const key = `${itemName.toLowerCase()}__${unit}`;\n    const prev = demandMap.get(key);\n    if (prev) {\n      prev.requiredQty = round2(prev.requiredQty + qty);\n    } else {\n      demandMap.set(key, {\n        itemName,\n        category,\n        requiredQty: round2(qty),\n        unit,\n        estCostPerBaseUnitCad,\n      });\n    }\n  };\n\n  let totalUnits = 0;\n  let totalFinishedStockAvailable = 0;\n  let totalUnitsToProduce = 0;\n  let totalCogsCad = 0;\n  let directMaterialsAndPackagingCogsCad = 0;\n  let coBrandingAddOnsCostCad = 0;\n  let customPigmentSetupFeeCad = 0;\n  let quotedSubtotalCad = 0;\n  let recommendedSubtotalCad = 0;\n  let maxCureTimeDays = 0;\n\n  // Check co-branding options once for setup fee & extra days\n  let addonUnitCostPerKit = 0;\n  let addonUnitPricePerKit = 0;\n  let addonExtraDays = 0;\n  for (const slug of coBrandingOptions) {\n    const addon = CO_BRANDING_ADDONS[slug];\n    if (addon) {\n      addonUnitCostPerKit += addon.unitCostCad;\n      addonUnitPricePerKit += addon.unitPriceCad;\n      if (addon.setupFeeCad > 0) {\n        customPigmentSetupFeeCad = round2(customPigmentSetupFeeCad + addon.setupFeeCad);\n      }\n      addonExtraDays = Math.max(addonExtraDays, addon.extraLeadDays);\n    }\n  }\n\n  const lineEvaluations: OrderLineEvaluation[] = (order.lineItems || []).map((li) => {\n    const qty = Math.max(1, Math.round(Number(li.quantity) || 1));\n    const bom = matchBomEntry(li, bomCatalog);\n    const invStock = Math.max(0, finishedStockBySku.get(bom.sku) || 0);\n    const availableNow = Math.min(qty, invStock);\n    finishedStockBySku.set(bom.sku, Math.max(0, invStock - availableNow));\n    const unitsToProduce = Math.max(0, qty - availableNow);\n\n    // Raw & Packaging costs per unit\n    let unitRawCost = 0;\n    for (const r of bom.rawBom) {\n      const inv = findMatchingInventory(r.itemName, stdInventory);\n      unitRawCost += computeBaseCostCadForComponent(r.amountPerUnit, r.unit, r.estimatedCostPerBaseUnitCad, inv);\n      if (unitsToProduce > 0) {\n        addDemand(r.itemName, 'materials', r.amountPerUnit * unitsToProduce, r.unit, r.estimatedCostPerBaseUnitCad);\n      }\n    }\n\n    let unitPackagingCost = 0;\n    for (const pk of bom.packagingBom) {\n      const inv = findMatchingInventory(pk.itemName, stdInventory);\n      const unitCost = inv && inv.costPerNormalizedUnit > 0 ? inv.costPerNormalizedUnit : pk.estimatedUnitCostCad;\n      unitPackagingCost += unitCost * pk.quantityPerUnit;\n      addDemand(pk.itemName, 'packaging', pk.quantityPerUnit * qty, pk.unit, pk.estimatedUnitCostCad);\n    }\n\n    // Apply B2B co-branding add-ons on B2B kits\n    let unitCoBrandingCost = 0;\n    let unitCoBrandingPrice = 0;\n    if (bom.track === 'b2b' && !bom.sku.includes('ADD-') && coBrandingOptions.length > 0) {\n      unitCoBrandingCost = addonUnitCostPerKit;\n      unitCoBrandingPrice = addonUnitPricePerKit;\n      for (const slug of coBrandingOptions) {\n        const addon = CO_BRANDING_ADDONS[slug];\n        if (!addon) continue;\n        for (const r of addon.rawComponents) {\n          addDemand(r.itemName, 'materials', r.amountPerUnit * qty, r.unit, r.estimatedCostPerBaseUnitCad);\n        }\n        for (const pk of addon.packagingComponents) {\n          addDemand(pk.itemName, 'packaging', pk.quantityPerUnit * qty, pk.unit, pk.estimatedUnitCostCad);\n        }\n      }\n    }\n\n    const lineLaborOverhead = bom.sku.includes('ADD-') ? 0 : laborOverheadPerUnit;\n    const unitTotalCogs = round2(unitRawCost + unitPackagingCost + unitCoBrandingCost + lineLaborOverhead);\n    const lineTotalCogs = round2(unitTotalCogs * qty);\n    const lineDirectMaterialsAndPkg = round2((unitRawCost + unitPackagingCost + unitCoBrandingCost) * qty);\n\n    const floorPrice = round2(unitTotalCogs / (1 - STUDIO_PRICING_RULES.grossMarginFloorPct / 100));\n    const catalogOrProvidedPrice =\n      Number(li.unitPrice) > 0\n        ? Number(li.unitPrice)\n        : bom.defaultUnitPriceCad > 0\n          ? bom.defaultUnitPriceCad + unitCoBrandingPrice\n          : floorPrice;\n\n    const recommendedUnitPrice = round2(Math.max(floorPrice, catalogOrProvidedPrice));\n    const lineRevenue = round2(catalogOrProvidedPrice * qty);\n    const marginPct =\n      catalogOrProvidedPrice > 0\n        ? round2(((catalogOrProvidedPrice - unitTotalCogs) / catalogOrProvidedPrice) * 100)\n        : 0;\n\n    totalUnits += qty;\n    totalFinishedStockAvailable += availableNow;\n    totalUnitsToProduce += unitsToProduce;\n    totalCogsCad = round2(totalCogsCad + lineTotalCogs);\n    directMaterialsAndPackagingCogsCad = round2(directMaterialsAndPackagingCogsCad + lineDirectMaterialsAndPkg);\n    coBrandingAddOnsCostCad = round2(coBrandingAddOnsCostCad + unitCoBrandingCost * qty);\n    quotedSubtotalCad = round2(quotedSubtotalCad + lineRevenue);\n    recommendedSubtotalCad = round2(recommendedSubtotalCad + recommendedUnitPrice * qty);\n\n    const effectiveCureDays =\n      unitsToProduce > 0\n        ? bom.cureTimeDays + (bom.track === 'b2b' ? addonExtraDays : 0)\n        : 2; // Already cured finished stock only needs packing\n    if (effectiveCureDays > maxCureTimeDays) {\n      maxCureTimeDays = effectiveCureDays;\n    }\n\n    return {\n      sku: bom.sku,\n      productName: bom.productName,\n      track: bom.track,\n      quantity: qty,\n      finishedStockAvailable: availableNow,\n      unitsToProduce,\n      ...(bom.formulationId ? { formulationId: bom.formulationId } : {}),\n      formulationName: bom.formulationName,\n      finishedUnitWeight: bom.finishedUnitWeight,\n      cureTimeDays: bom.cureTimeDays,\n      unitRawCostCad: round2(unitRawCost),\n      unitPackagingCostCad: round2(unitPackagingCost),\n      unitCoBrandingCostCad: round2(unitCoBrandingCost),\n      unitLaborOverheadCad: lineLaborOverhead,\n      unitTotalCogsCad: unitTotalCogs,\n      lineTotalCogsCad: lineTotalCogs,\n      quotedUnitPriceCad: round2(catalogOrProvidedPrice),\n      recommendedUnitPriceCad: recommendedUnitPrice,\n      lineRevenueCad: lineRevenue,\n      grossMarginPct: marginPct,\n      meetsMarginFloor: marginPct >= STUDIO_PRICING_RULES.grossMarginFloorPct,\n    };\n  });\n\n  // Check inventory shortfalls against normalized inventory\n  const shortfalls: OrderMaterialShortfall[] = [];\n  let maxShortfallLeadDays = 0;\n  for (const reqItem of demandMap.values()) {\n    const invMatch = findMatchingInventory(reqItem.itemName, stdInventory);\n    let availableInReqUnit = 0;\n    if (invMatch) {\n      availableInReqUnit =\n        invMatch.normalizedUnit === reqItem.unit\n          ? invMatch.normalizedStock\n          : round2(convertUnit(invMatch.normalizedStock, invMatch.normalizedUnit, reqItem.unit));\n    }\n\n    if (availableInReqUnit + 0.001 < reqItem.requiredQty) {\n      const shortfallQty = round2(reqItem.requiredQty - availableInReqUnit);\n      const reorderCost = round2(\n        computeBaseCostCadForComponent(\n          shortfallQty,\n          reqItem.unit,\n          reqItem.estCostPerBaseUnitCad,\n          invMatch,\n        ),\n      );\n      const vendorInfo = resolveSuggestedVendor(reqItem.itemName, reqItem.category, state);\n      maxShortfallLeadDays = Math.max(maxShortfallLeadDays, vendorInfo.leadDays);\n\n      shortfalls.push({\n        ...(invMatch ? { inventoryId: invMatch.id } : {}),\n        itemName: invMatch ? invMatch.item : reqItem.itemName,\n        category: reqItem.category,\n        requiredQty: reqItem.requiredQty,\n        availableQty: round2(availableInReqUnit),\n        shortfallQty,\n        unit: reqItem.unit,\n        estimatedReorderCostCad: reorderCost,\n        supplierLeadDays: vendorInfo.leadDays,\n        suggestedVendor: vendorInfo.vendor,\n      });\n    }\n  }\n\n  // Totals, discount, tax preview, margin & 50% B2B deposit check\n  const paymentSubtotal = Number(order.payment?.subtotal || 0);\n  const rawSubtotal = quotedSubtotalCad > 0 ? quotedSubtotalCad : paymentSubtotal;\n  const orderDiscountCad = Math.max(0, round2(Number((order as any).discountCad || 0)));\n  const netRevenueCad = round2(Math.max(0, rawSubtotal + customPigmentSetupFeeCad - orderDiscountCad));\n  const totalWithCogsSetup = round2(totalCogsCad);\n  const estimatedGrossProfitCad = round2(netRevenueCad - totalWithCogsSetup);\n  const grossMarginPct = netRevenueCad > 0 ? round2((estimatedGrossProfitCad / netRevenueCad) * 100) : 0;\n  const meetsMarginFloor = grossMarginPct >= STUDIO_PRICING_RULES.grossMarginFloorPct;\n\n  const isB2B =\n    order.client?.accountType !== 'Retail' ||\n    lineEvaluations.some((l) => l.track === 'b2b');\n  const depositPct = isB2B ? STUDIO_PRICING_RULES.b2bDepositPct : 100;\n  const b2bDepositRequiredCad = round2(\n    (Math.max(0, rawSubtotal - orderDiscountCad) * (depositPct / 100)) + customPigmentSetupFeeCad,\n  );\n  const b2bBalanceDueCad = round2(Math.max(0, netRevenueCad - b2bDepositRequiredCad));\n  const b2bDepositCoversDirectCogs = b2bDepositRequiredCad >= directMaterialsAndPackagingCogsCad;\n  const depositCashFlowGapCad = b2bDepositCoversDirectCogs\n    ? 0\n    : round2(directMaterialsAndPackagingCogsCad - b2bDepositRequiredCad);\n\n  const province = order.province || order.client?.province;\n  const taxes = computeCanadianTaxes(netRevenueCad, province);\n  const taxPreview = {\n    tpsCad: taxes.tpsCad,\n    tvqCad: taxes.tvqCad,\n    hstCad: taxes.hstCad,\n    totalTaxCad: taxes.totalTaxCad,\n    ...(province ? { province } : {}),\n  };\n\n  // Timeline & Cure Lead-Time Feasibility\n  const totalLeadDays =\n    maxCureTimeDays +\n    maxShortfallLeadDays +\n    STUDIO_PRICING_RULES.packagingAndFulfillmentBufferDays;\n  const earliestDateObj = new Date(now.getTime() + totalLeadDays * 86400000);\n  const earliestPossibleDeliveryDate = earliestDateObj.toISOString().split('T')[0];\n  const requestedDeliveryDate = parseDeliveryDate(order.timeline, now);\n\n  let cureFeasible = true;\n  let timelineWarning: string | undefined;\n  if (requestedDeliveryDate) {\n    const reqDateObj = new Date(`${requestedDeliveryDate}T00:00:00Z`);\n    if (reqDateObj.getTime() < earliestDateObj.getTime()) {\n      cureFeasible = false;\n      timelineWarning = `IMPOSSIBLE DELIVERY WINDOW: Requested ${requestedDeliveryDate} is earlier than earliest safe cure+restock+packing ship date ${earliestPossibleDeliveryDate} (${maxCureTimeDays}d cure + ${maxShortfallLeadDays}d restock + ${STUDIO_PRICING_RULES.packagingAndFulfillmentBufferDays}d pack). Recommend shifting date or splitting delivery.`;\n    }\n  }\n\n  const provNorm = (province || '').trim().toUpperCase();\n  const requiresQuebecBilingualPack =\n    provNorm === 'QC' ||\n    provNorm === 'QUEBEC' ||\n    provNorm === 'QU\u00C9BEC' ||\n    order.locale === 'fr' ||\n    order.locale === 'bilingual';\n\n  const requiresDevelopmentPortal =\n    isB2B &&\n    Boolean(\n      order.projectDetails?.developmentName ||\n        (order.client?.accountType && /builder|condo|rental|architect|developer/i.test(order.client.accountType)) ||\n        totalUnits >= 10,\n    );\n\n  const hasShortfalls = shortfalls.length > 0;\n  const dossierStatus: OrderEvaluationReport['dossierStatus'] = !cureFeasible\n    ? 'hold'\n    : hasShortfalls\n      ? 'needs_restock'\n      : order.requestType === 'quote_request' && meetsMarginFloor\n        ? 'approved_for_quote'\n        : 'pending_review';\n\n  const execStatusLine =\n    totalUnitsToProduce === 0\n      ? 'Ready to fulfill from finished studio stock (packing & QC only).'\n      : hasShortfalls\n        ? `Needs Batch Pour (${totalUnitsToProduce} units) + Raw/Packaging Restock (${shortfalls.length} items short).`\n        : `Materials in stock \u2014 Needs Batch Pour (${totalUnitsToProduce} units, ${maxCureTimeDays}d cure).`;\n\n  const linesTable = lineEvaluations\n    .map(\n      (l) =>\n        `| ${l.sku} | ${l.productName} | ${l.quantity} (${l.finishedStockAvailable} ready / ${l.unitsToProduce} pour) | $${l.unitTotalCogsCad.toFixed(2)} | $${l.quotedUnitPriceCad.toFixed(2)} | ${l.grossMarginPct.toFixed(1)}% | ${l.cureTimeDays}d |`,\n    )\n    .join('\\n');\n\n  const shortfallSection = hasShortfalls\n    ? shortfalls\n        .map(\n          (s) =>\n            `- **${s.itemName}** (${s.category}): Need **${s.requiredQty} ${s.unit}**, Available **${s.availableQty} ${s.unit}** -> **Short ${s.shortfallQty} ${s.unit}** (~$${s.estimatedReorderCostCad.toFixed(2)} CAD | Lead: ${s.supplierLeadDays || 7}d via ${s.suggestedVendor || 'Studio Vendor'})`,\n        )\n        .join('\\n')\n    : '- All raw botanicals, vessels, and packaging components verified in stock for this batch.';\n\n  const stagedQuoteMarkdown = [\n    `# INTERNAL PRODUCTION & COSTING DOSSIER \u2014 ${order.referenceCode}`,\n    `**CONFIDENTIAL INTERNAL STUDIO DOCUMENT \u2014 DO NOT SEND DIRECTLY TO EXTERNAL CLIENTS**`,\n    `- **Status:** \\`${dossierStatus}\\` | **Mode:** ${order.environment === 'staging' ? 'STAGING SANDBOX (ZERO LIVE MUTATION)' : order.requestType === 'quote_request' ? 'QUOTE STAGE (NO INVENTORY DEDUCTION)' : 'PAID ORDER REVIEW (HITL STOCK APPROVAL)'}`,\n    `- **Executive Summary:** ${execStatusLine}`,\n    `- **Client:** ${order.client.companyName} (${order.client.contactPerson} \u00B7 ${order.client.email})`,\n    `- **Province / Locale:** ${province || 'CA'} / ${order.locale.toUpperCase()} ${requiresQuebecBilingualPack ? '\u00B7 Quebec Loi 96 / OQLF Bilingual Pack Required' : ''}`,\n    ``,\n    `## 1. Line-by-Line Finished Stock, COGS & Margin Breakdown`,\n    `| SKU | Product | Qty (Ready / Pour) | Unit COGS | Unit Price | Gross Margin | Cure |`,\n    `|---|---|---:|---:|---:|---:|---:|`,\n    linesTable,\n    ``,\n    `## 2. Financial Summary, B2B 50% Deposit & Cash-Flow Check`,\n    `- **Quoted Subtotal:** $${rawSubtotal.toFixed(2)} CAD${customPigmentSetupFeeCad > 0 ? ` + $${customPigmentSetupFeeCad.toFixed(2)} Custom Jesmonite Color Setup` : ''}${orderDiscountCad > 0 ? ` - $${orderDiscountCad.toFixed(2)} Discount` : ''}`,\n    `- **Net Pre-Tax Revenue:** $${netRevenueCad.toFixed(2)} CAD`,\n    `- **Estimated Canadian Tax (${province || 'Default'}):** $${taxes.totalTaxCad.toFixed(2)} CAD (TPS $${taxes.tpsCad.toFixed(2)} \u00B7 TVQ $${taxes.tvqCad.toFixed(2)} \u00B7 HST $${taxes.hstCad.toFixed(2)})`,\n    `- **Total Loaded COGS:** $${totalWithCogsSetup.toFixed(2)} CAD (Direct Materials & Packaging: $${directMaterialsAndPackagingCogsCad.toFixed(2)} CAD)`,\n    `- **Gross Profit:** $${estimatedGrossProfitCad.toFixed(2)} CAD (**${grossMarginPct.toFixed(1)}% Margin** \u2014 ${meetsMarginFloor ? 'Meets >=70% Studio Floor' : 'ALERT: BELOW 70% MARGIN FLOOR'})`,\n    `- **Required ${depositPct}% B2B Deposit:** **$${b2bDepositRequiredCad.toFixed(2)} CAD** | **Balance Due at Delivery:** $${b2bBalanceDueCad.toFixed(2)} CAD`,\n    `- **Deposit Cash-Flow Coverage Check:** ${b2bDepositCoversDirectCogs ? `PASSED \u2014 50% deposit covers 100% of direct raw materials & packaging COGS ($${directMaterialsAndPackagingCogsCad.toFixed(2)} CAD).` : `CASH-FLOW WARNING \u2014 50% deposit ($${b2bDepositRequiredCad.toFixed(2)}) is short of direct raw materials & packaging COGS ($${directMaterialsAndPackagingCogsCad.toFixed(2)}) by $${depositCashFlowGapCad.toFixed(2)} CAD.`}`,\n    ``,\n    `## 3. Raw Materials & Packaging Restock / Purchase Estimate`,\n    shortfallSection,\n    ``,\n    `## 4. Curing Schedule & Delivery Feasibility`,\n    `- **Max Cure Window:** ${maxCureTimeDays} days | **Packaging & QC Buffer:** ${STUDIO_PRICING_RULES.packagingAndFulfillmentBufferDays} days | **Supplier Restock Lead:** ${maxShortfallLeadDays} days`,\n    `- **Earliest Safe Ship Date:** **${earliestPossibleDeliveryDate}**${requestedDeliveryDate ? ` (Requested: ${requestedDeliveryDate})` : ''}`,\n    timelineWarning ? `- **TIMELINE ALERT:** ${timelineWarning}` : `- Delivery window is feasible with current cure schedule.`,\n    ``,\n    `## 5. Copyable Quote Figures for Storefront #admin (Myrna Approval Only)`,\n    `- Reference: \\`${order.referenceCode}\\` | Net Quote: \\`$${netRevenueCad.toFixed(2)} CAD\\` | Est. Tax: \\`$${taxes.totalTaxCad.toFixed(2)} CAD\\` | Est. Total w/ Tax: \\`$${round2(netRevenueCad + taxes.totalTaxCad).toFixed(2)} CAD\\` | Required Deposit (${depositPct}%): \\`$${b2bDepositRequiredCad.toFixed(2)} CAD\\` | Earliest Ready: \\`${earliestPossibleDeliveryDate}\\``,\n  ].join('\\n');\n\n  return {\n    evaluatedAt: now.toISOString(),\n    dossierStatus,\n    requestType: order.requestType,\n    guardrailMode: order.requestType === 'paid_order' ? 'execute_paid_order' : 'stage_quote_no_deduction',\n    totalUnits,\n    totalFinishedStockAvailable,\n    totalUnitsToProduce,\n    directMaterialsAndPackagingCogsCad,\n    coBrandingAddOnsCostCad,\n    customPigmentSetupFeeCad,\n    totalCogsCad: totalWithCogsSetup,\n    quotedSubtotalCad: rawSubtotal,\n    discountCad: orderDiscountCad,\n    netRevenueCad,\n    recommendedSubtotalCad,\n    estimatedGrossProfitCad,\n    grossMarginPct,\n    meetsMarginFloor,\n    b2bDepositRequiredCad,\n    b2bBalanceDueCad,\n    depositPct,\n    b2bDepositCoversDirectCogs,\n    depositCashFlowGapCad,\n    taxPreview,\n    maxCureTimeDays,\n    earliestPossibleDeliveryDate,\n    ...(requestedDeliveryDate ? { requestedDeliveryDate } : {}),\n    cureFeasible,\n    ...(timelineWarning ? { timelineWarning } : {}),\n    requiresQuebecBilingualPack,\n    requiresDevelopmentPortal,\n    coBrandingOptions,\n    lineEvaluations,\n    shortfalls,\n    hasShortfalls,\n    stagedQuoteMarkdown,\n  };\n}\n", "import express from \"express\";\nimport type { Firestore } from \"firebase-admin/firestore\";\nimport {\n  buildReturnReceiptCapsule,\n  normalizeCapsuleForInboundIngestion,\n  shouldSendReturnReceipt,\n  validateInterAppCapsule,\n} from \"../lib/interAppCapsule.js\";\nimport {\n  computeHmacSha256Signature,\n  extractBridgeToken,\n  sanitizeFirestoreDocId,\n  tokensMatchConstantTime,\n  verifyHmacSha256Signature,\n} from \"../lib/bridgeSecurity.js\";\nimport type { InterAppCapsule } from \"../types.js\";\n\nconst DEFAULT_EXEC_OS_URL = \"https://ais-pre-vqblism4lsgzs2x5fuvjbz-136186099365.us-east1.run.app\";\nconst DEFAULT_APP_NAME = \"LJWellness StudioOS\";\nconst DEFAULT_SHARED_URL = \"https://ais-pre-ifdm6lmney5cu6xd3ojm3x-359488534598.us-west2.run.app\";\n\nexport interface BridgeRouterDeps {\n  getDb: () => Firestore;\n  resolveOwnerUid: (db: Firestore) => Promise<string | null>;\n  requireStudioOwner: express.RequestHandler;\n}\n\ninterface StoredBridgeRecord {\n  id: string;\n  capsuleId: string;\n  direction: \"inbound\" | \"outbound-push\" | \"outbound-receipt\" | \"outbound-staged\";\n  sourceApp: string;\n  targetApp: string;\n  purpose: string;\n  author: string;\n  status: string;\n  receivedAt: string;\n  inReplyTo?: string | null;\n  summary?: {\n    tasksImported: number;\n    assetsImported: number;\n    documentsImported: number;\n    notesImported: number;\n  };\n  capsule: InterAppCapsule;\n}\n\nexport function createBridgeRouter({\n  getDb,\n  resolveOwnerUid,\n  requireStudioOwner,\n}: BridgeRouterDeps): express.Router {\n  const router = express.Router();\n\n  // In-memory index mirrors Firestore so deduplication stays instantaneous even under burst pushes\n  const memoryInboundIndex = new Map<string, StoredBridgeRecord>();\n  const memoryOutboundQueue = new Map<string, StoredBridgeRecord>();\n\n  const getExecOsUrl = () =>\n    (process.env.EXEC_OS_URL || DEFAULT_EXEC_OS_URL).trim().replace(/\\/+$/, \"\");\n  const getExecOsKey = () => (process.env.EXEC_OS_BRIDGE_KEY || \"\").trim();\n  const getInboundKey = () =>\n    (process.env.BRIDGE_INBOUND_KEY || process.env.EXEC_OS_BRIDGE_KEY || \"\").trim();\n  const getHmacSecret = () => (process.env.BRIDGE_HMAC_SECRET || \"\").trim();\n  const getAppName = () => (process.env.BRIDGE_APP_NAME || DEFAULT_APP_NAME).trim();\n  const getOurBaseUrl = () =>\n    (process.env.APP_URL || DEFAULT_SHARED_URL).trim().replace(/\\/+$/, \"\");\n\n  const requireBridgePartnerAuth: express.RequestHandler = (req, res, next) => {\n    const expectedKey = getInboundKey();\n    if (!expectedKey) {\n      return res.status(503).json({\n        accepted: false,\n        error: \"Bridge inbound authentication key is not configured on the server.\",\n      });\n    }\n\n    const providedToken = extractBridgeToken(req.headers);\n    if (!tokensMatchConstantTime(providedToken, expectedKey)) {\n      return res.status(401).json({\n        accepted: false,\n        error: \"Unauthorized: Invalid or missing X-Bridge-Key or Bearer token.\",\n      });\n    }\n\n    const hmacSecret = getHmacSecret();\n    const signatureHeader =\n      typeof req.headers[\"x-bridge-signature\"] === \"string\"\n        ? req.headers[\"x-bridge-signature\"]\n        : undefined;\n\n    if (hmacSecret && (signatureHeader || process.env.BRIDGE_REQUIRE_HMAC === \"true\")) {\n      const rawBody: Buffer | string =\n        (req as any).rawBody instanceof Buffer\n          ? (req as any).rawBody\n          : JSON.stringify(req.body ?? {});\n      if (!verifyHmacSha256Signature(rawBody, signatureHeader, hmacSecret)) {\n        return res.status(401).json({\n          accepted: false,\n          error: \"Unauthorized: Invalid X-Bridge-Signature HMAC-SHA256 digest.\",\n        });\n      }\n    }\n\n    return next();\n  };\n\n  async function ingestValidatedCapsule(\n    capsule: InterAppCapsule,\n    direction: \"inbound\" | \"outbound-receipt\" = \"inbound\",\n  ): Promise<{\n    deduplicated: boolean;\n    capsuleId: string;\n    receivedAt: string;\n    summary: {\n      tasksImported: number;\n      assetsImported: number;\n      documentsImported: number;\n      notesImported: number;\n    };\n    returnCapsule: InterAppCapsule | null;\n  }> {\n    const db = getDb();\n    const docKey = `in_${sanitizeFirestoreDocId(capsule.id)}`;\n\n    // 1. Check in-memory and Firestore deduplication\n    const memHit = memoryInboundIndex.get(capsule.id);\n    if (memHit) {\n      return {\n        deduplicated: true,\n        capsuleId: capsule.id,\n        receivedAt: memHit.receivedAt,\n        summary: memHit.summary || {\n          tasksImported: 0,\n          assetsImported: 0,\n          documentsImported: 0,\n          notesImported: 0,\n        },\n        returnCapsule: null,\n      };\n    }\n\n    const existingSnap = await db.collection(\"bridge_capsules\").doc(docKey).get();\n    if (existingSnap.exists) {\n      const existingData = existingSnap.data() as StoredBridgeRecord;\n      memoryInboundIndex.set(capsule.id, existingData);\n      return {\n        deduplicated: true,\n        capsuleId: capsule.id,\n        receivedAt: existingData.receivedAt || new Date().toISOString(),\n        summary: existingData.summary || {\n          tasksImported: 0,\n          assetsImported: 0,\n          documentsImported: 0,\n          notesImported: 0,\n        },\n        returnCapsule: null,\n      };\n    }\n\n    // 2. Resolve Studio Owner UID for live workspace sync\n    const ownerUid = await resolveOwnerUid(db);\n    const normalized = normalizeCapsuleForInboundIngestion(capsule);\n    const nowIso = new Date().toISOString();\n    const today = nowIso.split(\"T\")[0];\n\n    let tasksImported = 0;\n    let assetsImported = 0;\n    let documentsImported = 0;\n    let notesImported = 0;\n\n    if (ownerUid) {\n      const batch = db.batch();\n\n      normalized.tasks.forEach((task, idx) => {\n        const taskId = `br_task_${sanitizeFirestoreDocId(capsule.id)}_${idx}`;\n        batch.set(db.collection(\"tasks\").doc(taskId), {\n          id: taskId,\n          uid: ownerUid,\n          title: task.title,\n          description: task.description,\n          assignedTo: task.assignedTo,\n          status: \"pending\",\n          priority: task.priority,\n          createdAt: today,\n          ...(task.dueDate ? { dueDate: task.dueDate } : {}),\n        });\n        tasksImported += 1;\n      });\n\n      normalized.assets.forEach((asset, idx) => {\n        const assetId = `br_asset_${sanitizeFirestoreDocId(capsule.id)}_${idx}`;\n        batch.set(db.collection(\"assets\").doc(assetId), {\n          id: assetId,\n          uid: ownerUid,\n          title: asset.title,\n          content: asset.content,\n          type: asset.type,\n          author: asset.author,\n          createdAt: today,\n        });\n        assetsImported += 1;\n      });\n\n      normalized.documents.forEach((docItem, idx) => {\n        const docId = `br_doc_${sanitizeFirestoreDocId(capsule.id)}_${idx}`;\n        batch.set(db.collection(\"documents\").doc(docId), {\n          id: docId,\n          uid: ownerUid,\n          title: docItem.title,\n          content: docItem.content,\n          type: docItem.type,\n          status: docItem.status,\n          clientName: docItem.clientName,\n          createdAt: today,\n          updatedAt: today,\n        });\n        documentsImported += 1;\n      });\n\n      normalized.smartNotes.forEach((note, idx) => {\n        const noteId = `br_note_${sanitizeFirestoreDocId(capsule.id)}_${idx}`;\n        batch.set(db.collection(\"smart_notes\").doc(noteId), {\n          id: noteId,\n          uid: ownerUid,\n          title: note.title,\n          category: \"Operations\",\n          status: \"actionable\",\n          specific: note.insights,\n          measurable: \"Synced via InterAppCapsule v1.0.0\",\n          achievable: \"Review in Studio\",\n          relevant: capsule.purpose,\n          timeBound: today,\n          insights: note.insights,\n          actionPlan: [],\n          tags: [\"InterAppBridge\", capsule.sourceApp],\n          author: \"StudioLead\",\n          createdAt: today,\n          updatedAt: today,\n        });\n        notesImported += 1;\n      });\n\n      await batch.commit();\n    }\n\n    const summary = {\n      tasksImported,\n      assetsImported,\n      documentsImported,\n      notesImported,\n    };\n\n    // Infinite-Loop Guard: only emit return receipt when requested AND !inReplyTo\n    const returnCapsule = shouldSendReturnReceipt(capsule)\n      ? buildReturnReceiptCapsule(capsule, getAppName(), summary)\n      : null;\n\n    const record: StoredBridgeRecord = {\n      id: docKey,\n      capsuleId: capsule.id,\n      direction,\n      sourceApp: capsule.sourceApp,\n      targetApp: capsule.targetApp || getAppName(),\n      purpose: capsule.purpose,\n      author: capsule.author,\n      status: \"INGESTED\",\n      receivedAt: nowIso,\n      inReplyTo: capsule.inReplyTo || null,\n      summary,\n      capsule,\n    };\n\n    await db.collection(\"bridge_capsules\").doc(docKey).set({\n      ...record,\n      uid: ownerUid || \"unassigned\",\n    });\n    memoryInboundIndex.set(capsule.id, record);\n\n    if (returnCapsule) {\n      const receiptKey = `out_ack_${sanitizeFirestoreDocId(returnCapsule.id)}`;\n      await db.collection(\"bridge_capsules\").doc(receiptKey).set({\n        id: receiptKey,\n        uid: ownerUid || \"unassigned\",\n        capsuleId: returnCapsule.id,\n        direction: \"outbound-receipt\",\n        sourceApp: returnCapsule.sourceApp,\n        targetApp: returnCapsule.targetApp || capsule.sourceApp,\n        purpose: returnCapsule.purpose,\n        author: returnCapsule.author,\n        status: \"SENT\",\n        receivedAt: nowIso,\n        inReplyTo: returnCapsule.inReplyTo || null,\n        capsule: returnCapsule,\n      });\n    }\n\n    return {\n      deduplicated: false,\n      capsuleId: capsule.id,\n      receivedAt: nowIso,\n      summary,\n      returnCapsule,\n    };\n  }\n\n  function buildPartnerHeaders(rawBody?: string): Record<string, string> {\n    const key = getExecOsKey();\n    const headers: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n      \"X-Bridge-Key\": key,\n      Authorization: `Bearer ${key}`,\n    };\n    const hmacSecret = getHmacSecret();\n    if (hmacSecret && rawBody !== undefined) {\n      headers[\"X-Bridge-Signature\"] = computeHmacSha256Signature(rawBody, hmacSecret);\n    }\n    return headers;\n  }\n\n  // =========================================================================\n  // 1. PUBLIC HEALTH CHECK (GET /api/bridge/health)\n  // =========================================================================\n  router.get(\"/health\", (_req, res) => {\n    res.json({\n      status: \"ok\",\n      app: getAppName(),\n      protocol: \"InterAppCapsule\",\n      schemaVersion: \"1.0.0\",\n      endpoints: {\n        health: \"/api/bridge/health\",\n        inbound: \"/api/bridge/inbound\",\n        webhook: \"/api/bridge/webhook\",\n        outbound: \"/api/bridge/outbound\",\n        outboundAck: \"/api/bridge/outbound/:capsuleId/ack\",\n      },\n      auth: {\n        headers: [\"X-Bridge-Key\", \"Authorization: Bearer <token>\"],\n        hmacHeader: \"X-Bridge-Signature\",\n        hmacConfigured: Boolean(getHmacSecret()),\n        inboundKeyConfigured: Boolean(getInboundKey()),\n      },\n      timestamp: new Date().toISOString(),\n    });\n  });\n\n  // =========================================================================\n  // 2. PARTNER-FACING INBOUND WEBHOOK (POST /api/bridge/inbound & /webhook)\n  // =========================================================================\n  const handleInboundWebhook: express.RequestHandler = async (req, res) => {\n    try {\n      const validation = validateInterAppCapsule(req.body);\n      if (!validation.valid) {\n        return res.status(400).json({\n          accepted: false,\n          error: validation.error,\n          issues: validation.issues,\n        });\n      }\n\n      const result = await ingestValidatedCapsule(validation.capsule, \"inbound\");\n      if (result.deduplicated) {\n        return res.status(200).json({\n          success: true,\n          accepted: true,\n          deduplicated: true,\n          capsuleId: result.capsuleId,\n          status: \"ALREADY_INGESTED\",\n          receivedAt: result.receivedAt,\n          returnCapsule: null,\n        });\n      }\n\n      return res.status(202).json({\n        success: true,\n        accepted: true,\n        deduplicated: false,\n        capsuleId: result.capsuleId,\n        status: \"QUEUED_FOR_INGESTION\",\n        ingested: result.summary,\n        receivedAt: result.receivedAt,\n        returnCapsule: result.returnCapsule,\n      });\n    } catch (error: any) {\n      console.error(\"Error in /api/bridge/inbound:\", error);\n      return res.status(500).json({\n        accepted: false,\n        error: \"Internal error processing InterAppCapsule.\",\n      });\n    }\n  };\n\n  router.post(\"/inbound\", requireBridgePartnerAuth, handleInboundWebhook);\n  router.post(\"/webhook\", requireBridgePartnerAuth, handleInboundWebhook);\n\n  // =========================================================================\n  // 3. PARTNER-FACING OUTBOUND PULL QUEUE (GET /api/bridge/outbound & /ack)\n  // =========================================================================\n  router.get(\"/outbound\", requireBridgePartnerAuth, async (req, res) => {\n    try {\n      const targetApp =\n        typeof req.query.targetApp === \"string\" ? req.query.targetApp.trim() : \"\";\n      const statusFilter =\n        typeof req.query.status === \"string\" && req.query.status.trim()\n          ? req.query.status.trim().toUpperCase()\n          : \"STAGED\";\n      const limit = Math.min(50, Math.max(1, Number(req.query.limit) || 20));\n\n      const db = getDb();\n      const snap = await db\n        .collection(\"bridge_outbound\")\n        .where(\"status\", \"==\", statusFilter)\n        .limit(limit * 2)\n        .get();\n\n      const records: StoredBridgeRecord[] = [];\n      snap.forEach((doc) => {\n        const data = doc.data() as StoredBridgeRecord;\n        if (\n          !targetApp ||\n          !data.targetApp ||\n          data.targetApp.toLowerCase().includes(targetApp.toLowerCase()) ||\n          targetApp.toLowerCase().includes(data.targetApp.toLowerCase())\n        ) {\n          records.push(data);\n        }\n      });\n\n      records.sort((a, b) => b.receivedAt.localeCompare(a.receivedAt));\n      const sliced = records.slice(0, limit);\n\n      return res.json({\n        success: true,\n        count: sliced.length,\n        capsules: sliced.map((r) => r.capsule),\n        records: sliced.map((r) => ({\n          id: r.capsuleId,\n          status: r.status,\n          targetApp: r.targetApp,\n          purpose: r.purpose,\n          stagedAt: r.receivedAt,\n        })),\n      });\n    } catch (error: any) {\n      console.error(\"Error in GET /api/bridge/outbound:\", error);\n      return res.status(500).json({\n        success: false,\n        error: \"Unable to query outbound bridge queue.\",\n      });\n    }\n  });\n\n  router.post(\"/outbound/:capsuleId/ack\", requireBridgePartnerAuth, async (req, res) => {\n    try {\n      const rawCapsuleId = String(req.params.capsuleId || \"\").trim();\n      if (!rawCapsuleId) {\n        return res.status(400).json({ success: false, error: \"Missing capsuleId parameter.\" });\n      }\n\n      const db = getDb();\n      const docKey = `stg_${sanitizeFirestoreDocId(rawCapsuleId)}`;\n      const nowIso = new Date().toISOString();\n      const body = req.body || {};\n      const ackStatus = String(body?.meta?.status || \"INGESTED\").toUpperCase();\n\n      const ref = db.collection(\"bridge_outbound\").doc(docKey);\n      const snap = await ref.get();\n      if (snap.exists) {\n        await ref.update({\n          status: ackStatus,\n          acknowledgedBy: String(body?.acknowledgedBy || \"Personal Executive OS\"),\n          acknowledgedAt: nowIso,\n        });\n      }\n      memoryOutboundQueue.delete(rawCapsuleId);\n\n      let reciprocalIngested: any = null;\n      const reciprocal = body?.reciprocalCapsule || body?.returnCapsule;\n      if (reciprocal) {\n        const validation = validateInterAppCapsule(reciprocal);\n        if (!validation.valid) {\n          return res.status(400).json({\n            success: false,\n            error: `Invalid reciprocalCapsule: ${validation.error}`,\n            issues: validation.issues,\n          });\n        }\n        reciprocalIngested = await ingestValidatedCapsule(validation.capsule, \"inbound\");\n      }\n\n      return res.json({\n        success: true,\n        capsuleId: rawCapsuleId,\n        status: ackStatus,\n        acknowledgedAt: nowIso,\n        reciprocalIngested,\n      });\n    } catch (error: any) {\n      console.error(\"Error in POST /api/bridge/outbound/:capsuleId/ack:\", error);\n      return res.status(500).json({\n        success: false,\n        error: \"Unable to acknowledge outbound capsule.\",\n      });\n    }\n  });\n\n  // =========================================================================\n  // 4. STUDIO-OWNER SERVER-TO-SERVER PROXY ROUTES (Protected by Firebase Auth)\n  // =========================================================================\n  router.get(\"/status\", requireStudioOwner, async (_req, res) => {\n    try {\n      const db = getDb();\n      const ownerUid = await resolveOwnerUid(db);\n\n      const historySnap = await db.collection(\"bridge_capsules\").limit(40).get();\n      const recentCapsules: any[] = [];\n      historySnap.forEach((doc) => {\n        const d = doc.data();\n        if (!ownerUid || !d.uid || d.uid === ownerUid || d.uid === \"unassigned\") {\n          recentCapsules.push({\n            id: d.capsuleId || doc.id,\n            direction: d.direction,\n            sourceApp: d.sourceApp,\n            targetApp: d.targetApp,\n            purpose: d.purpose,\n            status: d.status,\n            receivedAt: d.receivedAt,\n            inReplyTo: d.inReplyTo || null,\n            summary: d.summary || null,\n          });\n        }\n      });\n      recentCapsules.sort((a, b) =>\n        String(b.receivedAt || \"\").localeCompare(String(a.receivedAt || \"\")),\n      );\n\n      const stagedSnap = await db\n        .collection(\"bridge_outbound\")\n        .where(\"status\", \"==\", \"STAGED\")\n        .limit(20)\n        .get();\n      const stagedOutbound: any[] = [];\n      stagedSnap.forEach((doc) => {\n        const d = doc.data();\n        stagedOutbound.push({\n          id: d.capsuleId,\n          targetApp: d.targetApp,\n          purpose: d.purpose,\n          status: d.status,\n          stagedAt: d.receivedAt,\n        });\n      });\n      stagedOutbound.sort((a, b) =>\n        String(b.stagedAt || \"\").localeCompare(String(a.stagedAt || \"\")),\n      );\n\n      return res.json({\n        appName: getAppName(),\n        execOsUrl: getExecOsUrl(),\n        ourSharedBaseUrl: getOurBaseUrl(),\n        execOsKeyConfigured: Boolean(getExecOsKey()),\n        inboundKeyConfigured: Boolean(getInboundKey()),\n        hmacConfigured: Boolean(getHmacSecret()),\n        recentCapsules: recentCapsules.slice(0, 20),\n        stagedOutbound,\n      });\n    } catch (error: any) {\n      console.error(\"Error in GET /api/bridge/status:\", error);\n      return res.status(500).json({ error: \"Failed to load bridge status.\" });\n    }\n  });\n\n  router.post(\"/outbound/stage\", requireStudioOwner, async (req, res) => {\n    try {\n      const validation = validateInterAppCapsule(req.body);\n      if (!validation.valid) {\n        return res.status(400).json({\n          success: false,\n          error: validation.error,\n          issues: validation.issues,\n        });\n      }\n\n      const capsule = validation.capsule;\n      const db = getDb();\n      const ownerUid = await resolveOwnerUid(db);\n      const docKey = `stg_${sanitizeFirestoreDocId(capsule.id)}`;\n      const nowIso = new Date().toISOString();\n\n      const record: StoredBridgeRecord = {\n        id: docKey,\n        capsuleId: capsule.id,\n        direction: \"outbound-staged\",\n        sourceApp: capsule.sourceApp,\n        targetApp: capsule.targetApp || \"Personal Executive OS\",\n        purpose: capsule.purpose,\n        author: capsule.author,\n        status: \"STAGED\",\n        receivedAt: nowIso,\n        inReplyTo: capsule.inReplyTo || null,\n        capsule,\n      };\n\n      await db.collection(\"bridge_outbound\").doc(docKey).set({\n        ...record,\n        uid: ownerUid || \"unassigned\",\n      });\n      memoryOutboundQueue.set(capsule.id, record);\n\n      return res.status(201).json({\n        success: true,\n        capsuleId: capsule.id,\n        status: \"STAGED\",\n        stagedAt: nowIso,\n      });\n    } catch (error: any) {\n      console.error(\"Error in POST /api/bridge/outbound/stage:\", error);\n      return res.status(500).json({ error: \"Failed to stage outbound capsule.\" });\n    }\n  });\n\n  router.delete(\"/outbound/:capsuleId\", requireStudioOwner, async (req, res) => {\n    try {\n      const rawId = String(req.params.capsuleId || \"\").trim();\n      if (!rawId) return res.status(400).json({ error: \"Missing capsuleId\" });\n      const db = getDb();\n      await db.collection(\"bridge_outbound\").doc(`stg_${sanitizeFirestoreDocId(rawId)}`).delete();\n      memoryOutboundQueue.delete(rawId);\n      return res.json({ success: true, capsuleId: rawId });\n    } catch (error: any) {\n      return res.status(500).json({ error: \"Failed to delete staged capsule.\" });\n    }\n  });\n\n  router.get(\"/exec-os/health\", requireStudioOwner, async (_req, res) => {\n    try {\n      const targetUrl = `${getExecOsUrl()}/api/bridge/health`;\n      const upstream = await fetch(targetUrl, {\n        method: \"GET\",\n        signal: AbortSignal.timeout(8000),\n      });\n      const text = await upstream.text();\n      let parsed: any = null;\n      try {\n        parsed = JSON.parse(text);\n      } catch {\n        parsed = { raw: text.slice(0, 500) };\n      }\n      return res.status(upstream.ok ? 200 : upstream.status).json({\n        ok: upstream.ok,\n        httpStatus: upstream.status,\n        targetUrl,\n        remote: parsed,\n      });\n    } catch (error: any) {\n      return res.status(502).json({\n        ok: false,\n        error: error?.message || \"Failed to reach Personal Executive OS health endpoint.\",\n      });\n    }\n  });\n\n  router.post(\"/exec-os/push\", requireStudioOwner, async (req, res) => {\n    try {\n      const key = getExecOsKey();\n      if (!key) {\n        return res.status(503).json({\n          ok: false,\n          error:\n            \"EXEC_OS_BRIDGE_KEY is not configured on the server. Add your X-Bridge-Key from Personal Executive OS -> Connections & API to server environment secrets.\",\n        });\n      }\n\n      const validation = validateInterAppCapsule(req.body);\n      if (!validation.valid) {\n        return res.status(400).json({\n          ok: false,\n          error: validation.error,\n          issues: validation.issues,\n        });\n      }\n\n      const capsule = validation.capsule;\n      const rawJson = JSON.stringify(capsule);\n      const targetUrl = `${getExecOsUrl()}/api/bridge/inbound`;\n\n      const upstream = await fetch(targetUrl, {\n        method: \"POST\",\n        headers: buildPartnerHeaders(rawJson),\n        body: rawJson,\n        signal: AbortSignal.timeout(12000),\n      });\n\n      const responseText = await upstream.text();\n      let remoteData: any = {};\n      try {\n        remoteData = JSON.parse(responseText);\n      } catch {\n        remoteData = { raw: responseText.slice(0, 600) };\n      }\n\n      const db = getDb();\n      const ownerUid = await resolveOwnerUid(db);\n      const nowIso = new Date().toISOString();\n\n      await db\n        .collection(\"bridge_capsules\")\n        .doc(`out_${sanitizeFirestoreDocId(capsule.id)}`)\n        .set({\n          id: `out_${sanitizeFirestoreDocId(capsule.id)}`,\n          uid: ownerUid || \"unassigned\",\n          capsuleId: capsule.id,\n          direction: \"outbound-push\",\n          sourceApp: capsule.sourceApp,\n          targetApp: capsule.targetApp || \"Personal Executive OS\",\n          purpose: capsule.purpose,\n          author: capsule.author,\n          status: upstream.ok ? remoteData?.status || \"ACCEPTED\" : `HTTP_${upstream.status}`,\n          receivedAt: nowIso,\n          inReplyTo: capsule.inReplyTo || null,\n          capsule,\n        });\n\n      let syncedReturnCapsule: any = null;\n      const possibleReturn = remoteData?.returnCapsule || remoteData?.reciprocalCapsule;\n      if (upstream.ok && possibleReturn) {\n        const retValidation = validateInterAppCapsule(possibleReturn);\n        if (retValidation.valid) {\n          syncedReturnCapsule = await ingestValidatedCapsule(retValidation.capsule, \"inbound\");\n        }\n      }\n\n      return res.status(upstream.ok ? upstream.status : upstream.status).json({\n        ok: upstream.ok,\n        httpStatus: upstream.status,\n        capsuleId: capsule.id,\n        remote: remoteData,\n        syncedReturnCapsule,\n      });\n    } catch (error: any) {\n      console.error(\"Error in POST /api/bridge/exec-os/push:\", error);\n      return res.status(502).json({\n        ok: false,\n        error: error?.message || \"Failed to push capsule to Personal Executive OS.\",\n      });\n    }\n  });\n\n  router.get(\"/exec-os/pull\", requireStudioOwner, async (req, res) => {\n    try {\n      const key = getExecOsKey();\n      if (!key) {\n        return res.status(503).json({\n          ok: false,\n          error: \"EXEC_OS_BRIDGE_KEY is not configured on the server.\",\n        });\n      }\n\n      const targetAppParam =\n        typeof req.query.targetApp === \"string\" ? req.query.targetApp.trim() : getAppName();\n      const statusParam =\n        typeof req.query.status === \"string\" && req.query.status.trim()\n          ? req.query.status.trim()\n          : \"STAGED\";\n      const limitParam = Math.min(50, Math.max(1, Number(req.query.limit) || 20));\n\n      const params = new URLSearchParams({\n        status: statusParam,\n        limit: String(limitParam),\n      });\n      if (targetAppParam) {\n        params.set(\"targetApp\", targetAppParam);\n      }\n\n      const targetUrl = `${getExecOsUrl()}/api/bridge/outbound?${params.toString()}`;\n      const upstream = await fetch(targetUrl, {\n        method: \"GET\",\n        headers: buildPartnerHeaders(),\n        signal: AbortSignal.timeout(12000),\n      });\n\n      const text = await upstream.text();\n      let remoteData: any = {};\n      try {\n        remoteData = JSON.parse(text);\n      } catch {\n        remoteData = { raw: text.slice(0, 600) };\n      }\n\n      return res.status(upstream.ok ? 200 : upstream.status).json({\n        ok: upstream.ok,\n        httpStatus: upstream.status,\n        count: Array.isArray(remoteData?.capsules) ? remoteData.capsules.length : 0,\n        capsules: Array.isArray(remoteData?.capsules) ? remoteData.capsules : [],\n        records: Array.isArray(remoteData?.records) ? remoteData.records : [],\n        remote: remoteData,\n      });\n    } catch (error: any) {\n      return res.status(502).json({\n        ok: false,\n        error: error?.message || \"Failed to pull outbound queue from Personal Executive OS.\",\n      });\n    }\n  });\n\n  router.post(\"/exec-os/ack\", requireStudioOwner, async (req, res) => {\n    try {\n      const key = getExecOsKey();\n      if (!key) {\n        return res.status(503).json({\n          ok: false,\n          error: \"EXEC_OS_BRIDGE_KEY is not configured on the server.\",\n        });\n      }\n\n      const { capsuleId, reciprocalCapsule, status } = req.body || {};\n      if (!capsuleId || typeof capsuleId !== \"string\") {\n        return res.status(400).json({ ok: false, error: \"capsuleId is required.\" });\n      }\n\n      let validReciprocal: InterAppCapsule | null = null;\n      if (reciprocalCapsule) {\n        const check = validateInterAppCapsule(reciprocalCapsule);\n        if (!check.valid) {\n          return res.status(400).json({\n            ok: false,\n            error: `Invalid reciprocalCapsule: ${check.error}`,\n            issues: check.issues,\n          });\n        }\n        validReciprocal = check.capsule;\n      }\n\n      const ackBody = JSON.stringify({\n        acknowledgedBy: getAppName(),\n        meta: { status: status || \"INGESTED\" },\n        reciprocalCapsule: validReciprocal,\n      });\n\n      const targetUrl = `${getExecOsUrl()}/api/bridge/outbound/${encodeURIComponent(capsuleId)}/ack`;\n      const upstream = await fetch(targetUrl, {\n        method: \"POST\",\n        headers: buildPartnerHeaders(ackBody),\n        body: ackBody,\n        signal: AbortSignal.timeout(12000),\n      });\n\n      const text = await upstream.text();\n      let remote: any = {};\n      try {\n        remote = JSON.parse(text);\n      } catch {\n        remote = { raw: text.slice(0, 500) };\n      }\n\n      return res.status(upstream.ok ? 200 : upstream.status).json({\n        ok: upstream.ok,\n        httpStatus: upstream.status,\n        capsuleId,\n        remote,\n      });\n    } catch (error: any) {\n      return res.status(502).json({\n        ok: false,\n        error: error?.message || \"Failed to acknowledge capsule on Personal Executive OS.\",\n      });\n    }\n  });\n\n  router.post(\"/exec-os/pull-and-ingest\", requireStudioOwner, async (req, res) => {\n    try {\n      const key = getExecOsKey();\n      if (!key) {\n        return res.status(503).json({\n          ok: false,\n          error: \"EXEC_OS_BRIDGE_KEY is not configured on the server.\",\n        });\n      }\n\n      const targetAppParam =\n        typeof req.body?.targetApp === \"string\" ? req.body.targetApp.trim() : getAppName();\n      const params = new URLSearchParams({ status: \"STAGED\", limit: \"20\" });\n      if (targetAppParam) params.set(\"targetApp\", targetAppParam);\n\n      const pullRes = await fetch(`${getExecOsUrl()}/api/bridge/outbound?${params.toString()}`, {\n        method: \"GET\",\n        headers: buildPartnerHeaders(),\n        signal: AbortSignal.timeout(12000),\n      });\n\n      if (!pullRes.ok) {\n        const errText = await pullRes.text();\n        return res.status(pullRes.status).json({\n          ok: false,\n          error: `Personal Executive OS returned HTTP ${pullRes.status}`,\n          details: errText.slice(0, 400),\n        });\n      }\n\n      const pullData = await pullRes.json();\n      const rawCapsules: unknown[] = Array.isArray(pullData?.capsules) ? pullData.capsules : [];\n\n      let ingestedCount = 0;\n      let deduplicatedCount = 0;\n      const ackedIds: string[] = [];\n      const errors: string[] = [];\n\n      for (const item of rawCapsules) {\n        const validation = validateInterAppCapsule(item);\n        if (!validation.valid) {\n          errors.push(validation.error);\n          continue;\n        }\n\n        const cap = validation.capsule;\n        const ingestResult = await ingestValidatedCapsule(cap, \"inbound\");\n        if (ingestResult.deduplicated) deduplicatedCount += 1;\n        else ingestedCount += 1;\n\n        const ackBody = JSON.stringify({\n          acknowledgedBy: getAppName(),\n          meta: { status: \"INGESTED\" },\n          reciprocalCapsule: ingestResult.returnCapsule,\n        });\n\n        try {\n          const ackRes = await fetch(\n            `${getExecOsUrl()}/api/bridge/outbound/${encodeURIComponent(cap.id)}/ack`,\n            {\n              method: \"POST\",\n              headers: buildPartnerHeaders(ackBody),\n              body: ackBody,\n              signal: AbortSignal.timeout(10000),\n            },\n          );\n          if (ackRes.ok) {\n            ackedIds.push(cap.id);\n          } else {\n            errors.push(`ACK failed for ${cap.id} (HTTP ${ackRes.status})`);\n          }\n        } catch (ackErr: any) {\n          errors.push(`ACK network error for ${cap.id}: ${ackErr?.message || \"timeout\"}`);\n        }\n      }\n\n      return res.json({\n        ok: true,\n        pulledCount: rawCapsules.length,\n        ingestedCount,\n        deduplicatedCount,\n        ackedIds,\n        errors,\n      });\n    } catch (error: any) {\n      return res.status(502).json({\n        ok: false,\n        error: error?.message || \"Pull-and-ingest sync with Personal Executive OS failed.\",\n      });\n    }\n  });\n\n  return router;\n}\n", "import type { InterAppCapsule, AgentRole } from '../types';\n\nexport const STRICT_ISO_8601_REGEX =\n  /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,9})?(Z|[+-]\\d{2}:\\d{2})$/;\n\nexport const CAPSULE_ARRAY_FIELDS = [\n  'tasks',\n  'strategicNotes',\n  'notes',\n  'documents',\n  'formulations',\n  'assets',\n  'inventorySnapshot',\n  'marketingCampaigns',\n] as const;\n\nexport type CapsuleValidationResult =\n  | { valid: true; capsule: InterAppCapsule; error?: undefined; issues?: undefined }\n  | { valid: false; capsule?: undefined; error: string; issues: string[] };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n  return typeof value === 'string' && value.trim().length > 0;\n}\n\nexport function extractJsonFromCapsuleInput(rawText: string): string {\n  const trimmed = rawText.trim();\n  const fenced =\n    trimmed.match(/```json\\s*([\\s\\S]*?)\\s*```/i) ||\n    trimmed.match(/```\\s*([\\s\\S]*?)\\s*```/);\n  return fenced ? fenced[1].trim() : trimmed;\n}\n\nexport function validateInterAppCapsule(raw: unknown): CapsuleValidationResult {\n  const issues: string[] = [];\n\n  if (!isPlainObject(raw)) {\n    return {\n      valid: false,\n      error: 'Capsule body must be a non-null JSON object.',\n      issues: ['root: expected plain JSON object'],\n    };\n  }\n\n  if (raw.schemaVersion !== '1.0.0') {\n    issues.push('schemaVersion must be exact string \"1.0.0\"');\n  }\n  if (!isNonEmptyString(raw.id)) {\n    issues.push('id must be a non-empty string');\n  }\n  if (!isNonEmptyString(raw.sourceApp)) {\n    issues.push('sourceApp must be a non-empty string');\n  }\n  if (raw.targetApp !== undefined && typeof raw.targetApp !== 'string') {\n    issues.push('targetApp must be a string if provided');\n  }\n  if (!isNonEmptyString(raw.author)) {\n    issues.push('author must be a non-empty string');\n  }\n  if (!isNonEmptyString(raw.purpose)) {\n    issues.push('purpose must be a non-empty string');\n  }\n  if (\n    typeof raw.timestamp !== 'string' ||\n    !STRICT_ISO_8601_REGEX.test(raw.timestamp) ||\n    Number.isNaN(Date.parse(raw.timestamp))\n  ) {\n    issues.push(\n      'timestamp must be a valid strict ISO 8601 string (YYYY-MM-DDTHH:mm:ss(.sss)?Z|+/-HH:MM)',\n    );\n  }\n  if (\n    raw.directivesForReceivingAgents !== undefined &&\n    typeof raw.directivesForReceivingAgents !== 'string'\n  ) {\n    issues.push('directivesForReceivingAgents must be a string if provided');\n  }\n  if (raw.inReplyTo !== undefined && !isNonEmptyString(raw.inReplyTo)) {\n    issues.push('inReplyTo must be a non-empty string if provided');\n  }\n  if (\n    raw.returnDispatchRequested !== undefined &&\n    typeof raw.returnDispatchRequested !== 'boolean'\n  ) {\n    issues.push('returnDispatchRequested must be a boolean if provided');\n  }\n\n  if (!isPlainObject(raw.payload)) {\n    issues.push('payload must be a non-null JSON object (not an array)');\n  } else {\n    if (raw.payload.brandProfile !== undefined && !isPlainObject(raw.payload.brandProfile)) {\n      issues.push('payload.brandProfile must be an object if provided');\n    }\n    for (const field of CAPSULE_ARRAY_FIELDS) {\n      if (raw.payload[field] !== undefined && !Array.isArray(raw.payload[field])) {\n        issues.push(`payload.${field} must be an array if provided`);\n      }\n    }\n  }\n\n  if (issues.length > 0) {\n    return {\n      valid: false,\n      error: `InterAppCapsule v1.0.0 validation failed: ${issues[0]}`,\n      issues,\n    };\n  }\n\n  return {\n    valid: true,\n    capsule: raw as unknown as InterAppCapsule,\n  };\n}\n\n/**\n * Infinite-Loop Guard:\n * Only generate an automatic return receipt if returnDispatchRequested === true AND !inReplyTo.\n */\nexport function shouldSendReturnReceipt(capsule: InterAppCapsule): boolean {\n  return capsule.returnDispatchRequested === true && !capsule.inReplyTo;\n}\n\nexport function buildReturnReceiptCapsule(\n  incoming: InterAppCapsule,\n  ourAppName: string,\n  summary: {\n    tasksImported: number;\n    assetsImported: number;\n    documentsImported: number;\n    notesImported: number;\n  },\n): InterAppCapsule {\n  const nowIso = new Date().toISOString();\n  const suffix = Math.random().toString(36).slice(2, 7).toUpperCase();\n  return {\n    schemaVersion: '1.0.0',\n    id: `CAPSULE-ACK-${Date.now().toString(36).toUpperCase()}-${suffix}`,\n    sourceApp: ourAppName,\n    targetApp: incoming.sourceApp,\n    timestamp: nowIso,\n    author: 'LJWellnessBridge',\n    purpose: `Automatic Ingestion Receipt for ${incoming.id}`,\n    inReplyTo: incoming.id,\n    returnDispatchRequested: false,\n    payload: {\n      notes: [\n        `Ingested capsule ${incoming.id} from ${incoming.sourceApp}: ${summary.tasksImported} tasks, ${summary.assetsImported} assets, ${summary.documentsImported} documents, ${summary.notesImported} notes.`,\n      ],\n      strategicNotes: [\n        `2-Way Bridge sync confirmed at ${nowIso} for ${incoming.purpose}.`,\n      ],\n    },\n  };\n}\n\nconst VALID_AGENT_ROLES = new Set<AgentRole>([\n  'StudioLead',\n  'Formulator',\n  'Business',\n  'Marketing',\n  'NicheExpert',\n  'WealthAdvisor',\n  'Mentor',\n]);\n\nexport function resolveAgentRole(rawRole: unknown): AgentRole {\n  if (typeof rawRole === 'string' && VALID_AGENT_ROLES.has(rawRole as AgentRole)) {\n    return rawRole as AgentRole;\n  }\n  return 'StudioLead';\n}\n\nfunction extractNoteText(item: unknown): { title: string; content: string } {\n  if (typeof item === 'string') {\n    const clean = item.trim();\n    return {\n      title: clean.slice(0, 72) || 'Strategic Note',\n      content: clean,\n    };\n  }\n  if (isPlainObject(item)) {\n    const title = String(item.title || item.summary || 'Strategic Note').trim();\n    const content = String(item.content || item.text || item.summary || title).trim();\n    return { title: title.slice(0, 120), content };\n  }\n  return { title: 'Strategic Note', content: String(item ?? '') };\n}\n\nexport interface NormalizedInboundEntities {\n  tasks: Array<{\n    title: string;\n    description: string;\n    assignedTo: AgentRole;\n    priority: 'low' | 'medium' | 'high';\n    dueDate?: string;\n  }>;\n  assets: Array<{\n    title: string;\n    content: string;\n    type: 'recipe' | 'marketing' | 'strategy' | 'legal';\n    author: AgentRole;\n  }>;\n  documents: Array<{\n    title: string;\n    content: string;\n    type: 'quote' | 'agreement' | 'offering' | 'receipt' | 'audit' | 'other';\n    status: 'draft' | 'sent' | 'approved' | 'paid' | 'completed';\n    clientName: string;\n  }>;\n  smartNotes: Array<{\n    title: string;\n    insights: string;\n  }>;\n}\n\nexport function normalizeCapsuleForInboundIngestion(\n  capsule: InterAppCapsule,\n): NormalizedInboundEntities {\n  const sourceLabel = capsule.sourceApp.slice(0, 80);\n  const tasks: NormalizedInboundEntities['tasks'] = [];\n  const assets: NormalizedInboundEntities['assets'] = [];\n  const documents: NormalizedInboundEntities['documents'] = [];\n  const smartNotes: NormalizedInboundEntities['smartNotes'] = [];\n\n  if (Array.isArray(capsule.payload.tasks)) {\n    for (const rawTask of capsule.payload.tasks) {\n      if (!isPlainObject(rawTask)) continue;\n      const rawTitle = String(\n        rawTask.title || rawTask.task || rawTask.name || rawTask.text || 'Cross-App Directive',\n      ).trim();\n      const rawDesc = String(\n        rawTask.description || rawTask.task || rawTask.text || rawTitle,\n      ).trim();\n      const prioRaw = String(rawTask.priority || 'medium').toLowerCase();\n      const priority: 'low' | 'medium' | 'high' =\n        prioRaw === 'high' || prioRaw === 'urgent'\n          ? 'high'\n          : prioRaw === 'low'\n            ? 'low'\n            : 'medium';\n\n      tasks.push({\n        title: `[${sourceLabel}] ${rawTitle}`.slice(0, 480),\n        description: `${rawDesc}\\n\\nOrigin Capsule: ${capsule.id} (${sourceLabel})`,\n        assignedTo: resolveAgentRole(rawTask.assignedTo),\n        priority,\n        dueDate: typeof rawTask.dueDate === 'string' ? rawTask.dueDate.slice(0, 20) : undefined,\n      });\n    }\n  }\n\n  if (capsule.directivesForReceivingAgents && capsule.directivesForReceivingAgents.trim()) {\n    tasks.push({\n      title: `[${sourceLabel}] Agent Directives: ${capsule.purpose}`.slice(0, 480),\n      description: `${capsule.directivesForReceivingAgents.trim()}\\n\\nOrigin Capsule: ${capsule.id} (${sourceLabel})`,\n      assignedTo: 'StudioLead',\n      priority: 'high',\n    });\n  }\n\n  if (Array.isArray(capsule.payload.assets)) {\n    for (const rawAsset of capsule.payload.assets) {\n      if (!isPlainObject(rawAsset)) continue;\n      const title = String(rawAsset.title || rawAsset.name || 'Imported Asset').trim();\n      const content = String(rawAsset.content || rawAsset.summary || '').trim();\n      if (!content && !title) continue;\n      const t = String(rawAsset.type || 'strategy').toLowerCase();\n      const type: 'recipe' | 'marketing' | 'strategy' | 'legal' =\n        t === 'recipe' || t === 'marketing' || t === 'legal' ? t : 'strategy';\n\n      assets.push({\n        title: `[${sourceLabel}] ${title}`.slice(0, 480),\n        content: (content || title).slice(0, 190000),\n        type,\n        author: resolveAgentRole(rawAsset.author),\n      });\n    }\n  }\n\n  if (Array.isArray(capsule.payload.documents)) {\n    for (const rawDoc of capsule.payload.documents) {\n      if (!isPlainObject(rawDoc)) continue;\n      const title = String(rawDoc.title || rawDoc.name || 'Partner Document').trim();\n      const content = String(rawDoc.content || rawDoc.summary || title).trim();\n      documents.push({\n        title: `[${sourceLabel}] ${title}`.slice(0, 380),\n        content: content.slice(0, 190000),\n        type: 'other',\n        status: 'completed',\n        clientName: sourceLabel,\n      });\n    }\n  }\n\n  const combinedNotes = [\n    ...(Array.isArray(capsule.payload.strategicNotes) ? capsule.payload.strategicNotes : []),\n    ...(Array.isArray(capsule.payload.notes) ? capsule.payload.notes : []),\n  ];\n  for (const note of combinedNotes) {\n    const parsed = extractNoteText(note);\n    if (!parsed.content) continue;\n    smartNotes.push({\n      title: `[${sourceLabel}] ${parsed.title}`.slice(0, 280),\n      insights: parsed.content,\n    });\n  }\n\n  return { tasks, assets, documents, smartNotes };\n}\n", "import express from \"express\";\nimport { randomUUID } from \"node:crypto\";\nimport type { Firestore } from \"firebase-admin/firestore\";\nimport {\n  extractBridgeToken,\n  sanitizeFirestoreDocId,\n  tokensMatchConstantTime,\n} from \"../lib/bridgeSecurity.js\";\nimport {\n  buildDefaultAgreementCatalog,\n  inboundEventToIncomingOrderQuote,\n  normalizeAgreementCatalogInput,\n  signTimestampedPayload,\n  type StorefrontAgreementCatalog,\n  type StorefrontInboundEvent,\n  validateSafeStorefrontUrl,\n  validateStorefrontInboundEvent,\n  verifyTimestampedHmacSignature,\n} from \"../lib/storefrontBridge.js\";\nimport {\n  auditStudioInventory,\n  buildSkuBomCatalog,\n  evaluateCollectionAndFormulationCogs,\n  evaluateIncomingOrderOrQuote,\n  STUDIO_PRICING_RULES,\n} from \"../lib/studioOperations.js\";\nimport { generateFrenchPackagingPack } from \"../lib/quebecCompliance.js\";\nimport { runHeadlessStudioLeadIntake } from \"./agentServiceServer.js\";\nimport type { IncomingOrderQuote, OutboundStudioEvent } from \"../types.js\";\n\nconst DEFAULT_STOREFRONT_URL = \"https://staging.ljwellness.net\";\nconst DEFAULT_APP_NAME = \"Artisan 2nd Brain (LJWellness)\";\nconst CONFIG_COLLECTION = \"storefront_config\";\nconst CATALOG_DOC_ID = \"catalog_v1\";\nconst STAGING_COLLECTION = \"storefront_staging_events\";\nconst PRODUCTION_COLLECTION = \"storefront_events\";\nconst INCOMING_ORDERS_COLLECTION = \"incoming_orders\";\nconst OUTBOUND_EVENTS_COLLECTION = \"outbound_events\";\n\nclass PersistenceUnavailableError extends Error {\n  constructor() {\n    super(\"Firestore persistence is unavailable.\");\n    this.name = \"PersistenceUnavailableError\";\n  }\n}\n\nfunction isPersistenceUnavailableError(error: unknown): error is PersistenceUnavailableError {\n  return error instanceof PersistenceUnavailableError;\n}\n\nexport interface StorefrontRouterDeps {\n  getDb: () => Firestore;\n  resolveOwnerUid: (db: Firestore) => Promise<string | null>;\n  requireStudioOwner: express.RequestHandler;\n  getWorkshopSnapshot?: () => any;\n  setWorkshopSnapshot?: (snapshot: any) => void;\n}\n\nexport interface StoredStorefrontEventRecord {\n  id: string;\n  idempotencyKey: string;\n  environment: \"staging\" | \"production\";\n  eventType: StorefrontInboundEvent[\"eventType\"];\n  track: StorefrontInboundEvent[\"track\"];\n  referenceCode: string;\n  occurredAt: string;\n  receivedAt: string;\n  contactSummary: {\n    firmName?: string;\n    contactName: string;\n    email: string;\n    partnerRole?: string;\n  };\n  locale: \"en\" | \"fr\" | \"bilingual\";\n  province?: string;\n  fulfillmentPreference?: \"bulk_studio\" | \"direct_homeowner\";\n  targetDeliveryWindow?: string;\n  lineItems: StorefrontInboundEvent[\"lineItems\"];\n  subtotalCad: number;\n  discountCad: number;\n  taxBreakdown: StorefrontInboundEvent[\"taxBreakdown\"];\n  totalCad: number;\n  coBrandingOptions: string[];\n  requestSampleKit: boolean;\n  sanitizedNotes: string;\n  healthNotesRedacted: boolean;\n  crmLeadCreated: boolean;\n  isolatedToSandbox: boolean;\n}\n\nexport function createStorefrontRouter({\n  getDb,\n  resolveOwnerUid,\n  requireStudioOwner,\n  getWorkshopSnapshot,\n  setWorkshopSnapshot,\n}: StorefrontRouterDeps): express.Router {\n  const router = express.Router();\n\n  // In-memory mirrors for instant deduplication and resilient local preview operation\n  let memoryCatalog: StorefrontAgreementCatalog = buildDefaultAgreementCatalog();\n  let localSnapshot: any = null;\n  const memoryStagingEvents = new Map<string, StoredStorefrontEventRecord>();\n  const memoryProductionEvents = new Map<string, StoredStorefrontEventRecord>();\n  const memoryIncomingOrders = new Map<string, IncomingOrderQuote>();\n  const memoryOutboundQueue = new Map<string, OutboundStudioEvent>();\n\n  const readSnapshot = () => (getWorkshopSnapshot ? getWorkshopSnapshot() : localSnapshot) || {};\n  const writeSnapshot = (snap: any) => {\n    localSnapshot = snap;\n    if (setWorkshopSnapshot) setWorkshopSnapshot(snap);\n  };\n\n  const getStorefrontUrl = () =>\n    (process.env.STOREFRONT_URL || DEFAULT_STOREFRONT_URL).trim().replace(/\\/+$/, \"\");\n\n  const getStorefrontKey = () =>\n    (process.env.STOREFRONT_BRIDGE_KEY || process.env.BRIDGE_INBOUND_KEY || \"\").trim();\n\n  const getStorefrontHmacSecret = () =>\n    (process.env.STOREFRONT_HMAC_SECRET || process.env.BRIDGE_HMAC_SECRET || \"\").trim();\n\n  const inferTargetEnv = (url: string): \"staging\" | \"production\" => {\n    try {\n      const parsed = new URL(url);\n      if (parsed.hostname.toLowerCase().startsWith(\"staging.\")) return \"staging\";\n      return \"production\";\n    } catch {\n      return \"staging\";\n    }\n  };\n\n  async function loadAgreedCatalog(): Promise<StorefrontAgreementCatalog> {\n    try {\n      const db = getDb();\n      const snap = await db.collection(CONFIG_COLLECTION).doc(CATALOG_DOC_ID).get();\n      if (snap.exists) {\n        const parsed = normalizeAgreementCatalogInput(snap.data());\n        if (parsed.valid && parsed.catalog) {\n          memoryCatalog = parsed.catalog;\n          return parsed.catalog;\n        }\n      }\n    } catch {\n      if (process.env.NODE_ENV === \"production\") {\n        throw new PersistenceUnavailableError();\n      }\n    }\n    return memoryCatalog;\n  }\n\n  async function saveAgreedCatalog(catalog: StorefrontAgreementCatalog): Promise<boolean> {\n    memoryCatalog = catalog;\n    try {\n      const db = getDb();\n      const ownerUid = await resolveOwnerUid(db);\n      await db\n        .collection(CONFIG_COLLECTION)\n        .doc(CATALOG_DOC_ID)\n        .set({\n          ...catalog,\n          uid: ownerUid || \"unassigned\",\n        });\n      return true;\n    } catch {\n      return false;\n    }\n  }\n\n  async function loadLiveWorkshopContext(): Promise<any> {\n    const base = readSnapshot() || {};\n    if (Array.isArray(base.inventory) && base.inventory.length > 0) {\n      return base;\n    }\n    try {\n      const db = getDb();\n      const ownerUid = await resolveOwnerUid(db);\n      if (!ownerUid) return base;\n      const [invSnap, formSnap, colSnap, batchSnap, vendorSnap] = await Promise.all([\n        db.collection(\"inventory\").where(\"uid\", \"==\", ownerUid).limit(100).get(),\n        db.collection(\"formulations\").where(\"uid\", \"==\", ownerUid).limit(50).get(),\n        db.collection(\"collections\").where(\"uid\", \"==\", ownerUid).limit(30).get(),\n        db.collection(\"production_batches\").where(\"uid\", \"==\", ownerUid).limit(50).get(),\n        db.collection(\"vendors\").where(\"uid\", \"==\", ownerUid).limit(30).get(),\n      ]);\n      const loaded = {\n        ...base,\n        inventory: !invSnap.empty ? invSnap.docs.map((d) => ({ id: d.id, ...d.data() })) : base.inventory || [],\n        formulations: !formSnap.empty ? formSnap.docs.map((d) => ({ id: d.id, ...d.data() })) : base.formulations || [],\n        collections: !colSnap.empty ? colSnap.docs.map((d) => ({ id: d.id, ...d.data() })) : base.collections || [],\n        productionBatches: !batchSnap.empty ? batchSnap.docs.map((d) => ({ id: d.id, ...d.data() })) : base.productionBatches || [],\n        sourcing: {\n          vendors: !vendorSnap.empty ? vendorSnap.docs.map((d) => ({ id: d.id, ...d.data() })) : base.sourcing?.vendors || [],\n          purchaseOrders: base.sourcing?.purchaseOrders || [],\n        },\n        incomingOrders: Array.from(memoryIncomingOrders.values()),\n        outboundQueue: Array.from(memoryOutboundQueue.values()),\n      };\n      writeSnapshot(loaded);\n      return loaded;\n    } catch {\n      if (process.env.NODE_ENV === \"production\") {\n        throw new PersistenceUnavailableError();\n      }\n      return {\n        ...base,\n        incomingOrders: Array.from(memoryIncomingOrders.values()),\n        outboundQueue: Array.from(memoryOutboundQueue.values()),\n      };\n    }\n  }\n\n  async function buildReferenceDataBundle() {\n    const [catalog, snapshot] = await Promise.all([loadAgreedCatalog(), loadLiveWorkshopContext()]);\n    const standardizedInventory = auditStudioInventory(snapshot.inventory || []);\n    const skuBomCatalog = buildSkuBomCatalog(catalog, snapshot.formulations || []);\n    const cogsSummary = evaluateCollectionAndFormulationCogs(snapshot, catalog);\n    return {\n      skuBomCatalog,\n      standardizedInventory,\n      pricingRules: STUDIO_PRICING_RULES,\n      cogsSummary,\n    };\n  }\n\n  const requireStorefrontPartnerAuth: express.RequestHandler = (req, res, next) => {\n    const expectedKey = getStorefrontKey();\n    if (!expectedKey) {\n      return res.status(503).json({\n        accepted: false,\n        error: \"STOREFRONT_BRIDGE_KEY is not configured on StudioOS server.\",\n      });\n    }\n\n    const providedToken = extractBridgeToken(req.headers);\n    if (!tokensMatchConstantTime(providedToken, expectedKey)) {\n      return res.status(401).json({\n        accepted: false,\n        error: \"Unauthorized: Invalid or missing X-Bridge-Key or Bearer token.\",\n      });\n    }\n\n    const hmacSecret = getStorefrontHmacSecret();\n    if (hmacSecret) {\n      const rawBody: Buffer | string =\n        (req as any).rawBody instanceof Buffer\n          ? (req as any).rawBody\n          : req.method === \"GET\"\n            ? \"\"\n            : JSON.stringify(req.body ?? {});\n\n      const signatureHeader =\n        typeof req.headers[\"x-bridge-signature\"] === \"string\"\n          ? req.headers[\"x-bridge-signature\"]\n          : undefined;\n      const timestampHeader =\n        typeof req.headers[\"x-bridge-timestamp\"] === \"string\"\n          ? req.headers[\"x-bridge-timestamp\"]\n          : undefined;\n\n      const check = verifyTimestampedHmacSignature({\n        rawBody,\n        signatureHeader,\n        timestampHeader,\n        secret: hmacSecret,\n      });\n\n      if (!check.ok) {\n        return res.status(401).json({\n          accepted: false,\n          error: `Unauthorized: ${check.reason || \"Invalid HMAC signature.\"}`,\n        });\n      }\n    }\n\n    return next();\n  };\n\n  async function orchestrateIncomingOrderRecord(\n    incomingOrder: IncomingOrderQuote,\n    docKey: string,\n    isStaging: boolean,\n  ): Promise<IncomingOrderQuote> {\n    const requirePersistence = process.env.NODE_ENV === \"production\" || !isStaging;\n    const [catalog, snapshot] = await Promise.all([loadAgreedCatalog(), loadLiveWorkshopContext()]);\n    const intakeResult = await runHeadlessStudioLeadIntake(incomingOrder, snapshot, catalog);\n    const { evaluation, agentNarrative, model } = intakeResult;\n\n    const nowIso = new Date().toISOString();\n    const today = nowIso.split(\"T\")[0];\n    const toolsExecuted: string[] = [\"evaluate_order_quote_cogs\", \"check_sku_bom_and_stock\"];\n    const shortfallTaskIds: string[] = [];\n    let stagedAssetId: string | undefined;\n    let stagedDocumentId: string | undefined;\n    let complianceAssetId: string | undefined;\n    let portalSlug: string | undefined;\n    let wholesaleOrderId: string | undefined;\n\n    // 1. Always stage internal Outbound Queue items in memory (staging items stay quarantined to sandbox view)\n    const outboundQuoteId = sanitizeFirestoreDocId(`out_quote_${docKey.slice(0, 60)}`);\n    const outboundQuoteEvent: OutboundStudioEvent = {\n      id: outboundQuoteId,\n      kind: \"quote_proposal_ready\",\n      status: \"ready_for_review\",\n      sourceOrderId: incomingOrder.id,\n      referenceCode: incomingOrder.referenceCode,\n      title: `${isStaging ? \"[STAGING] \" : \"\"}Production & Costing Dossier \u2014 ${incomingOrder.client.companyName} (${incomingOrder.referenceCode})`,\n      summary: `Net $${(evaluation.netRevenueCad ?? 0).toFixed(2)} CAD | COGS $${evaluation.totalCogsCad.toFixed(2)} (${evaluation.grossMarginPct.toFixed(1)}% margin) | ${evaluation.depositPct}% Deposit $${evaluation.b2bDepositRequiredCad.toFixed(2)} CAD (Covers Direct COGS: ${evaluation.b2bDepositCoversDirectCogs ? \"YES\" : \"NO\"}) | Earliest Ship: ${evaluation.earliestPossibleDeliveryDate}`,\n      markdownContent: evaluation.stagedQuoteMarkdown,\n      depositRequiredCad: evaluation.b2bDepositRequiredCad,\n      ...(evaluation.shortfalls.length > 0 ? { shortfalls: evaluation.shortfalls } : {}),\n      externalSendAllowed: false,\n      createdAt: nowIso,\n    };\n    memoryOutboundQueue.set(outboundQuoteId, outboundQuoteEvent);\n\n    let outboundShortfallEvent: OutboundStudioEvent | null = null;\n    if (evaluation.hasShortfalls) {\n      const outboundShortId = sanitizeFirestoreDocId(`out_proc_${docKey.slice(0, 60)}`);\n      outboundShortfallEvent = {\n        id: outboundShortId,\n        kind: \"procurement_shortfall\",\n        status: \"ready_for_review\",\n        sourceOrderId: incomingOrder.id,\n        referenceCode: incomingOrder.referenceCode,\n        title: `${isStaging ? \"[STAGING] \" : \"\"}[PROCUREMENT] Material/Packaging Restock Required (${evaluation.shortfalls.length} items) \u2014 ${incomingOrder.referenceCode}`,\n        summary: evaluation.shortfalls\n          .map((s) => `${s.itemName}: short ${s.shortfallQty} ${s.unit} (~$${s.estimatedReorderCostCad.toFixed(2)}, ${s.supplierLeadDays || 7}d lead)`)\n          .join(\"; \"),\n        shortfalls: evaluation.shortfalls,\n        externalSendAllowed: false,\n        createdAt: nowIso,\n      };\n      memoryOutboundQueue.set(outboundShortId, outboundShortfallEvent);\n    }\n\n    let loi96Markdown: string | null = null;\n    if (evaluation.requiresQuebecBilingualPack) {\n      const firstLine = evaluation.lineEvaluations[0];\n      const pack = generateFrenchPackagingPack({\n        productType: /candle|melt|wax/i.test(firstLine?.productName || \"\") ? \"candle\" : /balm|butter|serum/i.test(firstLine?.productName || \"\") ? \"serum\" : \"box\",\n        productNameFr: `${firstLine?.productName || incomingOrder.referenceCode} (\u00C9dition Bilingue)`,\n        productNameEn: firstLine?.productName || incomingOrder.referenceCode,\n        netWeight: firstLine?.finishedUnitWeight || \"Selon fiche technique / Metric Spec\",\n        scentNotesFr: incomingOrder.projectDetails?.scentProfile || \"C\u00E8dre botanique, lavande fine et pierre naturelle\",\n        scentNotesEn: incomingOrder.projectDetails?.scentProfile || \"Botanical cedarwood, lavender & natural stone\",\n        inciList: \"Olea Europaea Fruit Oil, Butyrospermum Parkii Butter, Cocos Nucifera Oil, Ricinus Communis Seed Oil\",\n        companyAndAddress: \"LJWellness Atelier \u00B7 Montr\u00E9al, QC, Canada\",\n      });\n      loi96Markdown = `# QUEBEC LOI 96 / OQLF & HEALTH CANADA COMPLIANCE PACK \u2014 ${incomingOrder.referenceCode}\\n\\n## 1. \u00C9tiquette Bilingue\\n\\`\\`\\`\\n${pack.bilingualPackageLabel}\\n\\`\\`\\`\\n\\n## 2. Carte d'Accompagnement (FR)\\n\\`\\`\\`\\n${pack.frenchOnlyCareCard}\\n\\`\\`\\`\\n\\n## 3. Clauses Commerciales B2B (Qu\u00E9bec)\\n\\`\\`\\`\\n${pack.b2bFrenchQuoteClause}\\n\\`\\`\\``;\n    }\n\n    if (evaluation.requiresDevelopmentPortal) {\n      const slugBase = (incomingOrder.projectDetails?.developmentName || incomingOrder.client.companyName || incomingOrder.referenceCode)\n        .toLowerCase()\n        .replace(/[^a-z0-9]+/g, \"-\")\n        .replace(/^-+|-+$/g, \"\")\n        .slice(0, 60);\n      portalSlug = `${slugBase}-${incomingOrder.referenceCode.toLowerCase().replace(/[^a-z0-9]/g, \"\").slice(-4)}`;\n    }\n\n    let outboundComplianceEvent: OutboundStudioEvent | null = null;\n    if (loi96Markdown || portalSlug) {\n      const outboundCompId = sanitizeFirestoreDocId(`out_comp_${docKey.slice(0, 60)}`);\n      outboundComplianceEvent = {\n        id: outboundCompId,\n        kind: \"portal_and_compliance_ready\",\n        status: \"ready_for_review\",\n        sourceOrderId: incomingOrder.id,\n        referenceCode: incomingOrder.referenceCode,\n        title: `${isStaging ? \"[STAGING] \" : \"\"}Compliance & QR Fulfillment Prep \u2014 ${incomingOrder.referenceCode}`,\n        summary: [\n          loi96Markdown ? \"Quebec Loi 96 / OQLF Bilingual Pack Staged\" : null,\n          portalSlug ? `QR Portal Spec Draft (/portal/${portalSlug})` : null,\n        ].filter(Boolean).join(\" \u00B7 \"),\n        ...(loi96Markdown ? { markdownContent: loi96Markdown } : {}),\n        ...(portalSlug ? { portalSlug } : {}),\n        externalSendAllowed: false,\n        createdAt: nowIso,\n      };\n      memoryOutboundQueue.set(outboundCompId, outboundComplianceEvent);\n    }\n\n    // 2. STRICT STAGING QUARANTINE: Only persist production records to live Firestore workshop tables!\n    if (!isStaging) {\n      try {\n        const db = getDb();\n        const ownerUid = await resolveOwnerUid(db);\n        if (!ownerUid && requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n        if (ownerUid) {\n          const batch = db.batch();\n\n          stagedAssetId = sanitizeFirestoreDocId(`sf_dossier_${docKey.slice(0, 56)}`);\n          batch.set(db.collection(\"assets\").doc(stagedAssetId), {\n            id: stagedAssetId,\n            uid: ownerUid,\n            type: \"finance\",\n            title: `Internal Production & Costing Dossier \u2014 ${incomingOrder.referenceCode}`,\n            content: evaluation.stagedQuoteMarkdown,\n            author: \"StudioLead\",\n            createdAt: today,\n          });\n          toolsExecuted.push(\"create_asset\");\n\n          stagedDocumentId = sanitizeFirestoreDocId(`sf_doc_${docKey.slice(0, 56)}`);\n          batch.set(db.collection(\"documents\").doc(stagedDocumentId), {\n            id: stagedDocumentId,\n            uid: ownerUid,\n            title: `[INTERNAL DRAFT] Quote & Costing Dossier \u2014 ${incomingOrder.client.companyName} (${incomingOrder.referenceCode})`,\n            type: \"quote\",\n            status: \"draft\",\n            clientName: incomingOrder.client.companyName,\n            clientEmail: incomingOrder.client.email,\n            amount: evaluation.netRevenueCad ?? incomingOrder.payment?.subtotal ?? 0,\n            content: evaluation.stagedQuoteMarkdown,\n            createdAt: today,\n            updatedAt: today,\n          });\n\n          // Arty Review Task linked to referenceCode & idempotencyKey\n          const reviewTaskId = sanitizeFirestoreDocId(`sf_arty_${docKey.slice(0, 56)}`);\n          batch.set(db.collection(\"tasks\").doc(reviewTaskId), {\n            id: reviewTaskId,\n            uid: ownerUid,\n            title: `[Arty Review] ${incomingOrder.requestType === \"paid_order\" ? \"Verified Paid Order\" : \"Quote Dossier\"}: ${incomingOrder.referenceCode} (${incomingOrder.client.companyName})`,\n            description: `Idempotency: ${incomingOrder.idempotencyKey} | Net: $${(evaluation.netRevenueCad ?? 0).toFixed(2)} CAD | COGS: $${evaluation.totalCogsCad.toFixed(2)} (${evaluation.grossMarginPct.toFixed(1)}%) | ${evaluation.depositPct}% Deposit: $${evaluation.b2bDepositRequiredCad.toFixed(2)} | Earliest Ship: ${evaluation.earliestPossibleDeliveryDate}. Internal review only \u2014 DO NOT send externally.`,\n            assignedTo: \"StudioLead\",\n            status: \"pending\",\n            priority: \"high\",\n            createdAt: today,\n          });\n          toolsExecuted.push(\"create_task\");\n\n          // Shortfall Procurement Alert Task (without deducting stock!)\n          if (evaluation.hasShortfalls) {\n            const procTaskId = sanitizeFirestoreDocId(`sf_proc_${docKey.slice(0, 56)}`);\n            shortfallTaskIds.push(procTaskId);\n            batch.set(db.collection(\"tasks\").doc(procTaskId), {\n              id: procTaskId,\n              uid: ownerUid,\n              title: `[PROCUREMENT] Restock Required for ${incomingOrder.referenceCode} (${evaluation.shortfalls.length} items)`,\n              description: evaluation.shortfalls\n                .map((s) => `${s.itemName}: Short ${s.shortfallQty} ${s.unit} (Avail ${s.availableQty}, Need ${s.requiredQty}) \u2014 Est. $${s.estimatedReorderCostCad.toFixed(2)} CAD via ${s.suggestedVendor || \"Vendor\"} (${s.supplierLeadDays || 7}d lead)`)\n                .join(\"\\n\"),\n              assignedTo: \"Business\",\n              status: \"pending\",\n              priority: \"high\",\n              createdAt: today,\n            });\n          }\n\n          // Tentative or locked cure/ship event on Studio Planner\n          const evtId = sanitizeFirestoreDocId(`sf_evt_${docKey.slice(0, 56)}`);\n          batch.set(db.collection(\"events\").doc(evtId), {\n            id: evtId,\n            uid: ownerUid,\n            title: `${incomingOrder.requestType === \"paid_order\" ? \"[PO Cure Target]\" : \"[Tentative Quote Ship]\"} ${incomingOrder.referenceCode} (${incomingOrder.client.companyName})`,\n            date: evaluation.earliestPossibleDeliveryDate,\n            type: \"wholesale-deadline\",\n            category: \"General\",\n            description: `Earliest safe ship date (${evaluation.maxCureTimeDays}d cure). Internal staging only.`,\n          });\n          toolsExecuted.push(\"add_event\");\n\n          // Compliance pack asset if Quebec / French / Bilingual\n          if (loi96Markdown) {\n            complianceAssetId = sanitizeFirestoreDocId(`sf_loi96_${docKey.slice(0, 56)}`);\n            batch.set(db.collection(\"assets\").doc(complianceAssetId), {\n              id: complianceAssetId,\n              uid: ownerUid,\n              type: \"legal\",\n              title: `Quebec Loi 96 / OQLF Bilingual Pack \u2014 ${incomingOrder.referenceCode}`,\n              content: loi96Markdown,\n              author: \"Formulator\",\n              createdAt: today,\n            });\n            toolsExecuted.push(\"generate_french_compliance_pack\");\n          }\n\n          // Portal draft if B2B development run\n          if (portalSlug && incomingOrder.projectDetails) {\n            const portalId = sanitizeFirestoreDocId(`sf_portal_${docKey.slice(0, 56)}`);\n            batch.set(db.collection(\"portals\").doc(portalId), {\n              id: portalId,\n              uid: ownerUid,\n              slug: portalSlug,\n              developmentName: incomingOrder.projectDetails.developmentName || `${incomingOrder.client.companyName} Handover`,\n              developerName: incomingOrder.client.companyName,\n              addressOrLocation: incomingOrder.projectDetails.addressOrLocation || incomingOrder.client.city || incomingOrder.province || \"Canada\",\n              unitCount: incomingOrder.projectDetails.unitCount || evaluation.totalUnits,\n              boxEdition: \"Uniform Development QR\",\n              audienceMode: incomingOrder.projectDetails.audienceMode || \"homeowner\",\n              welcomeTitle: `Welcome Home \u2014 ${incomingOrder.projectDetails.developmentName || incomingOrder.client.companyName}`,\n              welcomeNote: \"Curated botanical & architectural handover care portal prepared internally for developer approval.\",\n              published: false,\n              scentProfile: incomingOrder.projectDetails.scentProfile || \"Pacific Cedar & Botanical Lavender\",\n              botanicalCareNote: \"Small-batch cold-cured botanicals.\",\n              conciergeEmail: \"concierge@ljwellness.net\",\n              conciergePhone: \"\",\n              propertyManagerName: incomingOrder.client.contactPerson,\n              propertyManagerContact: incomingOrder.client.email,\n              emergencyContacts: [],\n              applianceAndFinishSpecs: [],\n              seasonalChecklist: [],\n              createdAt: today,\n              updatedAt: today,\n            });\n            toolsExecuted.push(\"create_development_portal\");\n          }\n\n          // Split Mode Enforcement: Paid Order -> record PO + verified revenue + HITL ProposedActions (NEVER unapproved inventory deduction!)\n          if (incomingOrder.requestType === \"paid_order\" && incomingOrder.payment?.verifiedOnServer) {\n            wholesaleOrderId = sanitizeFirestoreDocId(`sf_wo_${docKey.slice(0, 56)}`);\n            batch.set(db.collection(\"wholesale_orders\").doc(wholesaleOrderId), {\n              id: wholesaleOrderId,\n              uid: ownerUid,\n              clientId: incomingOrder.client.companyName,\n              items: incomingOrder.lineItems.map((li) => ({\n                item: li.productName,\n                quantity: li.quantity,\n                price: li.unitPrice || 0,\n              })),\n              status: \"pending\",\n              date: today,\n              total: evaluation.netRevenueCad ?? incomingOrder.payment.subtotal,\n            });\n            toolsExecuted.push(\"create_wholesale_order\");\n\n            if (incomingOrder.payment.depositAmount > 0 || incomingOrder.payment.subtotal > 0) {\n              const txId = sanitizeFirestoreDocId(`sf_tx_${docKey.slice(0, 56)}`);\n              batch.set(db.collection(\"transactions\").doc(txId), {\n                id: txId,\n                uid: ownerUid,\n                type: \"in\",\n                amount: incomingOrder.payment.depositAmount > 0 ? incomingOrder.payment.depositAmount : incomingOrder.payment.subtotal,\n                desc: `Verified Storefront Payment (${incomingOrder.referenceCode}) \u2014 ${incomingOrder.client.companyName}`,\n                date: today,\n              });\n              toolsExecuted.push(\"update_finance\");\n            }\n\n            // Stage HITL ProposedAction so Myrna approves batch pour & inventory deduction before physical stock moves\n            const hitlBatchId = sanitizeFirestoreDocId(`sf_pa_${docKey.slice(0, 56)}`);\n            batch.set(db.collection(\"proposed_actions\").doc(hitlBatchId), {\n              id: hitlBatchId,\n              uid: ownerUid,\n              agent: \"Formulator\",\n              tool: \"create_batch\",\n              args: {\n                collectionId: incomingOrder.lineItems[0]?.sku || \"B2B-SUITE\",\n                recipeId: evaluation.lineEvaluations[0]?.formulationId || evaluation.lineEvaluations[0]?.formulationName || \"Seasalt & Pacific Brine Bar\",\n                batchNumber: `LOT-${incomingOrder.referenceCode}`,\n                quantity: evaluation.totalUnitsToProduce || evaluation.totalUnits,\n                notes: `HITL Approval Required before pouring/deducting materials for ${incomingOrder.referenceCode}.`,\n              },\n              status: \"pending\",\n              timestamp: nowIso,\n            });\n          }\n\n          batch.set(db.collection(OUTBOUND_EVENTS_COLLECTION).doc(outboundQuoteId), {\n            ...outboundQuoteEvent,\n            uid: ownerUid,\n          });\n          if (outboundShortfallEvent) {\n            batch.set(db.collection(OUTBOUND_EVENTS_COLLECTION).doc(outboundShortfallEvent.id), {\n              ...outboundShortfallEvent,\n              uid: ownerUid,\n            });\n          }\n          if (outboundComplianceEvent) {\n            batch.set(db.collection(OUTBOUND_EVENTS_COLLECTION).doc(outboundComplianceEvent.id), {\n              ...outboundComplianceEvent,\n              uid: ownerUid,\n            });\n          }\n\n          await batch.commit();\n        }\n      } catch (err) {\n        if (requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n        console.warn(\"Storefront production orchestration Firestore write skipped:\", err);\n      }\n    }\n\n    const enriched: IncomingOrderQuote = {\n      ...incomingOrder,\n      status: isStaging\n        ? \"sandbox_isolated\"\n        : evaluation.hasShortfalls\n          ? \"shortfall_blocked\"\n          : incomingOrder.requestType === \"paid_order\"\n            ? \"executed_order\"\n            : \"staged_quote\",\n      evaluation,\n      orchestrationSummary: {\n        processedAt: nowIso,\n        model,\n        toolsExecuted,\n        agentNarrative,\n        externalEmailsSent: false,\n        ...(stagedAssetId ? { stagedAssetId } : {}),\n        ...(stagedDocumentId ? { stagedDocumentId } : {}),\n        ...(complianceAssetId ? { complianceAssetId } : {}),\n        ...(portalSlug ? { portalSlug } : {}),\n        ...(shortfallTaskIds.length > 0 ? { shortfallTaskIds } : {}),\n        ...(wholesaleOrderId ? { wholesaleOrderId } : {}),\n      },\n    };\n\n    if (!isStaging) {\n      try {\n        const db = getDb();\n        const ownerUid = await resolveOwnerUid(db);\n        if (ownerUid) {\n          await db.collection(INCOMING_ORDERS_COLLECTION).doc(docKey).set({\n            ...enriched,\n            uid: ownerUid,\n          });\n        } else if (requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n      } catch (error) {\n        if (requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n        console.warn(\"Storefront incoming order was not persisted:\", error);\n      }\n    }\n\n    memoryIncomingOrders.set(docKey, enriched);\n    return enriched;\n  }\n\n  async function ingestStorefrontEvent(\n    event: StorefrontInboundEvent,\n  ): Promise<{\n    deduplicated: boolean;\n    isolatedToSandbox: boolean;\n    crmLeadCreated: boolean;\n    record: StoredStorefrontEventRecord;\n    incomingOrder?: IncomingOrderQuote;\n  }> {\n    const docKey = sanitizeFirestoreDocId(event.idempotencyKey);\n    const isStaging = event.environment === \"staging\";\n    const requirePersistence = process.env.NODE_ENV === \"production\" || !isStaging;\n    const targetMap = isStaging ? memoryStagingEvents : memoryProductionEvents;\n    const collectionName = isStaging ? STAGING_COLLECTION : PRODUCTION_COLLECTION;\n\n    const memHit = targetMap.get(docKey);\n    if (memHit) {\n      return {\n        deduplicated: true,\n        isolatedToSandbox: isStaging,\n        crmLeadCreated: memHit.crmLeadCreated,\n        record: memHit,\n        incomingOrder: memoryIncomingOrders.get(docKey),\n      };\n    }\n\n    let db: Firestore | null = null;\n    try {\n      db = getDb();\n      const existingSnap = await db.collection(collectionName).doc(docKey).get();\n      if (existingSnap.exists) {\n        const existingData = existingSnap.data() as StoredStorefrontEventRecord;\n        targetMap.set(docKey, existingData);\n        return {\n          deduplicated: true,\n          isolatedToSandbox: isStaging,\n          crmLeadCreated: Boolean(existingData.crmLeadCreated),\n          record: existingData,\n          incomingOrder: memoryIncomingOrders.get(docKey),\n        };\n      }\n    } catch {\n      if (requirePersistence) {\n        throw new PersistenceUnavailableError();\n      }\n      db = null;\n    }\n    if (!db && requirePersistence) {\n      throw new PersistenceUnavailableError();\n    }\n\n    const nowIso = new Date().toISOString();\n    const today = nowIso.split(\"T\")[0];\n    let crmLeadCreated = false;\n\n    // STRICT STAGING ISOLATION: Never mutate live corporate_accounts for staging payloads!\n    if (!isStaging && db && event.eventType !== \"ping\") {\n      try {\n        const ownerUid = await resolveOwnerUid(db);\n        if (!ownerUid && requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n        if (ownerUid) {\n          const itemSummary = event.lineItems\n            .map((li) => `${li.qty}x ${li.name}${li.sku ? ` [${li.sku}]` : \"\"} ($${li.unitPriceCad.toFixed(2)})`)\n            .join(\", \");\n\n          if (event.track === \"b2b\" && (event.eventType === \"b2b_inquiry\" || event.eventType === \"b2b_sample_request\")) {\n            const acctId = `sf_b2b_${docKey.slice(0, 60)}`;\n            await db.collection(\"corporate_accounts\").doc(acctId).set({\n              id: acctId,\n              uid: ownerUid,\n              companyName: event.contact.firmName || event.contact.contactName,\n              contactPerson: event.contact.contactName,\n              email: event.contact.email,\n              phone: event.contact.phone || \"\",\n              accountType:\n                event.contact.partnerRole === \"Architect\" || event.contact.partnerRole === \"Interior Designer\"\n                  ? \"Architecture / Design\"\n                  : event.contact.partnerRole === \"Condo Developer\"\n                    ? \"Condo Developer\"\n                    : \"Luxury Builder\",\n              nicheFocus: `${event.referenceCode} (${event.fulfillmentPreference || \"bulk_studio\"})`,\n              annualBudgetPotential: event.totalCad,\n              status: event.requestSampleKit ? \"Sample Sent\" : \"Lead\",\n              notes: [\n                `[Storefront Sync] Ref: ${event.referenceCode}`,\n                `Locale: ${event.locale.toUpperCase()} | Est. Total: $${event.totalCad.toFixed(2)} CAD`,\n                itemSummary ? `Items: ${itemSummary}` : null,\n                event.coBrandingOptions.length > 0\n                  ? `Co-Branding: ${event.coBrandingOptions.join(\", \")}`\n                  : null,\n                event.sanitizedNotes ? `Notes: ${event.sanitizedNotes}` : null,\n              ]\n                .filter(Boolean)\n                .join(\"\\n\"),\n              createdAt: today,\n              updatedAt: today,\n            });\n            crmLeadCreated = true;\n          }\n        }\n      } catch (err) {\n        if (requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n        console.warn(\"Storefront production CRM sync skipped (Firestore unavailable):\", err);\n      }\n    }\n\n    let incomingOrder: IncomingOrderQuote | undefined;\n    if (event.eventType !== \"ping\") {\n      const converted = inboundEventToIncomingOrderQuote(event, docKey);\n      incomingOrder = await orchestrateIncomingOrderRecord(converted, docKey, isStaging);\n    }\n\n    const record: StoredStorefrontEventRecord = {\n      id: docKey,\n      idempotencyKey: event.idempotencyKey,\n      environment: event.environment,\n      eventType: event.eventType,\n      track: event.track,\n      referenceCode: event.referenceCode,\n      occurredAt: event.occurredAt,\n      receivedAt: nowIso,\n      contactSummary: {\n        ...(event.contact.firmName ? { firmName: event.contact.firmName } : {}),\n        contactName: event.contact.contactName,\n        email: event.contact.email,\n        ...(event.contact.partnerRole ? { partnerRole: event.contact.partnerRole } : {}),\n      },\n      locale: event.locale,\n      ...(event.province ? { province: event.province } : {}),\n      ...(event.fulfillmentPreference ? { fulfillmentPreference: event.fulfillmentPreference } : {}),\n      ...(event.targetDeliveryWindow ? { targetDeliveryWindow: event.targetDeliveryWindow } : {}),\n      lineItems: event.lineItems,\n      subtotalCad: event.subtotalCad,\n      discountCad: event.discountCad,\n      taxBreakdown: event.taxBreakdown,\n      totalCad: event.totalCad,\n      coBrandingOptions: event.coBrandingOptions,\n      requestSampleKit: event.requestSampleKit,\n      sanitizedNotes: event.sanitizedNotes,\n      healthNotesRedacted: event.healthNotesRedacted,\n      crmLeadCreated,\n      isolatedToSandbox: isStaging,\n    };\n\n    if (db) {\n      try {\n        const ownerUid = await resolveOwnerUid(db);\n        if (!ownerUid && requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n        await db\n          .collection(collectionName)\n          .doc(docKey)\n          .set({\n            ...record,\n            uid: ownerUid || \"unassigned\",\n          });\n      } catch {\n        if (requirePersistence) {\n          throw new PersistenceUnavailableError();\n        }\n      }\n    } else if (requirePersistence) {\n      throw new PersistenceUnavailableError();\n    }\n\n    targetMap.set(docKey, record);\n    return {\n      deduplicated: false,\n      isolatedToSandbox: isStaging,\n      crmLeadCreated,\n      record,\n      incomingOrder,\n    };\n  }\n\n  function buildOutboundStorefrontHeaders(rawBody: string): Record<string, string> {\n    const key = getStorefrontKey();\n    const headers: Record<string, string> = {\n      \"Content-Type\": \"application/json\",\n      \"X-Bridge-Key\": key,\n      Authorization: `Bearer ${key}`,\n    };\n    const secret = getStorefrontHmacSecret();\n    if (secret) {\n      const signed = signTimestampedPayload(rawBody, secret);\n      headers[\"X-Bridge-Timestamp\"] = signed.timestamp;\n      headers[\"X-Bridge-Signature\"] = signed.signature;\n    }\n    return headers;\n  }\n\n  // =========================================================================\n  // 1. PUBLIC HEALTH ENDPOINT (GET /api/storefront/health)\n  // =========================================================================\n  router.get(\"/health\", (_req, res) => {\n    const configuredUrl = getStorefrontUrl();\n    res.json({\n      status: \"ok\",\n      app: DEFAULT_APP_NAME,\n      protocol: \"ljw-storefront-v1\",\n      targetEnvironment: inferTargetEnv(configuredUrl),\n      endpoints: {\n        health: \"/api/storefront/health\",\n        inbound: \"/api/storefront/inbound\",\n        catalog: \"/api/storefront/catalog\",\n        referenceData: \"/api/storefront/reference-data\",\n      },\n      security: {\n        keyHeader: \"X-Bridge-Key\",\n        timestampHeader: \"X-Bridge-Timestamp\",\n        signatureHeader: \"X-Bridge-Signature\",\n        replayWindowSeconds: 300,\n        keyConfigured: Boolean(getStorefrontKey()),\n        hmacConfigured: Boolean(getStorefrontHmacSecret()),\n        piiHealthMinimization: true,\n        stagingIsolationEnforced: true,\n        zeroExternalClientContact: true,\n      },\n      timestamp: new Date().toISOString(),\n    });\n  });\n\n  // =========================================================================\n  // 4C. OWNER-ONLY, NON-PERSISTING COSTING PREVIEW (POST /api/storefront/evaluate-preview)\n  // =========================================================================\n  router.post(\"/evaluate-preview\", requireStudioOwner, async (req, res) => {\n    try {\n      const input = req.body && typeof req.body === \"object\" ? req.body : {};\n      const tool = input.tool;\n      if (tool !== \"evaluate_order_quote_cogs\" && tool !== \"check_sku_bom_and_stock\") {\n        return res.status(400).json({ error: \"Unsupported studio evaluation tool.\" });\n      }\n\n      const defaultQuantity = tool === \"evaluate_order_quote_cogs\" ? 10 : 1;\n      const quantity =\n        input.quantity === undefined ? defaultQuantity : Number(input.quantity);\n      if (!Number.isSafeInteger(quantity) || quantity < 1 || quantity > 100000) {\n        return res.status(400).json({ error: \"Quantity must be a whole number between 1 and 100000.\" });\n      }\n\n      if (input.sku !== undefined && (typeof input.sku !== \"string\" || input.sku.length > 100)) {\n        return res.status(400).json({ error: \"SKU must be a string of 100 characters or fewer.\" });\n      }\n\n      const sku = typeof input.sku === \"string\" ? input.sku.trim().slice(0, 100) : \"\";\n      const [catalog, snapshot] = await Promise.all([loadAgreedCatalog(), loadLiveWorkshopContext()]);\n      let order: IncomingOrderQuote;\n      let resolvedSku: string | undefined;\n\n      if (tool === \"check_sku_bom_and_stock\") {\n        const bomCatalog = buildSkuBomCatalog(catalog, snapshot.formulations || []);\n        const skuUpper = (sku || \"LJW-B2B-ARC-02\").toUpperCase();\n        const bom =\n          bomCatalog.find(\n            (entry) =>\n              entry.sku === skuUpper ||\n              entry.productName.toLowerCase().includes(skuUpper.toLowerCase()),\n          ) || bomCatalog[0];\n        if (!bom) {\n          return res.status(422).json({ error: \"No SKU/BOM entries are available for evaluation.\" });\n        }\n\n        resolvedSku = bom.sku;\n        const id = `preview_${randomUUID()}`;\n        order = {\n          id,\n          idempotencyKey: id,\n          source: \"manual\",\n          environment: \"production\",\n          requestType: \"quote_request\",\n          status: \"pending_review\",\n          referenceCode: `BOM-${bom.sku}`,\n          receivedAt: new Date().toISOString(),\n          locale: \"en\",\n          client: {\n            companyName: \"BOM Check\",\n            contactPerson: \"Studio\",\n            email: \"studio@ljwellness.net\",\n            accountType: \"Luxury Builder\",\n          },\n          lineItems: [{ sku: bom.sku, productName: bom.productName, quantity }],\n        };\n      } else {\n        if (\n          input.incomingOrderId !== undefined &&\n          (typeof input.incomingOrderId !== \"string\" || input.incomingOrderId.length > 160)\n        ) {\n          return res.status(400).json({ error: \"Incoming order ID must be a string of 160 characters or fewer.\" });\n        }\n        if (input.province !== undefined && (typeof input.province !== \"string\" || input.province.length > 80)) {\n          return res.status(400).json({ error: \"Province must be a string of 80 characters or fewer.\" });\n        }\n        if (\n          input.requestedDeliveryDate !== undefined &&\n          (typeof input.requestedDeliveryDate !== \"string\" || input.requestedDeliveryDate.length > 40)\n        ) {\n          return res.status(400).json({ error: \"Requested delivery date is invalid.\" });\n        }\n        if (\n          input.coBrandingOptions !== undefined &&\n          (!Array.isArray(input.coBrandingOptions) ||\n            input.coBrandingOptions.length > 20 ||\n            input.coBrandingOptions.some((option: unknown) => typeof option !== \"string\" || option.length > 80))\n        ) {\n          return res.status(400).json({ error: \"Co-branding options are invalid.\" });\n        }\n        const coBrandingOptions = Array.isArray(input.coBrandingOptions)\n          ? input.coBrandingOptions.filter((option: unknown): option is string => typeof option === \"string\")\n          : undefined;\n\n        const incomingOrderId =\n          typeof input.incomingOrderId === \"string\" ? input.incomingOrderId.trim() : \"\";\n        const snapshotOrders = Array.isArray(snapshot.incomingOrders) ? snapshot.incomingOrders : [];\n        let matchedOrder = incomingOrderId\n          ? [...memoryIncomingOrders.values(), ...snapshotOrders].find(\n              (candidate: IncomingOrderQuote) =>\n                candidate.id === incomingOrderId || candidate.referenceCode === incomingOrderId,\n            )\n          : undefined;\n        if (!matchedOrder && incomingOrderId) {\n          try {\n            const db = getDb();\n            const document = await db\n              .collection(INCOMING_ORDERS_COLLECTION)\n              .doc(sanitizeFirestoreDocId(incomingOrderId))\n              .get();\n            if (document.exists) {\n              matchedOrder = document.data() as IncomingOrderQuote;\n            } else {\n              const matches = await db\n                .collection(INCOMING_ORDERS_COLLECTION)\n                .where(\"referenceCode\", \"==\", incomingOrderId)\n                .limit(1)\n                .get();\n              if (!matches.empty) {\n                matchedOrder = matches.docs[0].data() as IncomingOrderQuote;\n              }\n            }\n          } catch (error) {\n            if (process.env.NODE_ENV === \"production\") {\n              throw new PersistenceUnavailableError();\n            }\n            console.warn(\"Could not load incoming order for preview:\", error);\n          }\n        }\n\n        if (matchedOrder) {\n          order = matchedOrder;\n        } else {\n          const province =\n            (typeof input.province === \"string\" ? input.province.trim() : \"\") || \"QC\";\n          const id = `preview_${randomUUID()}`;\n          order = {\n            id,\n            idempotencyKey: id,\n            source: \"manual\",\n            environment: \"production\",\n            requestType: \"quote_request\",\n            status: \"pending_review\",\n            referenceCode: incomingOrderId || `EVAL-${Date.now().toString(36).toUpperCase()}`,\n            receivedAt: new Date().toISOString(),\n            locale: province.toUpperCase() === \"QC\" ? \"bilingual\" : \"en\",\n            province,\n            client: {\n              companyName: \"Internal Studio Evaluation\",\n              contactPerson: \"Myrna\",\n              email: \"studio@ljwellness.net\",\n              accountType: \"Luxury Builder\",\n              province,\n            },\n            lineItems: [\n              {\n                sku: sku || \"LJW-B2B-ARC-02\",\n                productName: sku || \"02. The Architectural Sanctuary\",\n                quantity,\n              },\n            ],\n            ...(typeof input.requestedDeliveryDate === \"string\"\n              ? { timeline: { requestedDeliveryDate: input.requestedDeliveryDate } }\n              : {}),\n            ...(coBrandingOptions ? { coBrandingOptions } : {}),\n          };\n        }\n      }\n\n      const evaluation = evaluateIncomingOrderOrQuote(order, snapshot, catalog);\n      return res.json({\n        order: { ...order, evaluation },\n        evaluation,\n        ...(resolvedSku ? { resolvedSku } : {}),\n      });\n    } catch (error: unknown) {\n      if (isPersistenceUnavailableError(error)) {\n        return res.status(503).json({ error: \"Persistence unavailable\" });\n      }\n      console.error(\"Error in POST /api/storefront/evaluate-preview:\", error);\n      return res.status(500).json({ error: \"Could not evaluate the studio preview.\" });\n    }\n  });\n\n  // =========================================================================\n  // 2. PARTNER INBOUND WEBHOOK + HEADLESS STUDIOLEAD INTAKE (POST /api/storefront/inbound)\n  // =========================================================================\n  router.post(\"/inbound\", requireStorefrontPartnerAuth, async (req, res) => {\n    try {\n      const validation = validateStorefrontInboundEvent(req.body);\n      if (!validation.valid || !validation.event) {\n        return res.status(400).json({\n          accepted: false,\n          error: validation.error || \"Invalid storefront event payload.\",\n          issues: validation.issues || [],\n        });\n      }\n\n      const result = await ingestStorefrontEvent(validation.event);\n\n      return res.status(result.deduplicated ? 200 : 202).json({\n        accepted: true,\n        deduplicated: result.deduplicated,\n        environment: result.record.environment,\n        isolatedToSandbox: result.isolatedToSandbox,\n        crmLeadCreated: result.crmLeadCreated,\n        eventId: result.record.id,\n        referenceCode: result.record.referenceCode,\n        receivedAt: result.record.receivedAt,\n        externalEmailsSent: false,\n        dossierStatus: result.incomingOrder?.evaluation?.dossierStatus || null,\n      });\n    } catch (error: unknown) {\n      console.error(\"Error in POST /api/storefront/inbound:\", error);\n      if (isPersistenceUnavailableError(error)) {\n        return res.status(503).json({\n          accepted: false,\n          error: \"Persistence unavailable\",\n        });\n      }\n      return res.status(500).json({\n        accepted: false,\n        error: \"Internal error processing storefront inbound payload.\",\n      });\n    }\n  });\n\n  // =========================================================================\n  // 3. CANONICAL CATALOG FEED (GET /api/storefront/catalog)\n  // =========================================================================\n  router.get(\"/catalog\", async (req, res, next) => {\n    const hasPartnerHeaders = Boolean(extractBridgeToken(req.headers));\n    if (hasPartnerHeaders) {\n      return requireStorefrontPartnerAuth(req, res, next);\n    }\n    return requireStudioOwner(req, res, next);\n  }, async (_req, res) => {\n    try {\n      const catalog = await loadAgreedCatalog();\n      return res.json(catalog);\n    } catch {\n      return res.status(500).json({ error: \"Failed to load agreed catalog.\" });\n    }\n  });\n\n  // =========================================================================\n  // 3B. REFERENCE LOOKUP TABLES READ ENDPOINT (GET /api/storefront/reference-data)\n  // =========================================================================\n  router.get(\"/reference-data\", requireStudioOwner, async (_req, res) => {\n    try {\n      const bundle = await buildReferenceDataBundle();\n      return res.json(bundle);\n    } catch {\n      return res.status(500).json({ error: \"Failed to build studio reference tables.\" });\n    }\n  });\n\n  // =========================================================================\n  // 4. STUDIO OWNER DASHBOARD STATUS (GET /api/storefront/status)\n  // =========================================================================\n  router.get(\"/status\", requireStudioOwner, async (_req, res) => {\n    try {\n      const storefrontUrl = getStorefrontUrl();\n      const catalog = await loadAgreedCatalog();\n\n      let stagingEvents = Array.from(memoryStagingEvents.values());\n      let productionEvents = Array.from(memoryProductionEvents.values());\n\n      try {\n        const db = getDb();\n        const [stgSnap, prodSnap] = await Promise.all([\n          db.collection(STAGING_COLLECTION).orderBy(\"receivedAt\", \"desc\").limit(25).get(),\n          db.collection(PRODUCTION_COLLECTION).orderBy(\"receivedAt\", \"desc\").limit(25).get(),\n        ]);\n\n        if (!stgSnap.empty) {\n          stagingEvents = stgSnap.docs.map((d) => d.data() as StoredStorefrontEventRecord);\n        }\n        if (!prodSnap.empty) {\n          productionEvents = prodSnap.docs.map((d) => d.data() as StoredStorefrontEventRecord);\n        }\n      } catch {\n        // Keep sorted memory mirrors if Firestore is offline/unconfigured in preview\n      }\n\n      stagingEvents.sort((a, b) => b.receivedAt.localeCompare(a.receivedAt));\n      productionEvents.sort((a, b) => b.receivedAt.localeCompare(a.receivedAt));\n\n      return res.json({\n        protocol: \"ljw-storefront-v1\",\n        storefrontUrl,\n        targetEnvironment: inferTargetEnv(storefrontUrl),\n        ourSharedBaseUrl: (process.env.APP_URL || \"https://artisan.ljwellness.net\")\n          .trim()\n          .replace(/\\/+$/, \"\"),\n        keyConfigured: Boolean(getStorefrontKey()),\n        hmacConfigured: Boolean(getStorefrontHmacSecret()),\n        catalog,\n        stagingEvents: stagingEvents.slice(0, 25),\n        productionEvents: productionEvents.slice(0, 25),\n      });\n    } catch {\n      return res.status(500).json({ error: \"Failed to load storefront connector status.\" });\n    }\n  });\n\n  // =========================================================================\n  // 4B. OPERATIONS DOSSIER & OUTBOUND REVIEW QUEUE (GET /api/storefront/operations)\n  // =========================================================================\n  router.get(\"/operations\", requireStudioOwner, async (_req, res) => {\n    try {\n      let incomingOrders = Array.from(memoryIncomingOrders.values());\n      let outboundQueue = Array.from(memoryOutboundQueue.values());\n\n      try {\n        const db = getDb();\n        const [incSnap, outSnap] = await Promise.all([\n          db.collection(INCOMING_ORDERS_COLLECTION).orderBy(\"receivedAt\", \"desc\").limit(30).get(),\n          db.collection(OUTBOUND_EVENTS_COLLECTION).orderBy(\"createdAt\", \"desc\").limit(30).get(),\n        ]);\n\n        if (!incSnap.empty) {\n          const firestoreIncoming = incSnap.docs.map((d) => d.data() as IncomingOrderQuote);\n          for (const item of firestoreIncoming) {\n            if (!memoryIncomingOrders.has(item.id)) memoryIncomingOrders.set(item.id, item);\n          }\n          incomingOrders = Array.from(memoryIncomingOrders.values());\n        }\n        if (!outSnap.empty) {\n          const firestoreOutbound = outSnap.docs.map((d) => d.data() as OutboundStudioEvent);\n          for (const item of firestoreOutbound) {\n            if (!memoryOutboundQueue.has(item.id)) memoryOutboundQueue.set(item.id, item);\n          }\n          outboundQueue = Array.from(memoryOutboundQueue.values());\n        }\n      } catch {\n        // Use in-memory records\n      }\n\n      incomingOrders.sort((a, b) => (b.receivedAt || \"\").localeCompare(a.receivedAt || \"\"));\n      outboundQueue.sort((a, b) => (b.createdAt || \"\").localeCompare(a.createdAt || \"\"));\n      const referenceData = await buildReferenceDataBundle();\n\n      return res.json({\n        incomingOrders: incomingOrders.slice(0, 30),\n        outboundQueue: outboundQueue.slice(0, 30),\n        referenceData,\n      });\n    } catch {\n      return res.status(500).json({ error: \"Failed to load operations queue.\" });\n    }\n  });\n\n  // =========================================================================\n  // 4D. SYNC LIVE CLIENT WORKSHOP STATE TO SERVER SNAPSHOT (POST /api/storefront/sync-state)\n  // =========================================================================\n  router.post(\"/sync-state\", requireStudioOwner, async (req, res) => {\n    try {\n      if (req.body && typeof req.body === \"object\") {\n        writeSnapshot(req.body);\n      }\n      return res.json({ ok: true, syncedAt: new Date().toISOString() });\n    } catch {\n      return res.status(500).json({ ok: false, error: \"Failed to sync workshop snapshot.\" });\n    }\n  });\n\n  // =========================================================================\n  // 4E. 1-CLICK RUN/RE-RUN ARTY STUDIOLEAD INTAKE ON INCOMING ORDER (POST /api/storefront/incoming/:id/execute)\n  // =========================================================================\n  router.post(\"/incoming/:id/execute\", requireStudioOwner, async (req, res) => {\n    try {\n      const targetId = sanitizeFirestoreDocId(req.params.id || \"\");\n      let order = memoryIncomingOrders.get(targetId);\n      if (!order) {\n        try {\n          const db = getDb();\n          const snap = await db.collection(INCOMING_ORDERS_COLLECTION).doc(targetId).get();\n          if (snap.exists) {\n            order = snap.data() as IncomingOrderQuote;\n          }\n        } catch {\n          // Ignore\n        }\n      }\n      if (!order) {\n        return res.status(404).json({ error: \"Incoming order/quote not found.\" });\n      }\n      const updated = await orchestrateIncomingOrderRecord(order, targetId, order.environment === \"staging\");\n      return res.json({ ok: true, order: updated });\n    } catch (error: unknown) {\n      if (isPersistenceUnavailableError(error)) {\n        return res.status(503).json({ ok: false, error: \"Persistence unavailable\" });\n      }\n      console.error(\"Error in POST /api/storefront/incoming/:id/execute:\", error);\n      return res.status(500).json({ ok: false, error: \"Failed to execute Arty dossier review.\" });\n    }\n  });\n\n  // =========================================================================\n  // 4F. UPDATE OUTBOUND QUEUE ITEM REVIEW STATUS (POST /api/storefront/outbound/:id/status)\n  // =========================================================================\n  router.post(\"/outbound/:id/status\", requireStudioOwner, async (req, res) => {\n    try {\n      const id = sanitizeFirestoreDocId(req.params.id || \"\");\n      const status = req.body?.status;\n      if (![\"ready_for_review\", \"approved_copied\", \"resolved\"].includes(status)) {\n        return res.status(400).json({ error: \"Invalid outbound item status.\" });\n      }\n      const existing = memoryOutboundQueue.get(id);\n      if (existing) {\n        const nextItem: OutboundStudioEvent = { ...existing, status };\n        memoryOutboundQueue.set(id, nextItem);\n      }\n      try {\n        const db = getDb();\n        await db.collection(OUTBOUND_EVENTS_COLLECTION).doc(id).update({ status });\n      } catch {\n        // Ignore if Firestore unavailable\n      }\n      return res.json({ ok: true, id, status });\n    } catch {\n      return res.status(500).json({ ok: false, error: \"Failed to update outbound queue status.\" });\n    }\n  });\n\n  // =========================================================================\n  // 5. SAVE AGREED CANONICAL CATALOG (PUT /api/storefront/catalog)\n  // =========================================================================\n  router.put(\"/catalog\", requireStudioOwner, async (req, res) => {\n    try {\n      const current = await loadAgreedCatalog();\n      const validation = normalizeAgreementCatalogInput({\n        ...(req.body || {}),\n        catalogVersion: Math.max(current.catalogVersion + 1, Number(req.body?.catalogVersion) || 1),\n      });\n\n      if (!validation.valid || !validation.catalog) {\n        return res.status(400).json({ error: validation.error || \"Invalid catalog agreement.\" });\n      }\n\n      const persistedToFirestore = await saveAgreedCatalog(validation.catalog);\n      return res.json({\n        ok: true,\n        persistedToFirestore,\n        catalog: validation.catalog,\n      });\n    } catch {\n      return res.status(500).json({ error: \"Failed to save agreed catalog.\" });\n    }\n  });\n\n  // =========================================================================\n  // 6. TEST CONNECTION TO STOREFRONT (POST /api/storefront/test-connection)\n  // =========================================================================\n  router.post(\"/test-connection\", requireStudioOwner, async (req, res) => {\n    try {\n      const candidateUrl =\n        typeof req.body?.storefrontUrl === \"string\" && req.body.storefrontUrl.trim()\n          ? req.body.storefrontUrl.trim()\n          : getStorefrontUrl();\n\n      const safeUrl = validateSafeStorefrontUrl(candidateUrl);\n      if (!safeUrl.valid || !safeUrl.normalizedUrl) {\n        return res.status(400).json({\n          ok: false,\n          error: safeUrl.error || \"Invalid Storefront URL.\",\n        });\n      }\n\n      const targetHealthUrl = `${safeUrl.normalizedUrl}/api/health`;\n      const upstream = await fetch(targetHealthUrl, {\n        method: \"GET\",\n        signal: AbortSignal.timeout(8000),\n      });\n\n      const rawText = await upstream.text();\n      let parsed: any = null;\n      try {\n        parsed = JSON.parse(rawText);\n      } catch {\n        parsed = { raw: rawText.slice(0, 400) };\n      }\n\n      return res.status(upstream.ok ? 200 : 502).json({\n        ok: upstream.ok,\n        httpStatus: upstream.status,\n        targetUrl: targetHealthUrl,\n        environment: inferTargetEnv(safeUrl.normalizedUrl),\n        remote: parsed,\n      });\n    } catch (error: any) {\n      return res.status(502).json({\n        ok: false,\n        error: error?.message || \"Could not reach Storefront /api/health endpoint.\",\n      });\n    }\n  });\n\n  // =========================================================================\n  // 7. SIGNED PUSH OF AGREED CATALOG TO STOREFRONT (POST /api/storefront/push-catalog)\n  // =========================================================================\n  router.post(\"/push-catalog\", requireStudioOwner, async (req, res) => {\n    try {\n      const key = getStorefrontKey();\n      if (!key) {\n        return res.status(503).json({\n          ok: false,\n          error: \"STOREFRONT_BRIDGE_KEY is not configured in server secrets.\",\n        });\n      }\n\n      const candidateUrl =\n        typeof req.body?.storefrontUrl === \"string\" && req.body.storefrontUrl.trim()\n          ? req.body.storefrontUrl.trim()\n          : getStorefrontUrl();\n\n      const safeUrl = validateSafeStorefrontUrl(candidateUrl);\n      if (!safeUrl.valid || !safeUrl.normalizedUrl) {\n        return res.status(400).json({\n          ok: false,\n          error: safeUrl.error || \"Invalid Storefront URL.\",\n        });\n      }\n\n      const catalog = await loadAgreedCatalog();\n      const rawJson = JSON.stringify(catalog);\n      const targetUrl = `${safeUrl.normalizedUrl}/api/studio/catalog-sync`;\n\n      const upstream = await fetch(targetUrl, {\n        method: \"POST\",\n        headers: buildOutboundStorefrontHeaders(rawJson),\n        body: rawJson,\n        signal: AbortSignal.timeout(12000),\n      });\n\n      const text = await upstream.text();\n      let remote: any = {};\n      try {\n        remote = JSON.parse(text);\n      } catch {\n        remote = { raw: text.slice(0, 500) };\n      }\n\n      return res.status(upstream.ok ? 200 : upstream.status).json({\n        ok: upstream.ok,\n        httpStatus: upstream.status,\n        targetUrl,\n        catalogVersion: catalog.catalogVersion,\n        skuCount: catalog.products.length,\n        remote,\n      });\n    } catch (error: any) {\n      return res.status(502).json({\n        ok: false,\n        error: error?.message || \"Failed to push agreed catalog to Storefront.\",\n      });\n    }\n  });\n\n  // =========================================================================\n  // 8. CLEAR STAGING SANDBOX & RUN INTERNAL STAGING TEST (WITH ARTY DOSSIER)\n  // =========================================================================\n  router.post(\"/simulate-staging\", requireStudioOwner, async (req, res) => {\n    try {\n      const track: \"b2b\" | \"eczema\" | \"menopause\" =\n        req.body?.track === \"eczema\" || req.body?.track === \"menopause\" ? req.body.track : \"b2b\";\n      const suffix = Date.now().toString(36).toUpperCase();\n\n      const samplePayload =\n        track === \"b2b\"\n          ? {\n              environment: \"staging\",\n              eventType: \"b2b_inquiry\",\n              track: \"b2b\",\n              idempotencyKey: `stg_b2b_${suffix}`,\n              referenceCode: `STG-B2B-${suffix}`,\n              locale: \"bilingual\",\n              province: \"QC\",\n              fulfillmentPreference: \"bulk_studio\",\n              targetDeliveryWindow: \"Next 30 Days\",\n              contact: {\n                firmName: \"Atelier Architecture Montr\u00E9al (TEST)\",\n                contactName: \"Marc-Antoine Gagnon\",\n                email: \"staging-test@ljwellness.net\",\n                partnerRole: \"Architect\",\n              },\n              lineItems: [\n                {\n                  sku: \"LJW-B2B-ARC-02\",\n                  storefrontSlug: \"architectural-sanctuary\",\n                  variantKey: \"default\",\n                  name: \"02. The Architectural Sanctuary\",\n                  qty: 12,\n                  unitPriceCad: 165,\n                },\n              ],\n              coBrandingOptions: [\"embossed-arch-card\", \"jesmonite-color-match\"],\n              requestSampleKit: true,\n              notes: \"Staging verification ping \u2014 must remain isolated from live CRM & inventory.\",\n            }\n          : track === \"eczema\"\n            ? {\n                environment: \"staging\",\n                eventType: \"retail_preorder\",\n                track: \"eczema\",\n                idempotencyKey: `stg_ecz_${suffix}`,\n                referenceCode: `STG-ECZ-${suffix}`,\n                locale: \"fr\",\n                province: \"QC\",\n                contact: {\n                  contactName: \"Camille Tremblay (TEST)\",\n                  email: \"staging-eczema@ljwellness.net\",\n                },\n                lineItems: [\n                  {\n                    sku: \"LJW-ECZ-BALM-100\",\n                    storefrontSlug: \"oat-borage-barrier-balm\",\n                    variantKey: \"100ml\",\n                    name: \"Colloidal Oat & Borage Flare Barrier Balm (100 ml)\",\n                    qty: 2,\n                    unitPriceCad: 48,\n                  },\n                ],\n                notes: \"Flare behind knees and sensitive skin flare notes \u2014 should be redacted.\",\n              }\n            : {\n                environment: \"staging\",\n                eventType: \"retail_preorder\",\n                track: \"menopause\",\n                idempotencyKey: `stg_men_${suffix}`,\n                referenceCode: `STG-MEN-${suffix}`,\n                locale: \"en\",\n                province: \"ON\",\n                contact: {\n                  contactName: \"Nadia Roy (TEST)\",\n                  email: \"staging-menopause@ljwellness.net\",\n                },\n                lineItems: [\n                  {\n                    sku: \"LJW-MEN-MIST-100\",\n                    storefrontSlug: \"peri-cooling-mist\",\n                    variantKey: \"100ml\",\n                    name: \"Thermal Calm Mineral Facial & Neck Mist\",\n                    qty: 1,\n                    unitPriceCad: 38,\n                  },\n                ],\n                notes: \"Night sweats and perimenopause sleep notes \u2014 should be redacted.\",\n              };\n\n      const check = validateStorefrontInboundEvent(samplePayload);\n      if (!check.valid || !check.event) {\n        return res.status(400).json({ ok: false, error: check.error });\n      }\n\n      const result = await ingestStorefrontEvent(check.event);\n      return res.status(201).json({\n        ok: true,\n        isolatedToSandbox: result.isolatedToSandbox,\n        crmLeadCreated: result.crmLeadCreated,\n        record: result.record,\n        incomingOrder: result.incomingOrder,\n      });\n    } catch (error: unknown) {\n      if (isPersistenceUnavailableError(error)) {\n        return res.status(503).json({ ok: false, error: \"Persistence unavailable\" });\n      }\n      console.error(\"Error in POST /api/storefront/simulate-staging:\", error);\n      return res.status(500).json({ ok: false, error: \"Staging simulation failed.\" });\n    }\n  });\n\n  router.delete(\"/staging\", requireStudioOwner, async (_req, res) => {\n    try {\n      const count = memoryStagingEvents.size;\n      memoryStagingEvents.clear();\n      for (const [k, v] of memoryIncomingOrders.entries()) {\n        if (v.environment === \"staging\") {\n          memoryIncomingOrders.delete(k);\n        }\n      }\n      for (const [k, v] of memoryOutboundQueue.entries()) {\n        if (v.title.startsWith(\"[STAGING]\")) {\n          memoryOutboundQueue.delete(k);\n        }\n      }\n      try {\n        const db = getDb();\n        const snap = await db.collection(STAGING_COLLECTION).limit(100).get();\n        if (!snap.empty) {\n          const batch = db.batch();\n          snap.docs.forEach((d) => batch.delete(d.ref));\n          await batch.commit();\n        }\n      } catch {\n        // Ignore if Firestore unavailable\n      }\n      return res.json({ ok: true, clearedMemoryCount: count });\n    } catch {\n      return res.status(500).json({ ok: false, error: \"Failed to clear staging sandbox.\" });\n    }\n  });\n\n  return router;\n}\n", "export type ComplianceLanguage = 'en' | 'fr' | 'bilingual';\n\nexport interface QuebecComplianceRule {\n  id: string;\n  statute: string;\n  title: string;\n  authority: string;\n  summary: string;\n  requirements: string[];\n  officialUrl: string;\n  officialLabel: string;\n}\n\nexport interface FrenchLabelInput {\n  productType: 'soap' | 'candle' | 'serum' | 'box';\n  productNameFr: string;\n  productNameEn: string;\n  netWeight: string;\n  scentNotesFr: string;\n  scentNotesEn: string;\n  inciList: string;\n  companyAndAddress: string;\n}\n\nexport interface FrenchLabelOutput {\n  bilingualPackageLabel: string;\n  frenchOnlyCareCard: string;\n  safetyWarningBilingual: string;\n  b2bFrenchQuoteClause: string;\n  printableHtml: string;\n}\n\nexport const QUEBEC_COMPLIANCE_RULES: QuebecComplianceRule[] = [\n  {\n    id: 'oqlf-bill96-packaging',\n    statute: 'Charte de la langue fran\u00E7aise (Loi 96 / art. 51)',\n    title: 'Product Packaging, Labels & Enclosed Care Leaflets',\n    authority: 'Office qu\u00E9b\u00E9cois de la langue fran\u00E7aise (OQLF)',\n    summary:\n      'Every inscription on a product, vessel, specimen box, wrapping, or enclosed care leaflet sold in Quebec must appear in French. Another language may be used alongside French, provided the French text is given at least equal prominence.',\n    requirements: [\n      'Product identity and scent description must appear in French (e.g. \"Savon botanique press\u00E9 \u00E0 froid\").',\n      'Usage directions, care notes, and safety warnings inside boxes must be at least equal in visual prominence to English.',\n      'Descriptive generic terms attached to registered brand names must be translated into French on labels by June 1, 2025 under the amended regulation.'\n    ],\n    officialUrl: 'https://www.oqlf.gouv.qc.ca/francisation/entreprises/commerce-et-affaires.html',\n    officialLabel: 'OQLF \u2014 Commerce et affaires'\n  },\n  {\n    id: 'oqlf-web-contracts',\n    statute: 'Charte de la langue fran\u00E7aise (art. 52 & 55)',\n    title: 'Websites, Public QR Portals, B2B Quotes & Invoices',\n    authority: 'OQLF & L\u00E9gisQu\u00E9bec',\n    summary:\n      'Catalogues, brochures, commercial websites, public portals, invoices, receipts, and contracts of adhesion offered to Quebec buyers or condo corporations must be available in French.',\n    requirements: [\n      'Homeowner QR portals distributed to Quebec condo buildings must support a French interface (\"Version fran\u00E7aise\").',\n      'Standard B2B quotes, order confirmations, and invoices for Quebec clients must be offered in French.',\n      'Contracts of adhesion / wholesale terms must first be presented in French before any party can opt for another version.'\n    ],\n    officialUrl: 'https://www.legisquebec.gouv.qc.ca/fr/document/lc/C-11',\n    officialLabel: 'L\u00E9gisQu\u00E9bec \u2014 Charte C-11'\n  },\n  {\n    id: 'health-canada-fr-ccpsa',\n    statute: 'Loi sur les aliments et drogues / LCSPC (CCPSA)',\n    title: 'Bilingual Cosmetic (CNF) & Candle Safety Labelling',\n    authority: 'Sant\u00E9 Canada & Bureau de la concurrence',\n    summary:\n      'Combines federal cosmetic rules and Quebec French rules: INCI descending ingredient list, metric net quantity (g or mL), Canadian dealer name & city/postal address, plus mandatory bilingual fire-safety cautions on candles.',\n    requirements: [\n      'File Cosmetic Notification Form (DC / CNF) in English or French within 10 days of first Canadian distribution.',\n      'Candles must display bilingual burn cautions (\"MISE EN GARDE : Garder hors de la port\u00E9e des enfants...\").',\n      'Net quantity must appear in metric units (g or mL) with standard numeral sizing on the principal display panel.'\n    ],\n    officialUrl: 'https://www.canada.ca/fr/sante-canada/services/securite-produits-consommation/cosmetiques.html',\n    officialLabel: 'Sant\u00E9 Canada \u2014 Cosm\u00E9tiques (FR)'\n  },\n  {\n    id: 'quebec-loi16-condos',\n    statute: 'Code civil du Qu\u00E9bec (Loi 16 \u2014 Copropri\u00E9t\u00E9)',\n    title: 'Condo Handover Binders & Carnet d\u2019entretien Alignment',\n    authority: 'Gouvernement du Qu\u00E9bec / Syndicats de copropri\u00E9t\u00E9',\n    summary:\n      'Quebec condo developments under Law 16 emphasize documented preventative maintenance logs and building stewardship. Providing French/bilingual A3 binders and QR maintenance checklists helps developers deliver clean homeowner turnover kits.',\n    requirements: [\n      'Separate building-wide syndic emergency numbers and shutoff valve maps cleanly in French.',\n      'Include four-season HVAC/ERV filter, caulking, and frost-valve checklists (\"Printemps / \u00C9t\u00E9 / Automne / Hiver\").',\n      'Note: Homeowner closing binders complement\u2014but do not replace\u2014a syndicate\u2019s formal engineer-certified Law 16 maintenance log.'\n    ],\n    officialUrl: 'https://www.quebec.ca/habitation-et-logement/copropriete-divise',\n    officialLabel: 'Qu\u00E9bec.ca \u2014 Copropri\u00E9t\u00E9 divise'\n  },\n  {\n    id: 'req-revenu-quebec-tvq',\n    statute: 'Loi sur la TVQ & Loi sur la publicit\u00E9 l\u00E9gale des entreprises',\n    title: 'Registraire des entreprises (REQ), TPS (5%) & TVQ (9.975%)',\n    authority: 'Registraire des entreprises & Revenu Qu\u00E9bec',\n    summary:\n      'Commercial operators in Quebec generally require registration with the REQ (with a compliant French business name or French generic descriptor) and must collect GST/TPS (5%) and QST/TVQ (9.975%) once worldwide taxable sales exceed $30,000 CAD over 4 consecutive quarters.',\n    requirements: [\n      'Verify REQ declaration and French business naming compliance if operating under a trade name in Quebec.',\n      'Track $30,000 CAD small-supplier threshold across wholesale, corporate gifting, and retail combined.',\n      'Configure B2B invoices with both TPS (5%) and TVQ (9.975%) registration numbers once registered.'\n    ],\n    officialUrl: 'https://www.revenuquebec.ca/fr/entreprises/taxes/tpstvh-et-tvq/',\n    officialLabel: 'Revenu Qu\u00E9bec \u2014 TPS et TVQ'\n  }\n];\n\nfunction escapeHtml(text?: string | null): string {\n  return String(text ?? '')\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;')\n    .replace(/'/g, '&#039;');\n}\n\nexport function generateFrenchPackagingPack(input: FrenchLabelInput): FrenchLabelOutput {\n  const {\n    productType,\n    productNameFr,\n    productNameEn,\n    netWeight,\n    scentNotesFr,\n    scentNotesEn,\n    inciList,\n    companyAndAddress\n  } = input;\n\n  const warningByType: Record<FrenchLabelInput['productType'], string> = {\n    candle:\n      'MISE EN GARDE : Pour pr\u00E9venir tout incendie ou blessure grave : Garder la bougie allum\u00E9e \u00E0 vue. Garder hors de la port\u00E9e des enfants et des animaux. Ne jamais br\u00FBler sur ou pr\u00E8s d\u2019un objet inflammable. Couper la m\u00E8che \u00E0 6 mm (1/4 po) avant chaque allumage.\\n\\nWARNING: To prevent fire and serious injury: Burn candle within sight. Keep out of reach of children and pets. Never burn on or near anything that can catch fire. Trim wick to 1/4 inch (6 mm) before lighting.',\n    soap:\n      'MODE D\u2019EMPLOI : Faire mousser avec de l\u2019eau ti\u00E8de et bien rincer. Usage externe seulement. \u00C9viter tout contact avec les yeux. Laisser s\u00E9cher sur un porte-savon drainant entre chaque utilisation.\\n\\nDIRECTIONS: Lather with warm water and rinse thoroughly. For external use only. Avoid contact with eyes. Allow bar to dry on a drained soap dish between uses.',\n    serum:\n      'MODE D\u2019EMPLOI : Appliquer quelques gouttes sur une peau propre et humide. Usage externe seulement. Cesser l\u2019utilisation en cas d\u2019irritation. Conserver \u00E0 l\u2019abri de la lumi\u00E8re et de la chaleur.\\n\\nDIRECTIONS: Apply a few drops onto clean, damp skin. For external use only. Discontinue use if irritation occurs. Store away from heat and direct light.',\n    box:\n      'CONTENU DU COFFRET ARCHITECTURAL : Savon botanique press\u00E9 \u00E0 froid, bougie de cire v\u00E9g\u00E9tale coul\u00E9e \u00E0 la main et guide d\u2019entretien du propri\u00E9taire (code QR).\\n\\nARCHITECT SPECIMEN BOX CONTENTS: Cold-process botanical bar soap, hand-poured botanical vessel candle, and homeowner care portal insert (QR code).'\n  };\n\n  const safetyWarningBilingual = warningByType[productType];\n\n  const bilingualPackageLabel = [\n    `${productNameFr.toUpperCase()}`,\n    `${productNameEn}`,\n    ``,\n    `Notes botaniques : ${scentNotesFr}`,\n    `Botanical Notes: ${scentNotesEn}`,\n    `Quantit\u00E9 nette / Net Wt: ${netWeight}`,\n    ``,\n    `Ingr\u00E9dients (INCI) : ${inciList}`,\n    ``,\n    safetyWarningBilingual,\n    ``,\n    `Distribu\u00E9 par / Distributed by : ${companyAndAddress}`,\n    `Fabriqu\u00E9 en petits lots au Qu\u00E9bec \u00B7 Crafted in Quebec`\n  ].join('\\n');\n\n  const frenchOnlyCareCard = [\n    `LJWELLNESS \u00B7 COFFRET ARCHITECTURAL DE BIENVENUE`,\n    `Produit : ${productNameFr} (${netWeight})`,\n    `Profil aromatique : ${scentNotesFr}`,\n    ``,\n    `Soins botaniques : Formul\u00E9 sans phtalates ni colorants synth\u00E9tiques, avec des huiles essentielles pures et des beurres v\u00E9g\u00E9taux press\u00E9s \u00E0 froid.`,\n    `Num\u00E9risez le code QR de votre coffret pour acc\u00E9der au r\u00E9pertoire des robinets d\u2019arr\u00EAt, aux codes de finition architecturale et au calendrier d\u2019entretien quatre saisons de votre r\u00E9sidence.`,\n    ``,\n    `Atelier : ${companyAndAddress}`\n  ].join('\\n');\n\n  const b2bFrenchQuoteClause = [\n    `CONDITIONS COMMERCIALES B2B (QU\u00C9BEC) \u2014 LJWELLNESS`,\n    `1. Objet : Fourniture de coffrets \u00AB Architect Specimen Box \u00BB, de cahiers du propri\u00E9taire A3 et/ou d\u2019un portail num\u00E9rique QR d\u00E9di\u00E9 au projet immobilier.`,\n    `2. D\u00E9lai de fabrication : 10 \u00E0 14 jours ouvrables suivant l\u2019approbation finale de la maquette et la r\u00E9ception de l\u2019acompte de 50 %.`,\n    `3. Conformit\u00E9 linguistique et r\u00E9glementaire : Tous les produits cosm\u00E9tiques, \u00E9tiquettes et cahiers remis au Qu\u00E9bec sont pr\u00E9par\u00E9s en fran\u00E7ais (ou en version bilingue \u00E0 pr\u00E9dominance/\u00E9galit\u00E9 fran\u00E7aise conform\u00E9ment \u00E0 la Charte de la langue fran\u00E7aise) et selon les exigences de Sant\u00E9 Canada.`,\n    `4. Taxes applicables : TPS (5 %) et TVQ (9,975 %) ajout\u00E9es le cas \u00E9ch\u00E9ant sur la facture finale selon le statut d\u2019inscription fiscale.`\n  ].join('\\n');\n\n  const printableHtml = `<!DOCTYPE html>\n<html lang=\"fr\">\n<head>\n  <meta charset=\"utf-8\" />\n  <title>Fiche d'\u00E9tiquetage Loi 96 \u2014 ${escapeHtml(productNameFr)}</title>\n  <style>\n    @page { size: letter portrait; margin: 16mm; }\n    body { font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif; color: #1C1917; background: #FAF8F3; padding: 24px; line-height: 1.5; }\n    .kicker { font-size: 9pt; letter-spacing: 0.2em; text-transform: uppercase; color: #8A6A28; font-weight: 700; }\n    h1 { font-family: Georgia, serif; font-size: 22pt; font-weight: 400; margin: 6px 0 18px; }\n    .panel { background: #FFFFFF; border: 1px solid #D6CEBE; padding: 18px; margin-bottom: 16px; white-space: pre-wrap; font-size: 9.5pt; }\n    .panel h2 { font-size: 9pt; text-transform: uppercase; letter-spacing: 0.14em; color: #8A6A28; margin-bottom: 8px; border-bottom: 1px solid #E7E0D3; padding-bottom: 6px; }\n  </style>\n</head>\n<body>\n  <div class=\"kicker\">LJWellness \u00B7 Conformit\u00E9 Qu\u00E9bec (Loi 96 / OQLF &amp; Sant\u00E9 Canada)</div>\n  <h1>${escapeHtml(productNameFr)} / ${escapeHtml(productNameEn)}</h1>\n  <div class=\"panel\"><h2>1. \u00C9tiquette bilingue (Fran\u00E7ais \u00E0 pr\u00E9dominance \u00E9gale ou sup\u00E9rieure)</h2>${escapeHtml(bilingualPackageLabel)}</div>\n  <div class=\"panel\"><h2>2. Carte d'accompagnement en fran\u00E7ais (Coffret de livraison)</h2>${escapeHtml(frenchOnlyCareCard)}</div>\n  <div class=\"panel\"><h2>3. Clauses commerciales B2B (Qu\u00E9bec)</h2>${escapeHtml(b2bFrenchQuoteClause)}</div>\n</body>\n</html>`;\n\n  return {\n    bilingualPackageLabel,\n    frenchOnlyCareCard,\n    safetyWarningBilingual,\n    b2bFrenchQuoteClause,\n    printableHtml\n  };\n}\n\nexport function getFrenchPortalSampleOverrides(developmentName: string) {\n  return {\n    welcomeTitle: `Bienvenue chez vous \u2014 ${developmentName}`,\n    welcomeNote:\n      'F\u00E9licitations pour votre nouvelle r\u00E9sidence. Ce portail rassemble au m\u00EAme endroit les emplacements des robinets d\u2019arr\u00EAt, les coordonn\u00E9es du syndic, les sp\u00E9cifications des finis architecturaux, le calendrier d\u2019entretien quatre saisons et les soins botaniques de votre coffret LJWellness.',\n    botanicalCareNote:\n      'Formul\u00E9 en petits lots au Qu\u00E9bec, sans phtalates, avec des huiles essentielles pures et des beurres v\u00E9g\u00E9taux press\u00E9s \u00E0 froid.'\n  };\n}\n", "/**\n * Security & Access Gating Configuration\n * Enforces exclusive studio access to authorized owner emails and brand hostnames.\n */\n\nexport const AUTHORIZED_EMAILS = [\n  'mdominique1025@gmail.com',\n  'myrnad@ljwellness.net',\n  'info@ljwellness.net',\n  'artisan@ljwellness.net',\n];\n\nexport const PRIMARY_OWNER_EMAIL = 'mdominique1025@gmail.com';\n\nexport const CANONICAL_STUDIO_DOMAIN = 'artisan.ljwellness.net';\n\nexport const AUTHORIZED_BRAND_DOMAINS = [\n  'artisan.ljwellness.net',\n  'ljwellness.net',\n  'www.ljwellness.net',\n  'staging.ljwellness.net',\n];\n\nexport function isAuthorizedEmail(email?: string | null): boolean {\n  if (!email) return false;\n  const normalized = email.trim().toLowerCase();\n  return AUTHORIZED_EMAILS.includes(normalized);\n}\n\n/**\n * Checks if a hostname is an authorized LJWellness studio domain, Cloud Run preview host, or localhost.\n */\nexport function isAuthorizedAppHostname(hostname?: string | null): boolean {\n  if (!hostname) return false;\n  const clean = hostname.trim().toLowerCase().split(':')[0];\n  if (!clean) return false;\n\n  if (AUTHORIZED_BRAND_DOMAINS.includes(clean)) return true;\n  if (clean === 'localhost' || clean === '127.0.0.1') return true;\n  if (clean.endsWith('.run.app')) return true;\n  return false;\n}\n\n/**\n * Validates browser Origin headers for API CORS / cross-origin protection.\n */\nexport function isAllowedOrigin(origin?: string | null, extraAppUrl?: string): boolean {\n  if (!origin) return false;\n  try {\n    const parsed = new URL(origin.trim());\n    if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') return false;\n\n    const host = parsed.hostname.toLowerCase();\n    // Require https for custom brand production domains (permit http only on localhost or explicit staging subdomain)\n    if (\n      (host === 'artisan.ljwellness.net' || host === 'ljwellness.net' || host === 'www.ljwellness.net') &&\n      parsed.protocol !== 'https:'\n    ) {\n      return false;\n    }\n\n    if (isAuthorizedAppHostname(host)) return true;\n\n    if (extraAppUrl) {\n      const extraParsed = new URL(extraAppUrl.trim());\n      if (extraParsed.origin === parsed.origin) return true;\n    }\n\n    return false;\n  } catch {\n    return false;\n  }\n}\n", "export interface B2BKitCostInputs {\n  botanicalUnitCost: number;\n  specimenBoxCost: number;\n  customBinderPrintCost: number;\n  wholesaleBinderPrintCost: number;\n  qrInsertCardCost: number;\n  customAssemblyCost: number;\n  wholesaleAssemblyCost: number;\n  overheadPerKit: number;\n  shippingFreightPerKit?: number;\n  insuranceTestingPerKit?: number;\n  spoilageBufferPct?: number;\n  paymentProcessingPct?: number;\n  customTargetMarginPct: number;\n  wholesaleFloorMarginPct: number;\n}\n\nexport interface B2BKitTierQuote {\n  id: 'custom-single' | 'builder-wholesale-10' | 'builder-volume-25' | 'condo-qr-suite-50';\n  name: string;\n  moqLabel: string;\n  targetAudience: string;\n  deliverablesSummary: string;\n  loadedCogs: number;\n  processingFeePerKit: number;\n  recommendedPrice: number;\n  recommendedDeposit50Pct: number;\n  unitProfit: number;\n  grossMarginPct: number;\n}\n\nfunction roundCents(n: number): number {\n  return Number(Math.max(0, n).toFixed(2));\n}\n\nfunction priceAtMargin(cogs: number, marginPct: number, feeRate = 0): number {\n  const safeMargin = Math.min(0.9, Math.max(0.15, marginPct / 100));\n  const denominator = Math.max(0.05, 1 - safeMargin - feeRate);\n  return roundCents(cogs / denominator);\n}\n\nexport function computeB2BKitTiers(inputs: B2BKitCostInputs): B2BKitTierQuote[] {\n  const baseBotanical = Math.max(0, inputs.botanicalUnitCost);\n  const baseBox = Math.max(0, inputs.specimenBoxCost);\n  const baseOverhead = Math.max(0, inputs.overheadPerKit);\n  const baseFreight = Math.max(0, inputs.shippingFreightPerKit ?? 0);\n  const baseInsurance = Math.max(0, inputs.insuranceTestingPerKit ?? 0);\n  const spoilageRate = Math.min(0.25, Math.max(0, (inputs.spoilageBufferPct ?? 0) / 100));\n  const feeRate = Math.min(0.1, Math.max(0, (inputs.paymentProcessingPct ?? 0) / 100));\n\n  const buildTierMetrics = (\n    cogs: number,\n    targetMarginPct: number\n  ): {\n    loadedCogs: number;\n    processingFeePerKit: number;\n    recommendedPrice: number;\n    recommendedDeposit50Pct: number;\n    unitProfit: number;\n    grossMarginPct: number;\n  } => {\n    const loadedCogs = roundCents(cogs);\n    const recommendedPrice = priceAtMargin(loadedCogs, targetMarginPct, feeRate);\n    const processingFeePerKit = roundCents(recommendedPrice * feeRate);\n    const unitProfit = roundCents(recommendedPrice - loadedCogs - processingFeePerKit);\n    const grossMarginPct =\n      recommendedPrice > 0 ? Number(((unitProfit / recommendedPrice) * 100).toFixed(1)) : 0;\n    const recommendedDeposit50Pct = roundCents(recommendedPrice * 0.5);\n    return {\n      loadedCogs,\n      processingFeePerKit,\n      recommendedPrice,\n      recommendedDeposit50Pct,\n      unitProfit,\n      grossMarginPct,\n    };\n  };\n\n  // 1. Custom Single-Buyer High-End Kit (Box + Monogrammed A3 Binder + QR)\n  const customMetrics = buildTierMetrics(\n    baseBotanical * (1 + spoilageRate) +\n      baseBox +\n      Math.max(0, inputs.customBinderPrintCost) +\n      Math.max(0, inputs.qrInsertCardCost) +\n      Math.max(0, inputs.customAssemblyCost) +\n      baseOverhead +\n      baseFreight +\n      baseInsurance,\n    inputs.customTargetMarginPct\n  );\n\n  // 2. Builder Wholesale Run (10-24 kits, Box + Fill-In A3 Binder + QR)\n  const wholesale10Metrics = buildTierMetrics(\n    baseBotanical * (1 + spoilageRate) +\n      baseBox +\n      Math.max(0, inputs.wholesaleBinderPrintCost) +\n      Math.max(0, inputs.qrInsertCardCost) +\n      Math.max(0, inputs.wholesaleAssemblyCost) +\n      baseOverhead +\n      baseFreight * 0.8 +\n      baseInsurance,\n    Math.min(85, inputs.wholesaleFloorMarginPct + 5)\n  );\n\n  // 3. Volume Builder Run (25-49 kits, bulk print/assembly efficiency)\n  const volume25Metrics = buildTierMetrics(\n    baseBotanical * 0.92 * (1 + spoilageRate) +\n      baseBox * 0.9 +\n      Math.max(0, inputs.wholesaleBinderPrintCost) * 0.85 +\n      Math.max(0, inputs.qrInsertCardCost) +\n      Math.max(0, inputs.wholesaleAssemblyCost) * 0.85 +\n      baseOverhead +\n      baseFreight * 0.6 +\n      baseInsurance,\n    inputs.wholesaleFloorMarginPct\n  );\n\n  // 4. Uniform Condo Development QR Suite (50+ kits, Box + Uniform Development QR Card, no A3 binder print)\n  const condo50Metrics = buildTierMetrics(\n    baseBotanical * 0.88 * (1 + spoilageRate) +\n      baseBox * 0.85 +\n      Math.max(0, inputs.qrInsertCardCost) +\n      Math.max(0, inputs.wholesaleAssemblyCost) * 0.75 +\n      baseOverhead +\n      baseFreight * 0.45 +\n      baseInsurance,\n    inputs.wholesaleFloorMarginPct\n  );\n\n  return [\n    {\n      id: 'custom-single',\n      name: 'Custom Single-Buyer Kit',\n      moqLabel: '1\u20139 Kits',\n      targetAudience: 'Luxury Realtors & Custom Estate Closings',\n      deliverablesSummary: 'Architect Specimen Box + Personalized Single-Buyer A3 Binder + QR Portal',\n      ...customMetrics,\n    },\n    {\n      id: 'builder-wholesale-10',\n      name: 'Builder Wholesale Run',\n      moqLabel: '10\u201324 Kits',\n      targetAudience: 'Boutique Homebuilders & Broker Teams',\n      deliverablesSummary: 'Architect Specimen Box + Wholesale Fill-In A3 Binder + Shared QR Card',\n      ...wholesale10Metrics,\n    },\n    {\n      id: 'builder-volume-25',\n      name: 'Multi-Phase Builder Tier',\n      moqLabel: '25\u201349 Kits',\n      targetAudience: 'Multi-Lot Builders & Townhome Phases',\n      deliverablesSummary: 'Bulk Specimen Boxes + Fill-In A3 Binder Cartons + Shared QR Card',\n      ...volume25Metrics,\n    },\n    {\n      id: 'condo-qr-suite-50',\n      name: 'Condo Development QR Suite',\n      moqLabel: '50+ Units',\n      targetAudience: 'Condo & Rental Tower Developers (Uniform Handover)',\n      deliverablesSummary: 'Architect Specimen Box + Uniform Development QR Portal Insert Card',\n      ...condo50Metrics,\n    },\n  ];\n}\n"],
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA,oBAAO;AACP,IAAAA,kBAAoB;AACpB,kBAAiB;AACjB,gBAAe;AACf,iBAAkE;AAClE,kBAAwB;AACxB,uBAA6B;;;ACN7B,mBAAuD;;;ACAvD,oBAAmB;AAKZ,SAAS,2BAA2B,SAA0B,QAAwB;AAC3F,QAAM,SAAS,cAAAC,QAAO,WAAW,UAAU,MAAM,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK;AAC/E,SAAO,UAAU,MAAM;AACzB;AAKO,SAAS,0BACd,SACA,iBACA,QACS;AACT,MAAI,CAAC,mBAAmB,CAAC,OAAQ,QAAO;AACxC,QAAM,UAAU,gBAAgB,KAAK;AACrC,QAAM,qBAAqB,QAAQ,YAAY,EAAE,WAAW,SAAS,IACjE,QAAQ,MAAM,CAAC,EAAE,KAAK,EAAE,YAAY,IACpC,QAAQ,YAAY;AAExB,MAAI,CAAC,iBAAiB,KAAK,kBAAkB,GAAG;AAC9C,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,cAAAA,QACjB,WAAW,UAAU,MAA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AAA,QAAQ,OAAO,QAAQ,CAAC;AAChC,QAAI,IAAI,KAAK,CAAC,MAAM,QAAQ;AAC1B,UAAI,SAAS,YAAAF,QAAK,KAAK,UAAU,YAAY,CAAC;AAAA,IAChD,CAAC;AAAA,EACH;AAEA,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI,OAAO,MAAM,MAAM;AACrB,cAAQ,IAAI,yCAAyC,IAAI,EAAE;AAAA,IAC7D,CAAC;AAAA,EACH,OAAO;AACL,QAAI,OAAO,MAAM,WAAW,MAAM;AAChC,cAAQ,IAAI,iDAAiD,IAAI,EAAE;AAAA,IACrE,CAAC;AAAA,EACH;AACF;AAEA,YAAY;",
  "names": ["import_express", "crypto", "tpsCad", "resolveOwnerUid", "requireStudioOwner", "express", "import_express", "DEFAULT_APP_NAME", "resolveOwnerUid", "requireStudioOwner", "express", "path", "fs", "express"]
}
