/* Cartesian Corp — AI components: Project Scoper + "Ask Cartesian" chat assistant. * * Works fully in the browser with a built-in scoping engine (no API key exposed). * To use a real LLM, deploy a small serverless proxy and set AI_ENDPOINT below. * The endpoint receives POST { mode: "chat" | "scope", messages: [...], text } and * should return JSON { reply: "..." }. Any failure falls back to the local engine. */ (function () { const AI_ENDPOINT = ''; // e.g. '/api/chat' const $ = (s, el = document) => el.querySelector(s); const $$ = (s, el = document) => [...el.querySelectorAll(s)]; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const team = () => (window.CC_DATA && window.CC_DATA.team) || []; const base = document.body.dataset.base || ''; const store = { get(k) { try { return JSON.parse(sessionStorage.getItem(k) || 'null'); } catch (e) { return null; } }, set(k, v) { try { sessionStorage.setItem(k, JSON.stringify(v)); } catch (e) { /* ignore */ } } }; const member = (initials) => team().find((m) => m.initials === initials); /* ================= SCOPING ENGINE ================= */ const DOMAINS = { ai: { kw: ['ai', 'agent', 'llm', 'gpt', 'claude', 'chatbot', 'bot', 'rag', 'copilot', 'assistant', 'genai', 'automation', 'automate', 'nlp', 'ml', 'machine learning', 'ticket', 'support', 'voice', 'mcp'], need: 'ai-agents', title: 'AI agent system', summary: 'An LLM-powered agent with retrieval over your knowledge, tool access to your systems, guardrails, and a human-in-the-loop review step for high-risk actions.', arch: ['Channels (web / Slack / email)', 'Agent orchestrator', 'Tools & APIs', 'RAG + vector store', 'Evals & guardrails', 'Observability'], team: ['NK', 'SU', 'SK', 'BK'], weeks: [2, 2, 6, 2], stack: ['Python', 'Claude / OpenAI', 'LangGraph or custom', 'pgvector', 'Azure / AWS'] }, data: { kw: ['data', 'lake', 'lakehouse', 'warehouse', 'etl', 'pipeline', 'analytics', 'dashboard', 'bi', 'spark', 'kafka', 'stream', 'real-time', 'realtime', 'snowflake', 'databricks', 'report'], need: 'data', title: 'Modern data platform', summary: 'A governed lakehouse with streaming and batch ingestion, modeled data products and self-serve analytics, ready for AI and ML workloads.', arch: ['Sources', 'Ingestion (Kafka / CDC)', 'Lakehouse (bronze → silver → gold)', 'dbt models', 'BI & ML features', 'Governance'], team: ['GM', 'NK', 'SK', 'KC'], weeks: [2, 2, 8, 2], stack: ['Spark', 'Kafka', 'Databricks / Snowflake', 'dbt', 'Airflow'] }, modern: { kw: ['legacy', 'monolith', 'migrate', 'migration', 'modernize', 'modernise', 'mainframe', 'on-prem', 'rewrite', 'cobol', 'old system', 'upgrade'], need: 'modernization', title: 'Legacy modernization program', summary: 'A step-by-step strangler-fig migration: carve out domains into services behind an API gateway, with an event backbone so old and new systems run side by side until cutover.', arch: ['Legacy monolith', 'API gateway / facade', 'Domain services', 'Event backbone', 'Cloud platform', 'Decommission'], team: ['SK', 'NK', 'GM', 'KC'], weeks: [3, 3, 12, 4], stack: ['Java / .NET', 'Kafka', 'Kubernetes', 'Terraform', 'Postgres'] }, cloud: { kw: ['cloud', 'devops', 'kubernetes', 'k8s', 'aws', 'azure', 'gcp', 'terraform', 'ci/cd', 'cicd', 'infra', 'infrastructure', 'cost', 'scaling', 'scale', 'observability', 'sre'], need: 'cloud', title: 'Cloud platform & DevOps foundation', summary: 'Infrastructure as code, GitOps delivery, golden-path templates, SLO-based observability and FinOps guardrails, so teams ship faster and cheaper.', arch: ['Landing zone', 'Terraform modules', 'Kubernetes / serverless', 'GitOps CI/CD', 'Observability & SLOs', 'FinOps'], team: ['SK', 'NK', 'SU', 'KC'], weeks: [2, 2, 6, 2], stack: ['Terraform', 'Kubernetes', 'Argo CD', 'GitHub Actions', 'Grafana'] }, product: { kw: ['app', 'saas', 'web', 'website', 'mobile', 'ios', 'android', 'platform', 'portal', 'marketplace', 'mvp', 'startup', 'dashboard', 'customer'], need: 'product', title: 'Product build: web & mobile', summary: 'A discovery sprint to lock scope and UX, then a production-grade web and mobile product with auth, billing, multi-tenancy and analytics built in, with room for AI features.', arch: ['UX & design system', 'React / React Native', 'API (Node / Java)', 'Postgres', 'Auth & billing', 'Analytics'], team: ['BK', 'SU', 'SK', 'KC'], weeks: [2, 2, 8, 2], stack: ['React', 'Next.js', 'Node / Java', 'Postgres', 'Stripe'] } }; function classify(text) { const t = ' ' + text.toLowerCase() + ' '; const scores = Object.entries(DOMAINS).map(([k, d]) => [k, d.kw.reduce((s, w) => s + (t.includes(w) ? (w.length > 4 ? 2 : 1) : 0), 0)]); scores.sort((a, b) => b[1] - a[1]); const primary = scores[0][1] > 0 ? scores[0][0] : 'product'; const secondary = scores[1][1] > 1 ? scores[1][0] : null; return { primary, secondary }; } function buildPlan(text, urgency, stage) { const { primary, secondary } = classify(text); const d = DOMAINS[primary]; const sec = secondary ? DOMAINS[secondary] : null; let weeks = d.weeks.slice(); if (stage === 'poc') weeks = [1, weeks[1], Math.max(4, weeks[2] - 2), weeks[3]]; if (stage === 'prod') weeks = [2, 2, weeks[2] + 2, 3]; if (urgency === 'fast') weeks = weeks.map((w, i) => (i === 2 ? Math.max(3, Math.round(w * 0.75)) : w)); const total = weeks.reduce((a, b) => a + b, 0); const teamIds = [...new Set([...d.team, ...(sec ? sec.team.slice(0, 1) : [])])].slice(0, 5); const complexity = total > 16 ? 'High' : total > 11 ? 'Medium' : 'Focused'; const extra = sec ? ` We would also bring in ${sec.title.toLowerCase()} expertise, since your brief touches on it.` : ''; return { domain: primary, need: d.need, title: d.title, summary: d.summary + extra, arch: d.arch, stack: d.stack, team: teamIds, total, complexity, phases: [['Discover', weeks[0]], ['Architect', weeks[1]], ['Build', weeks[2]], ['Launch & scale', weeks[3]]] }; } async function remote(payload) { if (!AI_ENDPOINT) return null; try { const r = await fetch(AI_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); if (!r.ok) return null; const j = await r.json(); return j && j.reply ? String(j.reply) : null; } catch (e) { return null; } } /* ================= SCOPER UI ================= */ const out = $('#scoperOut'); const input = $('#scoperText'); const go = $('#scoperGo'); if (out && input && go) { $$('#scoperChips .chip').forEach((c) => c.addEventListener('click', () => { input.value = c.textContent; input.focus(); })); const carried = store.get('cc_scoper'); if (carried) { input.value = carried; sessionStorage.removeItem('cc_scoper'); } let busy = false; go.addEventListener('click', async () => { if (busy) return; const text = input.value.trim(); if (text.length < 8) { input.focus(); input.placeholder = 'Tell us a little more: what should it do, and for whom?'; return; } busy = true; go.disabled = true; const plan = buildPlan(text, $('#scoperUrgency').value, $('#scoperStage').value); const body = $('#scoperBody') || out; out.classList.remove('has-plan'); out.classList.add('thinking'); window.dispatchEvent(new CustomEvent('cc:thinking', { detail: true })); body.innerHTML = '
' + ($('.orb3d', out) ? '' : '
') + '

'; const tl = $('#thinkLine'); for (const s of ['Reading your brief', 'Matching against past projects', 'Drafting the architecture', 'Assigning the team', 'Estimating the timeline']) { tl.textContent = s + '…'; await sleep(480); } const aiNote = await remote({ mode: 'scope', text, plan }); const tm = plan.team.map(member).filter(Boolean); out.classList.remove('thinking'); out.classList.add('has-plan'); window.dispatchEvent(new CustomEvent('cc:thinking', { detail: false })); body.innerHTML = `

Draft plan

${plan.title}

~${plan.total} weeks · ${plan.complexity}

Recommended approach

${esc(aiNote || plan.summary)}

Architecture

${plan.arch.map((a) => `${a}`).join('→')}

Your team

${tm.map((m) => `${m.initials}${m.name.split(' ')[0]} · ${m.role}`).join('')}

Phases

${plan.phases.map(([n, w]) => `
${n}
${w} wk
`).join('')}

Suggested stack

${plan.stack.map((s) => `${s}`).join('')}

Want this reviewed by our architects?
Book a free 30-minute call. We'll pressure-test the plan and give you a fixed-scope proposal.

`; const blocks = $$('.plan-block', out); for (const b of blocks) { b.classList.add('in'); await sleep(170); } $$('.phase .bar span', out).forEach((s) => { s.style.width = Math.min(100, +s.dataset.w) + '%'; }); $('#planBook').addEventListener('click', () => { window.CC && window.CC.goContact({ need: plan.need, msg: `${text}\n\n— AI Scoper draft: ${plan.title}, ~${plan.total} weeks (${plan.complexity}). Stage: ${$('#scoperStage').selectedOptions[0].text}. Timeline: ${$('#scoperUrgency').selectedOptions[0].text}.` }); }); busy = false; go.disabled = false; }); } /* ================= CHAT ASSISTANT ================= */ const chat = $('#chat'); if (!chat) return; const fab = $('#chatFab'), body = $('#chatBody'), form = $('#chatForm'), field = $('#chatText'), teaser = $('#chatTeaser'), suggest = $('#chatSuggest'); const history = []; let greeted = false; const CTA = (label = 'Book a free call', kind = 'contact') => `
${label} →`; const INTENTS = [ { re: /\b(hi|hello|hey|yo|namaste|good (morning|evening|afternoon))\b/, a: () => `Hi! 👋 I'm the Cartesian assistant. I can tell you what we build, who's on the team, how engagements work, or scope your project right now. What are you working on?` }, { re: /(price|pricing|cost|budget|rate|quote|how much|expensive|cheap)/, a: () => `Pricing depends on scope. We work three ways:
• Fixed-scope projects for well-defined builds
• Dedicated pod: an architect plus 2–4 engineers, billed monthly
• Advisory: architecture reviews and AI strategy sprints
Most projects start with a free 30-min call, and we send a fixed proposal within 48 hours.${CTA('Get a proposal')}` }, { re: /(founder|who are (you|u)|your team|the team\b|team members|who.*(work|build)s? (on|with))/, a: () => `Our founding team:
${team().map((m) => `• ${m.name}, ${m.role}`).join('
')}
You work directly with senior people, not a bench of juniors.${CTA('Meet us on a call')}` }, { re: /(agent|llm|gpt|claude|rag|chatbot|genai|copilot|ai\b|artificial)/, a: () => `AI agents are our specialty. We build agents that call your real tools (CRM, ERP, ticketing, databases), use retrieval over your documents, and ship with evals, guardrails and human approval steps. Typical first agent: 6–10 weeks to production.${CTA('Scope my AI agent', 'scope')}`, scope: true }, { re: /(data|lake|warehouse|pipeline|etl|analytics|spark|kafka|databricks|snowflake)/, a: () => `Gautham leads our data practice: lakehouses, streaming pipelines with Kafka and Spark, dbt models and governed data products. We design pipelines that move analytics from nightly batches to near real time.${CTA('Talk to our data architect')}` }, { re: /(legacy|monolith|migrat|moderni|mainframe|on-prem)/, a: () => `We modernize step by step with a strangler-fig approach: new services carve out the old system piece by piece, with zero-downtime cutovers. No big-bang rewrites.${CTA('Plan my migration')}` }, { re: /(cloud|devops|kubernetes|k8s|aws|azure|gcp|terraform|ci\/?cd|infra)/, a: () => `We build cloud foundations on AWS, Azure and GCP: Terraform, Kubernetes, GitOps and observability. Every engagement includes a FinOps review of idle and oversized resources.${CTA()}` }, { re: /(app|website|web|mobile|saas|mvp|product|startup)/, a: () => `We take products from idea to launch: discovery, UX, React / React Native front ends, robust APIs, billing and analytics. A typical MVP takes 10–14 weeks.${CTA('Scope my product', 'scope')}`, scope: true }, { re: /(time|timeline|how long|weeks|fast|deadline|quick)/, a: () => `Rough guide: discovery 1–2 weeks, architecture 1–2 weeks, build 4–12 weeks, launch 2 weeks. Try our AI Project Scoper for an estimate tailored to your idea.${CTA('Open the Scoper', 'scope')}`, scopeLink: true }, { re: /(process|how do you work|approach|method|agile|sprint)/, a: () => `Four steps: Discover → Architect → Build → Scale. Two-week sprints with live demos, full transparency in your Slack or Teams, and code you own from day one.${CTA()}` }, { re: /(portfolio|work|case stud|project|client|example)/, a: () => `Our Work page has reference solutions with product walkthrough videos: an AI support agent, a real-time logistics lakehouse, a core banking modernization and more. On a call we can walk you through comparable client work under NDA.${CTA('Discuss a similar project')}` }, { re: /(contact|email|call|meet|book|talk|reach|hire|start)/, a: () => `Let's talk! Email hello@cartesiancorp.com or send your details through our contact page. We reply within one business day.${CTA('Go to contact form')}` }, { re: /(where|location|india|usa|remote|timezone|office)/, a: () => `We're a remote-first team and work across time zones with overlap hours for the US, UK, EU and India.${CTA()}` }, { re: /(nda|security|secure|compliance|ip|own the code|confidential)/, a: () => `We sign NDAs before any detailed discussion. You own 100% of the code and IP, and we follow secure SDLC practices: least-privilege access, secrets management, and PII-safe AI pipelines.${CTA()}` } ]; function localAnswer(q) { const t = q.toLowerCase(); for (const it of INTENTS) if (it.re.test(t)) return it.a(); if (q.split(/\s+/).length > 6) { const p = buildPlan(q, 'normal', 'idea'); return `That sounds like a ${p.title.toLowerCase()}. My first-pass estimate is ~${p.total} weeks, led by ${p.team.slice(0, 2).map((i) => (member(i) || {}).name).join(' and ')}. Want our architects to turn this into a fixed proposal?${CTA('Yes, book a free call')}`; } return `Good question. The fastest way to a precise answer is a short call with one of our architects. Meanwhile I can tell you about our services, team, pricing or timelines.${CTA()}`; } const saved = store.get('cc_chat') || []; function persist() { store.set('cc_chat', $$('.msg:not(.typing)', body).slice(-30).map((el) => ({ who: el.classList.contains('user') ? 'user' : 'bot', html: el.innerHTML }))); store.set('cc_hist', history.slice(-20)); } function addMsg(html, who = 'bot') { const m = document.createElement('div'); m.className = 'msg ' + who; m.innerHTML = html; body.appendChild(m); body.scrollTop = body.scrollHeight; $$('[data-cta]', m).forEach((a) => a.addEventListener('click', (e) => { e.preventDefault(); const last = history.filter((h) => h.role === 'user').pop(); if (a.dataset.cta === 'scope') { if (last && last.content.split(/\s+/).length > 4) store.set('cc_scoper', last.content); const box = $('#scoperText'); if (box) { chat.classList.remove('open'); if (last) box.value = last.content; box.focus(); return; } location.href = base + 'ai-scoper.html'; } else { const transcript = history.filter((h) => h.role === 'user').map((h) => '- ' + h.content).join('\n'); chat.classList.remove('open'); window.CC && window.CC.goContact({ msg: transcript ? 'From my chat with the Cartesian assistant:\n' + transcript : '' }); } })); return m; } async function reply(q) { history.push({ role: 'user', content: q }); addMsg(esc(q), 'user'); const typing = addMsg('', 'bot typing'); const [remoteText] = await Promise.all([remote({ mode: 'chat', messages: history }), sleep(650 + Math.random() * 500)]); typing.remove(); const html = remoteText ? esc(remoteText).replace(/\n/g, '
') + CTA() : localAnswer(q); history.push({ role: 'assistant', content: html.replace(/<[^>]+>/g, ' ') }); addMsg(html); renderSuggestions(); persist(); } const SUGGESTIONS = ['What do you build?', 'Can you build an AI agent for us?', 'How much does a project cost?', 'Who is on the team?', 'How long does an MVP take?', 'Do you sign NDAs?']; function renderSuggestions() { const asked = new Set(history.filter((h) => h.role === 'user').map((h) => h.content)); suggest.innerHTML = ''; SUGGESTIONS.filter((s) => !asked.has(s)).slice(0, 4).forEach((s) => { const b = document.createElement('button'); b.type = 'button'; b.textContent = s; b.addEventListener('click', () => reply(s)); suggest.appendChild(b); }); } INTENTS.unshift({ re: /what do you (build|do)|services|offer/, a: () => `We're senior developers and architects who build:
• AI agents & LLM apps
• Enterprise architecture & modernization
• Data platforms & pipelines
• Cloud & DevOps
• Web & mobile products
Tell me what you're working on and I'll suggest an approach.` }); if (saved.length) { greeted = true; history.push(...(store.get('cc_hist') || [])); saved.forEach((m) => addMsg(m.html, m.who)); renderSuggestions(); } function openChat() { chat.classList.add('open', 'seen'); fab.setAttribute('aria-expanded', 'true'); store.set('cc_seen', true); teaser.classList.remove('show'); fab.setAttribute('aria-label', 'Close assistant'); if (!greeted) { greeted = true; addMsg(`Hi, I'm Ask Cartesian ✦
I can answer questions about our services, team and pricing, or give you an instant project estimate. What are you building?`); renderSuggestions(); persist(); } setTimeout(() => field.focus(), 300); } fab.addEventListener('click', () => chat.classList.contains('open') ? (chat.classList.remove('open'), fab.setAttribute('aria-expanded', 'false'), fab.setAttribute('aria-label', 'Open Cartesian AI assistant')) : openChat()); if (store.get('cc_seen')) chat.classList.add('seen'); teaser.addEventListener('click', openChat); form.addEventListener('submit', (e) => { e.preventDefault(); const q = field.value.trim(); if (!q) return; field.value = ''; reply(q); }); // proactive nudges (once per session) if (!store.get('cc_nudged')) { setTimeout(() => { if (chat.classList.contains('open') || store.get('cc_nudged')) return; store.set('cc_nudged', true); teaser.classList.add('show'); setTimeout(() => teaser.classList.remove('show'), 12000); }, 20000); } const workSec = $('.work-grid'); if (workSec && !store.get('cc_nudged')) { new IntersectionObserver(([e], obs) => { if (!e.isIntersecting) return; obs.disconnect(); setTimeout(() => { if (chat.classList.contains('open') || greeted) return; if (store.get('cc_nudged')) return; store.set('cc_nudged', true); teaser.textContent = 'Like what you see? Get a free estimate for your project.'; teaser.classList.add('show'); setTimeout(() => teaser.classList.remove('show'), 9000); }, 4000); }, { threshold: .25 }).observe(workSec); } })();