Spaces:
Running
Running
Ashraf Al-Kassem Claude Opus 4.6 commited on
Commit ·
a5f93e1
1
Parent(s): fc6fc7e
feat: Mission 29 — Prompt Studio Enhancements + Auth Fixes + User Seeding
Browse filesMission 29: Knowledge chunking (DOCX/XLSX support, keyword retrieval),
dynamic qualification criteria (relational CRUD), AI step output schema,
and prompt compiler integration for all three.
Auth fixes: seed demo + admin users on startup, fix Google OAuth
email_verified_at bug, fix admin-api.ts 403 logout, comprehensive
auth test suite (19 tests covering studio + admin flows).
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (20)
- backend/alembic/versions/i9j0k1l2m3n4_mission_29_knowledge_chunks_qualification.pyAdded+59
- backend/app/api/v1/auth.py+5-1
- backend/app/api/v1/knowledge.py+51-2
- backend/app/api/v1/qualification_criteria.pyAdded+223
- backend/app/api/v1/test_chat.py+5-2
- backend/app/core/seed.py+76-2
- backend/app/domain/runtime.py+20-12
- backend/app/models/models.py+30
- backend/app/services/knowledge_chunker.pyAdded+188
- backend/app/services/prompt_compiler.py+72-20
- backend/main.py+4-1
- backend/requirements.txt+2
- backend/scripts/create_test_user.py+68-1
- backend/tests/test_auth_comprehensive.pyAdded+294
- backend/tests/test_knowledge_chunks.pyAdded+195
- backend/tests/test_prompt_compile_enhanced.pyAdded+206
- backend/tests/test_qualification_criteria.pyAdded+201
- frontend/src/app/(dashboard)/automations/[id]/NodeConfigPanel.tsx+40
- frontend/src/app/(dashboard)/prompt-studio/page.tsx+144-3
- frontend/src/lib/admin-api.ts+12-1
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""Mission 29 — Knowledge chunks + qualification criteria tables
Revision ID: i9j0k1l2m3n4Revises: h8i9j0k1l2m3Create Date: 2026-03-01"""from alembic import opimport sqlalchemy as sa
revision = "i9j0k1l2m3n4"down_revision = "h8i9j0k1l2m3"branch_labels = Nonedepends_on = None
def upgrade() -> None: # --- KnowledgeChunk --- op.create_table( "knowledgechunk", sa.Column("id", sa.Uuid(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("workspace_id", sa.Uuid(), nullable=False), sa.Column("knowledge_file_id", sa.Uuid(), nullable=False), sa.Column("chunk_index", sa.Integer(), nullable=False, server_default="0"), sa.Column("content_text", sa.Text(), nullable=False), sa.ForeignKeyConstraint(["workspace_id"], ["workspace.id"]), sa.ForeignKeyConstraint(["knowledge_file_id"], ["workspaceknowledgefile.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_index("ix_knowledgechunk_workspace_id", "knowledgechunk", ["workspace_id"]) op.create_index("ix_knowledgechunk_knowledge_file_id", "knowledgechunk", ["knowledge_file_id"]) op.create_index("idx_kc_ws_file", "knowledgechunk", ["workspace_id", "knowledge_file_id"])
# --- QualificationCriterion --- op.create_table( "qualificationcriterion", sa.Column("id", sa.Uuid(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=False), sa.Column("updated_at", sa.DateTime(), nullable=False), sa.Column("workspace_id", sa.Uuid(), nullable=False), sa.Column("code", sa.String(), nullable=False), sa.Column("label", sa.String(), nullable=False), sa.Column("description", sa.String(), nullable=True), sa.Column("criterion_type", sa.String(), nullable=False, server_default="boolean"), sa.Column("enum_values", sa.JSON(), nullable=True), sa.Column("weight", sa.Integer(), nullable=True), sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"), sa.Column("is_enabled", sa.Boolean(), nullable=False, server_default="1"), sa.ForeignKeyConstraint(["workspace_id"], ["workspace.id"]), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("workspace_id", "code", name="uq_qualcriterion_ws_code"), ) op.create_index("ix_qualificationcriterion_workspace_id", "qualificationcriterion", ["workspace_id"]) op.create_index("ix_qualificationcriterion_code", "qualificationcriterion", ["code"])
def downgrade() -> None: op.drop_table("qualificationcriterion") op.drop_table("knowledgechunk")615 unmodified lines61661761861962062162218 unmodified lines641642643644645646615 unmodified linesfull_name=full_name,auth_provider="google",provider_subject=google_id,is_active=True)db.add(user)await db.flush()18 unmodified linesuser.provider_subject = google_idif full_name:user.full_name = full_namedb.add(user)await db.commit()await db.refresh(user)615 unmodified lines61661761861962062162262318 unmodified lines642643644645646647648649650615 unmodified linesfull_name=full_name,auth_provider="google",provider_subject=google_id,is_active=True,email_verified_at=datetime.utcnow(),)db.add(user)await db.flush()18 unmodified linesuser.provider_subject = google_idif full_name:user.full_name = full_name# Google confirmed email — mark verified if not alreadyif user.email_verified_at is None:user.email_verified_at = datetime.utcnow()db.add(user)await db.commit()await db.refresh(user)
6 unmodified lines78910111213141516171861 unmodified lines8081828384858612 unmodified lines991001011021031042 unmodified lines10710810911011111266 unmodified lines1791801811821831846 unmodified linesfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlmodel import selectfrom app.api import depsfrom app.core.db import get_dbfrom app.models.models import Workspace, WorkspaceKnowledgeFilefrom app.schemas.envelope import ResponseEnvelope, wrap_data, wrap_errorfrom app.core.modules import require_module_enabled, MODULE_KNOWLEDGE_FILESfrom app.services.entitlements import require_entitlementrouter = APIRouter()61 unmodified lineselse:extracted_text = full_text[:MAX_EXTRACTED_TEXT]except ImportError:# PyMuPDF not installed — mark as unsupportedstatus = "FAILED"except Exception:status = "FAILED"12 unmodified lines)db.add(knowledge_file)await db.commit()await db.refresh(knowledge_file)2 unmodified lines"filename": knowledge_file.filename,"extracted": extracted_text is not None,"status": status,})66 unmodified linesif not kb_file:raise HTTPException(status_code=404, detail="File not found")# Delete from storageif os.path.exists(kb_file.storage_path):os.remove(kb_file.storage_path)6 unmodified lines78910111213141516171819202161 unmodified lines838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012 unmodified lines1331341351361371381391401411421431441451461472 unmodified lines15015115215315415515666 unmodified lines2232242252262272282292302312322336 unmodified linesfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlmodel import selectfrom sqlmodel import delete as sql_deletefrom app.api import depsfrom app.core.db import get_dbfrom app.models.models import Workspace, WorkspaceKnowledgeFile, KnowledgeChunkfrom app.schemas.envelope import ResponseEnvelope, wrap_data, wrap_errorfrom app.core.modules import require_module_enabled, MODULE_KNOWLEDGE_FILESfrom app.services.entitlements import require_entitlementfrom app.services.knowledge_chunker import create_chunks_for_filerouter = APIRouter()61 unmodified lineselse:extracted_text = full_text[:MAX_EXTRACTED_TEXT]except ImportError:status = "FAILED"except Exception:status = "FAILED"elif extension.lower() == ".docx":try:from docx import Document as DocxDocumentdoc = DocxDocument(storage_path)full_text = "\n".join(p.text for p in doc.paragraphs)if not full_text.strip():status = "FAILED"else:extracted_text = full_text[:MAX_EXTRACTED_TEXT]except ImportError:status = "FAILED"except Exception:status = "FAILED"elif extension.lower() == ".xlsx":try:from openpyxl import load_workbookwb = load_workbook(storage_path, read_only=True, data_only=True)rows_text = []for ws in wb.worksheets:for row in ws.iter_rows(values_only=True):cells = [str(c) if c is not None else "" for c in row]rows_text.append("\t".join(cells))wb.close()full_text = "\n".join(rows_text)if not full_text.strip():status = "FAILED"else:extracted_text = full_text[:MAX_EXTRACTED_TEXT]except ImportError:status = "FAILED"except Exception:status = "FAILED"12 unmodified lines)db.add(knowledge_file)await db.flush()# Create knowledge chunks for retrievalchunk_count = 0if extracted_text:chunk_count = await create_chunks_for_file(db, workspace.id, uuid.UUID(file_id), extracted_text,)await db.commit()await db.refresh(knowledge_file)2 unmodified lines"filename": knowledge_file.filename,"extracted": extracted_text is not None,"status": status,"chunk_count": chunk_count,})66 unmodified linesif not kb_file:raise HTTPException(status_code=404, detail="File not found")# Delete chunks firstawait db.execute(sql_delete(KnowledgeChunk).where(KnowledgeChunk.knowledge_file_id == file_id))# Delete from storageif os.path.exists(kb_file.storage_path):os.remove(kb_file.storage_path)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Qualification Criteria API — Mission 29Workspace-scoped dynamic lead qualification criteria (stored as rows)."""import refrom typing import Any, List, Optionalfrom uuid import UUID
from fastapi import APIRouter, Depends, HTTPExceptionfrom pydantic import BaseModelfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlmodel import select
from app.api import depsfrom app.core.db import get_dbfrom app.models.models import Workspace, QualificationCriterionfrom app.schemas.envelope import ResponseEnvelope, wrap_data, wrap_errorfrom app.core.modules import require_module_enabled, MODULE_PROMPT_STUDIOfrom app.services.entitlements import require_entitlement
router = APIRouter()
VALID_CRITERION_TYPES = {"boolean", "enum", "text", "score"}
def _slugify(label: str) -> str: """Convert label to a snake_case code.""" s = label.lower().strip() s = re.sub(r"[^a-z0-9]+", "_", s) s = s.strip("_") return s or "criterion"
# --- Schemas ---
class CriterionCreate(BaseModel): label: str code: Optional[str] = None description: Optional[str] = None criterion_type: str = "boolean" enum_values: Optional[List[str]] = None weight: Optional[int] = None sort_order: int = 0 is_enabled: bool = True
class CriterionUpdate(BaseModel): label: Optional[str] = None description: Optional[str] = None criterion_type: Optional[str] = None enum_values: Optional[List[str]] = None weight: Optional[int] = None sort_order: Optional[int] = None is_enabled: Optional[bool] = None
def _criterion_to_dict(c: QualificationCriterion) -> dict: return { "id": str(c.id), "code": c.code, "label": c.label, "description": c.description, "criterion_type": c.criterion_type, "enum_values": c.enum_values, "weight": c.weight, "sort_order": c.sort_order, "is_enabled": c.is_enabled, "created_at": c.created_at.isoformat(), }
# --- Endpoints ---
@router.get( "/qualification", response_model=ResponseEnvelope[List[dict]], dependencies=[ Depends(require_module_enabled(MODULE_PROMPT_STUDIO, "read")), Depends(require_entitlement("prompt_studio")), ],)async def list_criteria( db: AsyncSession = Depends(get_db), workspace: Workspace = Depends(deps.get_active_workspace),) -> Any: """List all qualification criteria for the active workspace.""" result = await db.execute( select(QualificationCriterion) .where(QualificationCriterion.workspace_id == workspace.id) .order_by(QualificationCriterion.sort_order) ) criteria = result.scalars().all() return wrap_data([_criterion_to_dict(c) for c in criteria])
@router.post( "/qualification", response_model=ResponseEnvelope[dict], dependencies=[ Depends(require_module_enabled(MODULE_PROMPT_STUDIO, "write")), Depends(require_entitlement("prompt_studio")), ],)async def create_criterion( body: CriterionCreate, db: AsyncSession = Depends(get_db), workspace: Workspace = Depends(deps.get_active_workspace),) -> Any: """Create a new qualification criterion.""" if not body.label or not body.label.strip(): return wrap_error("Label is required")
if body.criterion_type not in VALID_CRITERION_TYPES: return wrap_error(f"Invalid criterion_type. Must be one of: {', '.join(VALID_CRITERION_TYPES)}")
code = body.code or _slugify(body.label)
# Check uniqueness within workspace existing = await db.execute( select(QualificationCriterion).where( QualificationCriterion.workspace_id == workspace.id, QualificationCriterion.code == code, ) ) if existing.scalars().first(): return wrap_error(f"A criterion with code '{code}' already exists in this workspace")
criterion = QualificationCriterion( workspace_id=workspace.id, code=code, label=body.label.strip(), description=body.description, criterion_type=body.criterion_type, enum_values=body.enum_values, weight=body.weight, sort_order=body.sort_order, is_enabled=body.is_enabled, ) db.add(criterion) await db.commit() await db.refresh(criterion)
return wrap_data(_criterion_to_dict(criterion))
@router.patch( "/qualification/{criterion_id}", response_model=ResponseEnvelope[dict], dependencies=[ Depends(require_module_enabled(MODULE_PROMPT_STUDIO, "write")), Depends(require_entitlement("prompt_studio")), ],)async def update_criterion( criterion_id: UUID, body: CriterionUpdate, db: AsyncSession = Depends(get_db), workspace: Workspace = Depends(deps.get_active_workspace),) -> Any: """Update a qualification criterion.""" result = await db.execute( select(QualificationCriterion).where( QualificationCriterion.id == criterion_id, QualificationCriterion.workspace_id == workspace.id, ) ) criterion = result.scalars().first() if not criterion: raise HTTPException(status_code=404, detail="Criterion not found")
if body.label is not None: criterion.label = body.label.strip() if body.description is not None: criterion.description = body.description if body.criterion_type is not None: if body.criterion_type not in VALID_CRITERION_TYPES: return wrap_error(f"Invalid criterion_type. Must be one of: {', '.join(VALID_CRITERION_TYPES)}") criterion.criterion_type = body.criterion_type if body.enum_values is not None: criterion.enum_values = body.enum_values if body.weight is not None: criterion.weight = body.weight if body.sort_order is not None: criterion.sort_order = body.sort_order if body.is_enabled is not None: criterion.is_enabled = body.is_enabled
await db.commit() await db.refresh(criterion)
return wrap_data(_criterion_to_dict(criterion))
@router.delete( "/qualification/{criterion_id}", response_model=ResponseEnvelope[dict], dependencies=[ Depends(require_module_enabled(MODULE_PROMPT_STUDIO, "write")), Depends(require_entitlement("prompt_studio")), ],)async def delete_criterion( criterion_id: UUID, db: AsyncSession = Depends(get_db), workspace: Workspace = Depends(deps.get_active_workspace),) -> Any: """Delete a qualification criterion.""" result = await db.execute( select(QualificationCriterion).where( QualificationCriterion.id == criterion_id, QualificationCriterion.workspace_id == workspace.id, ) ) criterion = result.scalars().first() if not criterion: raise HTTPException(status_code=404, detail="Criterion not found")
await db.delete(criterion) await db.commit()
return wrap_data({"deleted": True})76 unmodified lines777879808182838476 unmodified linesdb.add(user_msg)await db.flush()# 3. Compile workspace prompt (includes knowledge files + qualification)compiled = await compile_workspace_prompt(workspace.id, db, include_files=True, include_qualification=True)if not compiled.version_id:return wrap_error("No active prompt configuration found for this workspace.")76 unmodified lines777879808182838485868776 unmodified linesdb.add(user_msg)await db.flush()# 3. Compile workspace prompt (includes knowledge chunks + qualification)compiled = await compile_workspace_prompt(workspace.id, db, include_files=True, include_qualification=True,query_hint=text,)if not compiled.version_id:return wrap_error("No active prompt configuration found for this workspace.")
12345678910154 unmodified lines165166167"""Startup seed utilities: Ensures all canonical modules and default plans exist.Runs once on app startup; idempotent (uses INSERT or IGNORE logic via get-or-create)."""import loggingfrom app.core.db import SessionLocal as AsyncSessionLocalfrom app.models.models import SystemModuleConfig, Plan, PlanEntitlement, SystemSettingsfrom app.core.modules import ALL_MODULESfrom sqlmodel import select154 unmodified lineslogger.info("[seed_system_settings] System settings already exist.")except Exception as e:logger.error(f"[seed_system_settings] Failed: {e}", exc_info=True)123456789101112131415154 unmodified lines170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241"""Startup seed utilities: Ensures all canonical modules, default plans, and seed users exist.Runs once on app startup; idempotent (uses INSERT or IGNORE logic via get-or-create)."""import loggingfrom datetime import datetimefrom app.core.db import SessionLocal as AsyncSessionLocalfrom app.core.security import get_password_hashfrom app.models.models import (SystemModuleConfig, Plan, PlanEntitlement, SystemSettings,User, Workspace, WorkspaceMember, WorkspaceRole,)from app.core.modules import ALL_MODULESfrom sqlmodel import select154 unmodified lineslogger.info("[seed_system_settings] System settings already exist.")except Exception as e:logger.error(f"[seed_system_settings] Failed: {e}", exc_info=True)# --- Default seed users ---SEED_USERS = [{"email": "demo@leadpilot.com","password": "demo123456","full_name": "Demo User","is_superuser": False,"workspace_name": "Demo Workspace",},{"email": "admin@leadpilot.com","password": "admin123456","full_name": "Admin","is_superuser": True,"workspace_name": "Admin Workspace",},]async def seed_users():"""Seed demo and admin users with workspaces. Idempotent: skips if email exists.Both users are created with email_verified_at set (no verification required)."""try:async with AsyncSessionLocal() as db:new_count = 0for user_def in SEED_USERS:result = await db.execute(select(User).where(User.email == user_def["email"]))if result.scalars().first():logger.info(f"[seed_users] {user_def['email']} already exists; skipping.")continuenow = datetime.utcnow()user = User(email=user_def["email"],hashed_password=get_password_hash(user_def["password"]),full_name=user_def["full_name"],is_active=True,is_superuser=user_def["is_superuser"],email_verified_at=now,)db.add(user)await db.flush()workspace = Workspace(name=user_def["workspace_name"])db.add(workspace)await db.flush()membership = WorkspaceMember(user_id=user.id,workspace_id=workspace.id,role=WorkspaceRole.OWNER,)db.add(membership)new_count += 1logger.info(f"[seed_users] Created {user_def['email']} (superuser={user_def['is_superuser']}).")if new_count > 0:await db.commit()logger.info(f"[seed_users] Seeded {new_count} user(s).")else:logger.info("[seed_users] All seed users already exist; no action taken.")except Exception as e:logger.error(f"[seed_users] Failed: {e}", exc_info=True)
281 unmodified lines2822832842852862872882892902912922932942952962972982997 unmodified lines307308309310311312281 unmodified linesasync def handle_ai_reply(session: AsyncSession, instance: ExecutionInstance, config: Dict[str, Any]) -> Dict[str, Any]:"""Generates an AI reply using unified prompt compiler + conversation history."""# 1. Compile workspace prompt (includes knowledge files, qualification, step config)compiled = await compile_workspace_prompt(instance.workspace_id,session,include_files=True,include_qualification=True,step_config=config,)if not compiled.version_id:raise Exception("No active PromptConfig found for workspace")# 2. Fetch conversation and history (last 15 messages)conv_result = await session.execute(select(Conversation).where(Conversation.contact_id == instance.contact_id))7 unmodified lineshistory = list(msg_result.scalars().all())history.reverse()messages = []messages.append({"role": "system", "content": compiled.system_instruction})281 unmodified lines2822832842852862872887 unmodified lines296297298299300301302303304305306307308309310311312313314315316317318319320281 unmodified linesasync def handle_ai_reply(session: AsyncSession, instance: ExecutionInstance, config: Dict[str, Any]) -> Dict[str, Any]:"""Generates an AI reply using unified prompt compiler + conversation history."""# 1. Fetch conversation and history (last 15 messages) — needed for query_hintconv_result = await session.execute(select(Conversation).where(Conversation.contact_id == instance.contact_id))7 unmodified lineshistory = list(msg_result.scalars().all())history.reverse()# Extract last user message for chunk-based knowledge retrievallast_user_msg = ""for msg in reversed(history):if msg.direction == "inbound":last_user_msg = msg.content or ""break# 2. Compile workspace prompt (includes knowledge chunks, qualification, step config)compiled = await compile_workspace_prompt(instance.workspace_id,session,include_files=True,include_qualification=True,step_config=config,query_hint=last_user_msg or None,)if not compiled.version_id:raise Exception("No active PromptConfig found for workspace")messages = []messages.append({"role": "system", "content": compiled.system_instruction})
340 unmodified lines3413423433443453465 unmodified lines352353354355356357340 unmodified linesstatus: str = Field(default="READY") # READY | FAILEDclass QualificationConfig(WorkspaceScopedModel, table=True):"""Workspace-scoped lead qualification configuration."""version: int = Field(default=1)5 unmodified lines)class PasswordResetToken(BaseIDModel, table=True):user_id: UUID = Field(foreign_key="user.id", index=True)token_hash: str = Field(index=True)340 unmodified lines3413423433443453463473483493503513523533543553563573583593605 unmodified lines366367368369370371372373374375376377378379380381382383384385386387340 unmodified linesstatus: str = Field(default="READY") # READY | FAILEDclass KnowledgeChunk(SQLModel, table=True):"""Individual text chunk from a knowledge file for retrieval."""id: UUID = Field(default_factory=uuid4, primary_key=True, index=True)created_at: datetime = Field(default_factory=datetime.utcnow)workspace_id: UUID = Field(index=True, foreign_key="workspace.id")knowledge_file_id: UUID = Field(index=True, foreign_key="workspaceknowledgefile.id")chunk_index: int = Field(default=0)content_text: str__table_args__ = (Index("idx_kc_ws_file", "workspace_id", "knowledge_file_id"),)class QualificationConfig(WorkspaceScopedModel, table=True):"""Workspace-scoped lead qualification configuration."""version: int = Field(default=1)5 unmodified lines)class QualificationCriterion(WorkspaceScopedModel, table=True):"""Dynamic lead qualification criterion — stored as rows, not JSON."""code: str = Field(index=True)label: strdescription: Optional[str] = Nonecriterion_type: str = Field(default="boolean") # boolean | enum | text | scoreenum_values: Optional[List[str]] = Field(default=None, sa_column=Column(JSON))weight: Optional[int] = Nonesort_order: int = Field(default=0)is_enabled: bool = Field(default=True)__table_args__ = (UniqueConstraint("workspace_id", "code", name="uq_qualcriterion_ws_code"),)class PasswordResetToken(BaseIDModel, table=True):user_id: UUID = Field(foreign_key="user.id", index=True)token_hash: str = Field(index=True)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188"""Knowledge Chunker Service — Mission 29Handles text chunking for knowledge files and keyword-based retrieval."""import loggingimport refrom typing import Listfrom uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSessionfrom sqlmodel import delete, select
from app.models.models import KnowledgeChunk
logger = logging.getLogger(__name__)
CHUNK_SIZE = 1000CHUNK_OVERLAP = 100
# Common English stopwords to ignore during keyword extraction_STOPWORDS = frozenset({ "a", "an", "the", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "do", "does", "did", "will", "would", "could", "should", "may", "might", "shall", "can", "to", "of", "in", "for", "on", "with", "at", "by", "from", "as", "into", "through", "during", "before", "after", "above", "below", "between", "out", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "each", "every", "both", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "and", "but", "or", "if", "it", "its", "this", "that", "these", "those", "i", "me", "my", "we", "our", "you", "your", "he", "him", "his", "she", "her", "they", "them", "their", "what", "which", "who", "whom",})
def chunk_text(text: str) -> List[str]: """ Split text into overlapping chunks, preferring paragraph/sentence boundaries. Returns list of chunk strings. """ if not text or not text.strip(): return []
text = text.strip() if len(text) <= CHUNK_SIZE: return [text]
chunks: List[str] = [] start = 0
while start < len(text): end = start + CHUNK_SIZE
if end >= len(text): chunks.append(text[start:].strip()) break
# Try to break at paragraph boundary segment = text[start:end] para_break = segment.rfind("\n\n") if para_break > CHUNK_SIZE // 3: end = start + para_break + 2 else: # Try sentence boundary sentence_break = max( segment.rfind(". "), segment.rfind(".\n"), segment.rfind("? "), segment.rfind("! "), ) if sentence_break > CHUNK_SIZE // 3: end = start + sentence_break + 2
chunk = text[start:end].strip() if chunk: chunks.append(chunk)
# Advance with overlap start = end - CHUNK_OVERLAP if end - CHUNK_OVERLAP > start else end
return chunks
async def create_chunks_for_file( db: AsyncSession, workspace_id: UUID, file_id: UUID, text: str,) -> int: """ Delete existing chunks for a file, then create new ones from text. Returns the number of chunks created. """ # Delete old chunks await db.execute( delete(KnowledgeChunk).where( KnowledgeChunk.knowledge_file_id == file_id, ) )
chunks = chunk_text(text) for i, chunk_content in enumerate(chunks): db.add(KnowledgeChunk( workspace_id=workspace_id, knowledge_file_id=file_id, chunk_index=i, content_text=chunk_content, ))
await db.flush() logger.info("Created %d chunks for file %s", len(chunks), file_id) return len(chunks)
def _extract_keywords(text: str, max_keywords: int = 8) -> List[str]: """Extract meaningful keywords from text, filtering stopwords.""" words = re.findall(r"[a-zA-Z0-9]+", text.lower()) seen = set() keywords = [] for w in words: if w not in _STOPWORDS and len(w) >= 3 and w not in seen: seen.add(w) keywords.append(w) if len(keywords) >= max_keywords: break return keywords
async def retrieve_relevant_chunks( db: AsyncSession, workspace_id: UUID, query_text: str, max_chunks: int = 8,) -> List[str]: """ Keyword-based chunk retrieval with recency fallback. Returns list of chunk content strings. """ keywords = _extract_keywords(query_text)
if keywords: # Build ILIKE conditions for each keyword conditions = [] for kw in keywords: conditions.append( KnowledgeChunk.content_text.ilike(f"%{kw}%") )
# Search for chunks matching ANY keyword, order by created_at DESC stmt = ( select(KnowledgeChunk) .where( KnowledgeChunk.workspace_id == workspace_id, ) .filter(*[ # Use OR: match any keyword ]) )
# Build OR condition manually from sqlalchemy import or_ stmt = ( select(KnowledgeChunk) .where( KnowledgeChunk.workspace_id == workspace_id, or_(*conditions), ) .order_by(KnowledgeChunk.created_at.desc()) .limit(max_chunks) )
result = await db.execute(stmt) chunks = result.scalars().all()
if chunks: return [c.content_text for c in chunks]
# Fallback: most recent chunks regardless of keyword match stmt = ( select(KnowledgeChunk) .where(KnowledgeChunk.workspace_id == workspace_id) .order_by(KnowledgeChunk.created_at.desc()) .limit(max_chunks) ) result = await db.execute(stmt) chunks = result.scalars().all() return [c.content_text for c in chunks]1234511 unmodified lines1718192021223 unmodified lines26272829303132333418 unmodified lines53545556575811 unmodified lines70717273747537 unmodified lines11311411511611711811912012112212312412512612712812913013113213313413513613713813914015 unmodified lines15615715815916016114 unmodified lines176177178179180181"""Prompt Compiler Service — Mission 20Single source of truth for workspace AI context compilation.Used by Test Chat AND Runtime AI_REPLY."""11 unmodified linesPromptVersion,WorkspaceKnowledgeFile,QualificationConfig,)logger = logging.getLogger(__name__)3 unmodified linesSEP_GUARDRAILS = "=== GUARDRAILS ==="SEP_KNOWLEDGE_BASE = "=== KNOWLEDGE BASE (FILES) ==="SEP_QUALIFICATION = "=== LEAD QUALIFICATION ==="SEP_STEP_GOAL = "=== STEP GOAL ==="SEP_TASKS = "=== TASKS ==="SEP_STEP_INSTRUCTIONS = "=== STEP INSTRUCTIONS ==="# Max chars per knowledge file excerptMAX_CHARS_PER_FILE = 400018 unmodified linesinclude_files: bool = True,include_qualification: bool = True,step_config: Optional[Dict[str, Any]] = None,) -> CompiledPrompt:"""Assemble the full system instruction for a workspace.11 unmodified linesstep_config : Optional[Dict]If provided, appends step-level goal/tasks/extra_instructions(used by runtime AI_REPLY for automation steps).Returns-------37 unmodified linessections.append(f"\n{SEP_GUARDRAILS}")sections.append(json.dumps(version.guardrails_json, indent=2))# 3. Knowledge fileskb_count = 0if include_files:files_result = await db.execute(select(WorkspaceKnowledgeFile).where(WorkspaceKnowledgeFile.workspace_id == workspace_id,WorkspaceKnowledgeFile.extracted_text.isnot(None),WorkspaceKnowledgeFile.status == "READY",))files = files_result.scalars().all()if files:sections.append(f"\n{SEP_KNOWLEDGE_BASE}")for f in files:text = f.extracted_textif len(text) > MAX_CHARS_PER_FILE:text = text[:MAX_CHARS_PER_FILE] + "\n[... truncated]"sections.append(f"--- {f.filename} ---")sections.append(text)kb_count = len(files)# 4. Qualification configqual_count = 0if include_qualification:qual_result = await db.execute(15 unmodified linessections.append(f"- {q['label']}")qual_count = len(enabled_questions)# 5. Step-level overrides (for automation AI_REPLY nodes)if step_config:goal = step_config.get("goal")14 unmodified linessections.append(f"\n{SEP_STEP_INSTRUCTIONS}")sections.append(extra)return CompiledPrompt(system_instruction="\n".join(sections),temperature=version.temperature,1234511 unmodified lines171819202122233 unmodified lines272829303132333435363718 unmodified lines5657585960616211 unmodified lines74757677787980818237 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916015 unmodified lines17617717817918018118218318418518618718818919019119219319419519619719819920020120214 unmodified lines217218219220221222223224225226227228229230231232233"""Prompt Compiler Service — Mission 20 + Mission 29 enhancementsSingle source of truth for workspace AI context compilation.Used by Test Chat AND Runtime AI_REPLY."""11 unmodified linesPromptVersion,WorkspaceKnowledgeFile,QualificationConfig,QualificationCriterion,)logger = logging.getLogger(__name__)3 unmodified linesSEP_GUARDRAILS = "=== GUARDRAILS ==="SEP_KNOWLEDGE_BASE = "=== KNOWLEDGE BASE (FILES) ==="SEP_QUALIFICATION = "=== LEAD QUALIFICATION ==="SEP_QUALIFICATION_CRITERIA = "=== QUALIFICATION CRITERIA ==="SEP_STEP_GOAL = "=== STEP GOAL ==="SEP_TASKS = "=== TASKS ==="SEP_STEP_INSTRUCTIONS = "=== STEP INSTRUCTIONS ==="SEP_EXPECTED_OUTPUTS = "=== EXPECTED OUTPUTS ==="# Max chars per knowledge file excerptMAX_CHARS_PER_FILE = 400018 unmodified linesinclude_files: bool = True,include_qualification: bool = True,step_config: Optional[Dict[str, Any]] = None,query_hint: Optional[str] = None,) -> CompiledPrompt:"""Assemble the full system instruction for a workspace.11 unmodified linesstep_config : Optional[Dict]If provided, appends step-level goal/tasks/extra_instructions(used by runtime AI_REPLY for automation steps).query_hint : Optional[str]If provided, uses keyword-based chunk retrieval instead of fullfile text. Pass the last user message for relevance matching.Returns-------37 unmodified linessections.append(f"\n{SEP_GUARDRAILS}")sections.append(json.dumps(version.guardrails_json, indent=2))# 3. Knowledge files / chunkskb_count = 0if include_files:if query_hint:# Mission 29: Use chunk-based retrieval for smarter contextfrom app.services.knowledge_chunker import retrieve_relevant_chunkschunk_texts = await retrieve_relevant_chunks(db, workspace_id, query_hint, max_chunks=8,)if chunk_texts:sections.append(f"\n{SEP_KNOWLEDGE_BASE}")for ct in chunk_texts:sections.append(ct)kb_count = len(chunk_texts)else:# Backward compat: include full file excerptsfiles_result = await db.execute(select(WorkspaceKnowledgeFile).where(WorkspaceKnowledgeFile.workspace_id == workspace_id,WorkspaceKnowledgeFile.extracted_text.isnot(None),WorkspaceKnowledgeFile.status == "READY",))files = files_result.scalars().all()if files:sections.append(f"\n{SEP_KNOWLEDGE_BASE}")for f in files:text = f.extracted_textif len(text) > MAX_CHARS_PER_FILE:text = text[:MAX_CHARS_PER_FILE] + "\n[... truncated]"sections.append(f"--- {f.filename} ---")sections.append(text)kb_count = len(files)# 4. Qualification config (questions to collect)qual_count = 0if include_qualification:qual_result = await db.execute(15 unmodified linessections.append(f"- {q['label']}")qual_count = len(enabled_questions)# 4b. Qualification criteria (evaluation rules — Mission 29)if include_qualification:criteria_result = await db.execute(select(QualificationCriterion).where(QualificationCriterion.workspace_id == workspace_id,QualificationCriterion.is_enabled.is_(True),).order_by(QualificationCriterion.sort_order))criteria = criteria_result.scalars().all()if criteria:sections.append(f"\n{SEP_QUALIFICATION_CRITERIA}")sections.append("Evaluate each lead against these criteria:")for c in criteria:line = f"- {c.label}"if c.description:line += f": {c.description}"line += f" [type: {c.criterion_type}]"if c.criterion_type == "enum" and c.enum_values:line += f" (options: {', '.join(c.enum_values)})"sections.append(line)# 5. Step-level overrides (for automation AI_REPLY nodes)if step_config:goal = step_config.get("goal")14 unmodified linessections.append(f"\n{SEP_STEP_INSTRUCTIONS}")sections.append(extra)# Mission 29: Output schemaoutput_schema = step_config.get("output_schema", [])if output_schema:sections.append(f"\n{SEP_EXPECTED_OUTPUTS}")sections.append("Extract and return the following data points:")for field in output_schema:if isinstance(field, dict):sections.append(f"- {field.get('key', '')}: {field.get('label', '')}")return CompiledPrompt(system_instruction="\n".join(sections),temperature=version.temperature,
4 unmodified lines5678910118 unmodified lines20212223242511 unmodified lines373839404142121 unmodified lines1641651661671681694 unmodified linesfrom app.core.config import settingsfrom app.core.db import enginefrom app.api.v1 import auth, workspaces, health, prompt_config, test_chat, integrations, webhooks, automations, knowledge, analytics, templatesfrom app.core.seed import seed_modules, seed_plans, seed_system_settingsfrom app.api.v1.dispatch import router as dispatch_routerfrom app.api.v1.inbox import router as inbox_routerfrom app.api.v1.zoho import router as zoho_router8 unmodified linesfrom app.api.v1.qualification import router as qualification_routerfrom app.api.v1.entitlements import router as entitlements_routerfrom app.api.v1.settings_profile import router as settings_profile_routerfrom fastapi import HTTPExceptionimport uuidimport logging11 unmodified linesawait seed_modules()await seed_plans()await seed_system_settings()yieldapp = FastAPI(121 unmodified linesapp.include_router(qualification_router, prefix=f"{settings.API_V1_STR}/qualification-config", tags=["qualification"])app.include_router(entitlements_router, prefix=f"{settings.API_V1_STR}/entitlements", tags=["entitlements"])app.include_router(settings_profile_router, prefix=f"{settings.API_V1_STR}/settings", tags=["settings-profile"])@app.get("/")async def root():4 unmodified lines5678910118 unmodified lines2021222324252611 unmodified lines38394041424344121 unmodified lines1661671681691701711724 unmodified linesfrom app.core.config import settingsfrom app.core.db import enginefrom app.api.v1 import auth, workspaces, health, prompt_config, test_chat, integrations, webhooks, automations, knowledge, analytics, templatesfrom app.core.seed import seed_modules, seed_plans, seed_system_settings, seed_usersfrom app.api.v1.dispatch import router as dispatch_routerfrom app.api.v1.inbox import router as inbox_routerfrom app.api.v1.zoho import router as zoho_router8 unmodified linesfrom app.api.v1.qualification import router as qualification_routerfrom app.api.v1.entitlements import router as entitlements_routerfrom app.api.v1.settings_profile import router as settings_profile_routerfrom app.api.v1.qualification_criteria import router as qual_criteria_routerfrom fastapi import HTTPExceptionimport uuidimport logging11 unmodified linesawait seed_modules()await seed_plans()await seed_system_settings()await seed_users()yieldapp = FastAPI(121 unmodified linesapp.include_router(qualification_router, prefix=f"{settings.API_V1_STR}/qualification-config", tags=["qualification"])app.include_router(entitlements_router, prefix=f"{settings.API_V1_STR}/entitlements", tags=["entitlements"])app.include_router(settings_profile_router, prefix=f"{settings.API_V1_STR}/settings", tags=["settings-profile"])app.include_router(qual_criteria_router, prefix=f"{settings.API_V1_STR}/prompt-studio", tags=["prompt-studio"])@app.get("/")async def root():
23 unmodified lines24252623 unmodified linesaiosmtplibjinja2python-dotenv23 unmodified lines242526272823 unmodified linesaiosmtplibjinja2python-dotenvpython-docx>=1.1.0openpyxl>=3.1.0
1 unmodified line23456735 unmodified lines4344454647484958 unmodified lines10810911011111211311 unmodified lines1251261271281291 unmodified lineimport osimport asyncioimport logging# Add the parent directory to sys.path to allow importing from 'app'# This assumes the script is in backend/scripts/35 unmodified lineshashed_password=security.get_password_hash("Password123!"),full_name="Test User",is_active=True,is_superuser=True)session.add(db_user)await session.flush()58 unmodified linesfull_name="LeadPilot Admin",is_active=True,is_superuser=True,)session.add(db_admin)await session.flush()11 unmodified linesawait session.commit()logger.info(f"Admin user {admin_email} created successfully.")if __name__ == "__main__":asyncio.run(create_test_user())1 unmodified line234567835 unmodified lines444546474849505158 unmodified lines11011111211311411511611 unmodified lines1281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961 unmodified lineimport osimport asyncioimport loggingfrom datetime import datetime# Add the parent directory to sys.path to allow importing from 'app'# This assumes the script is in backend/scripts/35 unmodified lineshashed_password=security.get_password_hash("Password123!"),full_name="Test User",is_active=True,is_superuser=True,email_verified_at=datetime.utcnow(),)session.add(db_user)await session.flush()58 unmodified linesfull_name="LeadPilot Admin",is_active=True,is_superuser=True,email_verified_at=datetime.utcnow(),)session.add(db_admin)await session.flush()11 unmodified linesawait session.commit()logger.info(f"Admin user {admin_email} created successfully.")# --- Seed studio demo user (demo@leadpilot.com) ---async with async_session() as session:demo_email = "demo@leadpilot.com"result = await session.execute(select(User).where(User.email == demo_email))if result.scalars().first():logger.info(f"Demo user {demo_email} already exists.")else:logger.info(f"Creating demo user: {demo_email}")db_demo = User(email=demo_email,hashed_password=security.get_password_hash("demo123456"),full_name="Demo User",is_active=True,is_superuser=False,email_verified_at=datetime.utcnow(),)session.add(db_demo)await session.flush()db_demo_ws = Workspace(name="Demo Workspace")session.add(db_demo_ws)await session.flush()db_demo_member = WorkspaceMember(user_id=db_demo.id,workspace_id=db_demo_ws.id,role=WorkspaceRole.OWNER,)session.add(db_demo_member)await session.commit()logger.info(f"Demo user {demo_email} created successfully.")# --- Seed superadmin (admin@leadpilot.com) ---async with async_session() as session:sa_email = "admin@leadpilot.com"result = await session.execute(select(User).where(User.email == sa_email))if result.scalars().first():logger.info(f"Superadmin {sa_email} already exists.")else:logger.info(f"Creating superadmin: {sa_email}")db_sa = User(email=sa_email,hashed_password=security.get_password_hash("admin123456"),full_name="Admin",is_active=True,is_superuser=True,email_verified_at=datetime.utcnow(),)session.add(db_sa)await session.flush()db_sa_ws = Workspace(name="Admin Workspace")session.add(db_sa_ws)await session.flush()db_sa_member = WorkspaceMember(user_id=db_sa.id,workspace_id=db_sa_ws.id,role=WorkspaceRole.OWNER,)session.add(db_sa_member)await session.commit()logger.info(f"Superadmin {sa_email} created successfully.")if __name__ == "__main__":asyncio.run(create_test_user())
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294"""Comprehensive auth tests covering studio login, admin login, token validation,role checks, and email verification edge cases."""import pytestfrom datetime import datetime, timedeltafrom httpx import AsyncClientfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlmodel import select
from app.models.models import User, Workspace, WorkspaceMember, WorkspaceRolefrom app.core.security import get_password_hash, create_access_token
# ── Helpers ──────────────────────────────────────────────────────────────
async def _create_user( db: AsyncSession, email: str, password: str = "testpass123", full_name: str = "Test User", is_superuser: bool = False, is_active: bool = True, verified: bool = True, with_workspace: bool = True,) -> User: """Insert a user directly into DB. Returns the User object.""" now = datetime.utcnow() user = User( email=email, hashed_password=get_password_hash(password), full_name=full_name, is_active=is_active, is_superuser=is_superuser, email_verified_at=now if verified else None, email_verification_expires_at=( now + timedelta(days=7) if not verified else None ), ) db.add(user) await db.flush()
if with_workspace: ws = Workspace(name=f"{email}'s Workspace") db.add(ws) await db.flush() mem = WorkspaceMember( user_id=user.id, workspace_id=ws.id, role=WorkspaceRole.OWNER, ) db.add(mem) await db.flush()
return user
def _auth_header(token: str) -> dict: return {"Authorization": f"Bearer {token}"}
# ── Studio Auth Tests ────────────────────────────────────────────────────
@pytest.mark.asyncioasync def test_studio_login_success(async_client: AsyncClient, db_session: AsyncSession): """Login with correct credentials returns access_token.""" await _create_user(db_session, "studio_ok@test.com") r = await async_client.post( "/api/v1/auth/login", data={"username": "studio_ok@test.com", "password": "testpass123"}, headers={"content-type": "application/x-www-form-urlencoded"}, ) assert r.status_code == 200 d = r.json() assert d["success"] is True assert "access_token" in d["data"] assert d["data"]["token_type"] == "bearer"
@pytest.mark.asyncioasync def test_studio_login_wrong_password(async_client: AsyncClient, db_session: AsyncSession): """Login with wrong password returns error.""" await _create_user(db_session, "studio_wrong@test.com") r = await async_client.post( "/api/v1/auth/login", data={"username": "studio_wrong@test.com", "password": "wrongpassword"}, headers={"content-type": "application/x-www-form-urlencoded"}, ) d = r.json() assert d["success"] is False
@pytest.mark.asyncioasync def test_studio_login_nonexistent(async_client: AsyncClient): """Login with non-existent user returns error.""" r = await async_client.post( "/api/v1/auth/login", data={"username": "ghost@test.com", "password": "anything"}, headers={"content-type": "application/x-www-form-urlencoded"}, ) d = r.json() assert d["success"] is False
@pytest.mark.asyncioasync def test_studio_login_inactive_user(async_client: AsyncClient, db_session: AsyncSession): """Login with inactive user returns error.""" await _create_user(db_session, "inactive@test.com", is_active=False) r = await async_client.post( "/api/v1/auth/login", data={"username": "inactive@test.com", "password": "testpass123"}, headers={"content-type": "application/x-www-form-urlencoded"}, ) d = r.json() assert d["success"] is False assert "inactive" in d["error"].lower()
@pytest.mark.asyncioasync def test_get_me_valid_token(async_client: AsyncClient, db_session: AsyncSession): """GET /me with valid token returns user data.""" user = await _create_user(db_session, "me_valid@test.com") token = create_access_token(user.id) r = await async_client.get("/api/v1/auth/me", headers=_auth_header(token)) assert r.status_code == 200 d = r.json() assert d["success"] is True assert d["data"]["email"] == "me_valid@test.com"
@pytest.mark.asyncioasync def test_get_me_no_token(async_client: AsyncClient): """GET /me with no auth header returns 401 or 403.""" r = await async_client.get("/api/v1/auth/me") assert r.status_code in (401, 403)
@pytest.mark.asyncioasync def test_get_me_invalid_token(async_client: AsyncClient): """GET /me with garbage token returns 403.""" r = await async_client.get( "/api/v1/auth/me", headers=_auth_header("not.a.real.jwt.token"), ) assert r.status_code in (401, 403)
@pytest.mark.asyncioasync def test_get_me_expired_token(async_client: AsyncClient, db_session: AsyncSession): """GET /me with expired token returns 403.""" user = await _create_user(db_session, "expired@test.com") token = create_access_token(user.id, expires_delta=timedelta(seconds=-1)) r = await async_client.get("/api/v1/auth/me", headers=_auth_header(token)) assert r.status_code in (401, 403)
@pytest.mark.asyncioasync def test_duplicate_signup(async_client: AsyncClient, db_session: AsyncSession): """Signup with existing email returns error.""" await _create_user(db_session, "dup@test.com") r = await async_client.post( "/api/v1/auth/signup", json={"email": "dup@test.com", "password": "testpass123", "full_name": "Dup"}, ) d = r.json() assert d["success"] is False assert "already exists" in d["error"].lower()
# ── Admin Auth Tests ─────────────────────────────────────────────────────
@pytest.mark.asyncioasync def test_admin_login_success(async_client: AsyncClient, db_session: AsyncSession): """Admin login with superuser returns access_token.""" await _create_user(db_session, "admin_ok@test.com", is_superuser=True) r = await async_client.post( "/api/v1/admin_auth/login", json={"email": "admin_ok@test.com", "password": "testpass123"}, ) d = r.json() assert d["success"] is True assert "access_token" in d["data"]
@pytest.mark.asyncioasync def test_admin_login_non_superuser(async_client: AsyncClient, db_session: AsyncSession): """Admin login with non-superuser is rejected.""" await _create_user(db_session, "nonadmin@test.com", is_superuser=False) r = await async_client.post( "/api/v1/admin_auth/login", json={"email": "nonadmin@test.com", "password": "testpass123"}, ) d = r.json() assert d["success"] is False assert "admin" in d["error"].lower() or "privileges" in d["error"].lower()
@pytest.mark.asyncioasync def test_admin_login_wrong_password(async_client: AsyncClient, db_session: AsyncSession): """Admin login with wrong password returns error.""" await _create_user(db_session, "admin_wrong@test.com", is_superuser=True) r = await async_client.post( "/api/v1/admin_auth/login", json={"email": "admin_wrong@test.com", "password": "wrongpass"}, ) d = r.json() assert d["success"] is False
@pytest.mark.asyncioasync def test_admin_login_inactive(async_client: AsyncClient, db_session: AsyncSession): """Admin login with inactive superuser returns error.""" await _create_user(db_session, "admin_inactive@test.com", is_superuser=True, is_active=False) r = await async_client.post( "/api/v1/admin_auth/login", json={"email": "admin_inactive@test.com", "password": "testpass123"}, ) d = r.json() assert d["success"] is False assert "disabled" in d["error"].lower()
@pytest.mark.asyncioasync def test_admin_me_superuser(async_client: AsyncClient, db_session: AsyncSession): """Admin /me with superuser token returns admin data.""" user = await _create_user(db_session, "admin_me@test.com", is_superuser=True) token = create_access_token(user.id) r = await async_client.get("/api/v1/admin_auth/me", headers=_auth_header(token)) assert r.status_code == 200 d = r.json() assert d["success"] is True assert d["data"]["is_superuser"] is True
@pytest.mark.asyncioasync def test_admin_me_non_superuser(async_client: AsyncClient, db_session: AsyncSession): """Admin /me with non-superuser token returns 403.""" user = await _create_user(db_session, "admin_me_norole@test.com", is_superuser=False) token = create_access_token(user.id) r = await async_client.get("/api/v1/admin_auth/me", headers=_auth_header(token)) assert r.status_code == 403
@pytest.mark.asyncioasync def test_admin_me_no_token(async_client: AsyncClient): """Admin /me with no token returns 401 or 403.""" r = await async_client.get("/api/v1/admin_auth/me") assert r.status_code in (401, 403)
@pytest.mark.asyncioasync def test_admin_endpoint_non_superuser_blocked(async_client: AsyncClient, db_session: AsyncSession): """Non-superuser cannot access admin endpoints.""" user = await _create_user(db_session, "admin_blocked@test.com", is_superuser=False) token = create_access_token(user.id) r = await async_client.get("/api/v1/admin/modules", headers=_auth_header(token)) assert r.status_code == 403
# ── Verification Grace Period Edge Cases ─────────────────────────────────
@pytest.mark.asyncioasync def test_unverified_within_grace_can_access(async_client: AsyncClient, db_session: AsyncSession): """Unverified user within grace period can access /me.""" user = await _create_user(db_session, "grace_ok@test.com", verified=False) # Ensure grace period is in the future user.email_verification_expires_at = datetime.utcnow() + timedelta(days=7) db_session.add(user) await db_session.flush()
token = create_access_token(user.id) r = await async_client.get("/api/v1/auth/me", headers=_auth_header(token)) assert r.status_code == 200 d = r.json() assert d["data"]["requires_email_verification"] is True
@pytest.mark.asyncioasync def test_unverified_past_grace_blocked(async_client: AsyncClient, db_session: AsyncSession): """Unverified user past grace period is blocked.""" user = await _create_user(db_session, "grace_expired@test.com", verified=False) # Set grace period in the past user.email_verification_expires_at = datetime.utcnow() - timedelta(days=1) db_session.add(user) await db_session.flush()
token = create_access_token(user.id) r = await async_client.get("/api/v1/auth/me", headers=_auth_header(token)) assert r.status_code == 403 assert "grace period" in r.json().get("error", "").lower()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195"""Mission 29: Knowledge Chunks TestsTests file upload creates chunks, cascade delete, and chunk retrieval."""import ioimport pytestimport pytest_asynciofrom typing import Optionalfrom uuid import UUID, uuid4from httpx import AsyncClientfrom sqlalchemy.ext.asyncio import AsyncSessionfrom sqlmodel import select
from app.models.models import ( Workspace, WorkspaceMember, SystemModuleConfig, KnowledgeChunk,)from app.core.modules import module_cachefrom app.services.knowledge_chunker import chunk_text, retrieve_relevant_chunks
# ── Helpers ─────────────────────────────────────────────────────────
async def _signup_and_login(client: AsyncClient, email: str) -> str: await client.post("/api/v1/auth/signup", json={ "email": email, "password": "securepassword123", "full_name": "KB User", }) login = await client.post( "/api/v1/auth/login", data={"username": email, "password": "securepassword123"}, headers={"content-type": "application/x-www-form-urlencoded"}, ) return login.json()["data"]["access_token"]
def _auth(token: str, workspace_id: Optional[str] = None) -> dict: headers = {"Authorization": f"Bearer {token}"} if workspace_id: headers["X-Workspace-ID"] = workspace_id return headers
@pytest.fixture(autouse=True)def clear_module_cache(): module_cache._cache.clear() yield module_cache._cache.clear()
@pytest_asyncio.fixtureasync def kb_setup(async_client: AsyncClient, db_session: AsyncSession): """Create user + workspace + modules for knowledge tests.""" token = await _signup_and_login(async_client, "kbchunk@example.com")
ws = Workspace(id=uuid4(), name="KB Chunk WS", subscription_tier="free") db_session.add(ws)
me_res = await async_client.get("/api/v1/auth/me", headers=_auth(token)) user_id = UUID(me_res.json()["data"]["id"])
member = WorkspaceMember(user_id=user_id, workspace_id=ws.id, role="owner") db_session.add(member)
for mod in ["knowledge_files", "prompt_studio"]: db_session.add(SystemModuleConfig(module_name=mod, is_enabled=True))
await db_session.flush() return {"token": token, "workspace": ws}
# ── Unit Tests: chunk_text ─────────────────────────────────────────
def test_chunk_text_short(): """Short text should return a single chunk.""" result = chunk_text("Hello world") assert len(result) == 1 assert result[0] == "Hello world"
def test_chunk_text_empty(): """Empty text should return empty list.""" assert chunk_text("") == [] assert chunk_text(" ") == []
def test_chunk_text_long(): """Long text should be split into multiple chunks.""" text = "A" * 3000 chunks = chunk_text(text) assert len(chunks) > 1 # All original text should be covered total = sum(len(c) for c in chunks) # Due to overlap, total chars > original but all content is covered assert total >= 3000
def test_chunk_text_paragraph_boundaries(): """Chunks should prefer paragraph boundaries.""" text = ("First paragraph. " * 30) + "\n\n" + ("Second paragraph. " * 30) chunks = chunk_text(text) assert len(chunks) >= 2
# ── Integration Tests ──────────────────────────────────────────────
@pytest.mark.asyncioasync def test_upload_creates_chunks(async_client: AsyncClient, kb_setup, db_session: AsyncSession): setup = kb_setup headers = _auth(setup["token"], str(setup["workspace"].id))
file_content = b"This is a test knowledge file with important pricing information.\n" * 20
response = await async_client.post( "/api/v1/knowledge/files", files={"file": ("test.txt", io.BytesIO(file_content), "text/plain")}, headers=headers, ) assert response.status_code == 200 data = response.json() assert data["success"] is True assert data["data"]["extracted"] is True assert data["data"]["chunk_count"] > 0
# Verify chunks in DB file_id = UUID(data["data"]["id"]) result = await db_session.execute( select(KnowledgeChunk).where(KnowledgeChunk.knowledge_file_id == file_id) ) chunks = result.scalars().all() assert len(chunks) == data["data"]["chunk_count"] assert all(c.workspace_id == setup["workspace"].id for c in chunks)
@pytest.mark.asyncioasync def test_delete_cascades_chunks(async_client: AsyncClient, kb_setup, db_session: AsyncSession): setup = kb_setup headers = _auth(setup["token"], str(setup["workspace"].id))
file_content = b"Some content for cascade test.\n" * 10
# Upload upload_res = await async_client.post( "/api/v1/knowledge/files", files={"file": ("cascade.txt", io.BytesIO(file_content), "text/plain")}, headers=headers, ) file_id = upload_res.json()["data"]["id"]
# Verify chunks exist result = await db_session.execute( select(KnowledgeChunk).where(KnowledgeChunk.knowledge_file_id == UUID(file_id)) ) assert len(result.scalars().all()) > 0
# Delete file del_res = await async_client.delete(f"/api/v1/knowledge/files/{file_id}", headers=headers) assert del_res.status_code == 200
# Verify chunks deleted result = await db_session.execute( select(KnowledgeChunk).where(KnowledgeChunk.knowledge_file_id == UUID(file_id)) ) assert len(result.scalars().all()) == 0
@pytest.mark.asyncioasync def test_chunk_retrieval_keyword(db_session: AsyncSession): """Test keyword-based chunk retrieval.""" ws_id = uuid4() file_id = uuid4()
# Create test chunks chunks_data = [ "Our premium pricing starts at $500 per month for the basic plan.", "Customer support is available 24/7 via phone and email.", "The enterprise plan includes advanced analytics and reporting.", "Our team has over 10 years of experience in marketing automation.", ] for i, text in enumerate(chunks_data): db_session.add(KnowledgeChunk( workspace_id=ws_id, knowledge_file_id=file_id, chunk_index=i, content_text=text, )) await db_session.flush()
# Search for pricing-related content results = await retrieve_relevant_chunks(db_session, ws_id, "What is the pricing?") assert len(results) > 0 assert any("pricing" in r.lower() for r in results)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Mission 29: Enhanced Prompt Compilation TestsTests qualification criteria, output schema, and chunk retrieval in compiled prompts."""import pytestimport pytest_asynciofrom uuid import uuid4from sqlalchemy.ext.asyncio import AsyncSession
from app.models.models import ( PromptConfig, PromptVersion, QualificationCriterion, KnowledgeChunk,)from app.services.prompt_compiler import compile_workspace_prompt
# ── Tests ───────────────────────────────────────────────────────────
@pytest.mark.asyncioasync def test_compile_includes_qualification_criteria(db_session: AsyncSession): """Compiled prompt should include qualification criteria section.""" ws_id = uuid4()
# Create prompt config + version config = PromptConfig(workspace_id=ws_id, name="Test Config") db_session.add(config) await db_session.flush()
version = PromptVersion( prompt_config_id=config.id, version_number=1, system_prompt_text="You are a sales assistant.", business_profile_json={}, guardrails_json={}, structured_data={}, model="gemini", temperature=0.7, max_tokens_per_execution=1000, ) db_session.add(version) await db_session.flush() config.current_version_id = version.id await db_session.flush()
# Add criteria db_session.add(QualificationCriterion( workspace_id=ws_id, code="budget_check", label="Budget Above $5K", description="Lead stated budget exceeds $5,000", criterion_type="boolean", is_enabled=True, sort_order=0, )) db_session.add(QualificationCriterion( workspace_id=ws_id, code="company_size", label="Company Size", criterion_type="enum", enum_values=["small", "medium", "large"], is_enabled=True, sort_order=1, )) db_session.add(QualificationCriterion( workspace_id=ws_id, code="disabled_one", label="Disabled Criterion", criterion_type="text", is_enabled=False, sort_order=2, )) await db_session.flush()
compiled = await compile_workspace_prompt(ws_id, db_session)
assert "=== QUALIFICATION CRITERIA ===" in compiled.system_instruction assert "Budget Above $5K" in compiled.system_instruction assert "Company Size" in compiled.system_instruction assert "options: small, medium, large" in compiled.system_instruction # Disabled criterion should NOT appear assert "Disabled Criterion" not in compiled.system_instruction
@pytest.mark.asyncioasync def test_compile_includes_output_schema(db_session: AsyncSession): """Step config with output_schema should add EXPECTED OUTPUTS section.""" ws_id = uuid4()
config = PromptConfig(workspace_id=ws_id, name="Test Config") db_session.add(config) await db_session.flush()
version = PromptVersion( prompt_config_id=config.id, version_number=1, system_prompt_text="You are a helpful assistant.", business_profile_json={}, guardrails_json={}, structured_data={}, model="gemini", temperature=0.7, max_tokens_per_execution=1000, ) db_session.add(version) await db_session.flush() config.current_version_id = version.id await db_session.flush()
step_config = { "goal": "Collect lead info", "tasks": ["Ask for name", "Ask for budget"], "output_schema": [ {"key": "name", "label": "Full Name"}, {"key": "budget", "label": "Budget Range"}, ], }
compiled = await compile_workspace_prompt( ws_id, db_session, step_config=step_config, )
assert "=== EXPECTED OUTPUTS ===" in compiled.system_instruction assert "name: Full Name" in compiled.system_instruction assert "budget: Budget Range" in compiled.system_instruction
@pytest.mark.asyncioasync def test_compile_chunk_retrieval(db_session: AsyncSession): """When query_hint is provided, should use chunk retrieval.""" ws_id = uuid4() file_id = uuid4()
config = PromptConfig(workspace_id=ws_id, name="Test Config") db_session.add(config) await db_session.flush()
version = PromptVersion( prompt_config_id=config.id, version_number=1, system_prompt_text="You are a helpful assistant.", business_profile_json={}, guardrails_json={}, structured_data={}, model="gemini", temperature=0.7, max_tokens_per_execution=1000, ) db_session.add(version) await db_session.flush() config.current_version_id = version.id await db_session.flush()
# Add knowledge chunks db_session.add(KnowledgeChunk( workspace_id=ws_id, knowledge_file_id=file_id, chunk_index=0, content_text="Our premium pricing starts at $500 per month.", )) db_session.add(KnowledgeChunk( workspace_id=ws_id, knowledge_file_id=file_id, chunk_index=1, content_text="Customer support is available 24/7 via phone.", )) await db_session.flush()
# Compile with query_hint about pricing compiled = await compile_workspace_prompt( ws_id, db_session, query_hint="What is the pricing?", )
assert "=== KNOWLEDGE BASE (FILES) ===" in compiled.system_instruction assert "pricing" in compiled.system_instruction.lower() assert compiled.knowledge_file_count > 0
@pytest.mark.asyncioasync def test_compile_backward_compat_no_query_hint(db_session: AsyncSession): """Without query_hint, should still work (backward compat).""" ws_id = uuid4()
config = PromptConfig(workspace_id=ws_id, name="Test Config") db_session.add(config) await db_session.flush()
version = PromptVersion( prompt_config_id=config.id, version_number=1, system_prompt_text="You are a helpful assistant.", business_profile_json={}, guardrails_json={}, structured_data={}, model="gemini", temperature=0.7, max_tokens_per_execution=1000, ) db_session.add(version) await db_session.flush() config.current_version_id = version.id await db_session.flush()
# Should not raise compiled = await compile_workspace_prompt(ws_id, db_session) assert "You are a helpful assistant." in compiled.system_instruction123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201"""Mission 29: Qualification Criteria TestsTests CRUD operations for dynamic lead qualification criteria."""import pytestimport pytest_asynciofrom typing import Optionalfrom uuid import UUID, uuid4from httpx import AsyncClientfrom sqlalchemy.ext.asyncio import AsyncSession
from app.models.models import ( Workspace, WorkspaceMember, SystemModuleConfig,)from app.core.modules import module_cache
# ── Helpers ─────────────────────────────────────────────────────────
async def _signup_and_login(client: AsyncClient, email: str) -> str: await client.post("/api/v1/auth/signup", json={ "email": email, "password": "securepassword123", "full_name": "Criteria User", }) login = await client.post( "/api/v1/auth/login", data={"username": email, "password": "securepassword123"}, headers={"content-type": "application/x-www-form-urlencoded"}, ) return login.json()["data"]["access_token"]
def _auth(token: str, workspace_id: Optional[str] = None) -> dict: headers = {"Authorization": f"Bearer {token}"} if workspace_id: headers["X-Workspace-ID"] = workspace_id return headers
@pytest.fixture(autouse=True)def clear_module_cache(): module_cache._cache.clear() yield module_cache._cache.clear()
@pytest_asyncio.fixtureasync def criteria_setup(async_client: AsyncClient, db_session: AsyncSession): """Create user + workspace + modules for criteria tests.""" token = await _signup_and_login(async_client, "criteria@example.com")
ws = Workspace(id=uuid4(), name="Criteria WS", subscription_tier="free") db_session.add(ws)
me_res = await async_client.get("/api/v1/auth/me", headers=_auth(token)) user_id = UUID(me_res.json()["data"]["id"])
member = WorkspaceMember(user_id=user_id, workspace_id=ws.id, role="owner") db_session.add(member)
db_session.add(SystemModuleConfig(module_name="prompt_studio", is_enabled=True)) await db_session.flush()
return {"token": token, "workspace": ws}
# ── Tests ───────────────────────────────────────────────────────────
@pytest.mark.asyncioasync def test_create_criterion(async_client: AsyncClient, criteria_setup): setup = criteria_setup headers = _auth(setup["token"], str(setup["workspace"].id))
response = await async_client.post("/api/v1/prompt-studio/qualification", json={ "label": "Budget Above $10K", "description": "Lead has stated budget exceeding $10,000", "criterion_type": "boolean", }, headers=headers)
assert response.status_code == 200 data = response.json() assert data["success"] is True assert data["data"]["label"] == "Budget Above $10K" assert data["data"]["code"] == "budget_above_10k" assert data["data"]["criterion_type"] == "boolean" assert data["data"]["is_enabled"] is True
@pytest.mark.asyncioasync def test_list_criteria(async_client: AsyncClient, criteria_setup): setup = criteria_setup headers = _auth(setup["token"], str(setup["workspace"].id))
# Create two criteria await async_client.post("/api/v1/prompt-studio/qualification", json={ "label": "Decision Maker", "criterion_type": "boolean", "sort_order": 0, }, headers=headers)
await async_client.post("/api/v1/prompt-studio/qualification", json={ "label": "Company Size", "criterion_type": "enum", "enum_values": ["1-10", "11-50", "51-200", "200+"], "sort_order": 1, }, headers=headers)
response = await async_client.get("/api/v1/prompt-studio/qualification", headers=headers) assert response.status_code == 200 data = response.json() assert data["success"] is True assert isinstance(data["data"], list) assert len(data["data"]) >= 2
# Check enum values preserved enum_item = next((c for c in data["data"] if c["code"] == "company_size"), None) assert enum_item is not None assert enum_item["enum_values"] == ["1-10", "11-50", "51-200", "200+"]
@pytest.mark.asyncioasync def test_update_criterion(async_client: AsyncClient, criteria_setup): setup = criteria_setup headers = _auth(setup["token"], str(setup["workspace"].id))
# Create create_res = await async_client.post("/api/v1/prompt-studio/qualification", json={ "label": "Timeline Under 3 Months", "criterion_type": "boolean", }, headers=headers) criterion_id = create_res.json()["data"]["id"]
# Update response = await async_client.patch( f"/api/v1/prompt-studio/qualification/{criterion_id}", json={"description": "Project timeline is less than 3 months", "weight": 5}, headers=headers, ) assert response.status_code == 200 data = response.json() assert data["success"] is True assert data["data"]["description"] == "Project timeline is less than 3 months" assert data["data"]["weight"] == 5
@pytest.mark.asyncioasync def test_delete_criterion(async_client: AsyncClient, criteria_setup): setup = criteria_setup headers = _auth(setup["token"], str(setup["workspace"].id))
# Create create_res = await async_client.post("/api/v1/prompt-studio/qualification", json={ "label": "To Delete", "criterion_type": "text", }, headers=headers) criterion_id = create_res.json()["data"]["id"]
# Delete response = await async_client.delete( f"/api/v1/prompt-studio/qualification/{criterion_id}", headers=headers, ) assert response.status_code == 200 assert response.json()["data"]["deleted"] is True
# Verify gone from list list_res = await async_client.get("/api/v1/prompt-studio/qualification", headers=headers) ids = [c["id"] for c in list_res.json()["data"]] assert criterion_id not in ids
@pytest.mark.asyncioasync def test_duplicate_code_rejected(async_client: AsyncClient, criteria_setup): setup = criteria_setup headers = _auth(setup["token"], str(setup["workspace"].id))
await async_client.post("/api/v1/prompt-studio/qualification", json={ "label": "Unique Test", "code": "unique_code", "criterion_type": "boolean", }, headers=headers)
# Try to create with same code response = await async_client.post("/api/v1/prompt-studio/qualification", json={ "label": "Another", "code": "unique_code", "criterion_type": "boolean", }, headers=headers)
data = response.json() assert data["success"] is False assert "already exists" in data["error"].lower()
@pytest.mark.asyncioasync def test_unauthenticated_access(async_client: AsyncClient): response = await async_client.get("/api/v1/prompt-studio/qualification") assert response.status_code in (401, 403)37 unmodified lines3839404142431 unmodified line45464748495040 unmodified lines91929394959637 unmodified linesonChange: (updated: Record<string, any>) => void;}) {const tasks: string[] = Array.isArray(config.tasks) ? config.tasks : [];const addTask = () => onChange({ ...config, tasks: [...tasks, ""] });const removeTask = (i: number) =>1 unmodified lineconst updateTask = (i: number, val: string) =>onChange({ ...config, tasks: tasks.map((t, idx) => (idx === i ? val : t)) });return (<div className="space-y-4"><LabeledField label="Goal" required>40 unmodified linesonChange={(e) => onChange({ ...config, extra_instructions: e.target.value })}/></LabeledField></div>);}37 unmodified lines383940414243441 unmodified line46474849505152535455565740 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513637 unmodified linesonChange: (updated: Record<string, any>) => void;}) {const tasks: string[] = Array.isArray(config.tasks) ? config.tasks : [];const outputs: { key: string; label: string }[] = Array.isArray(config.output_schema) ? config.output_schema : [];const addTask = () => onChange({ ...config, tasks: [...tasks, ""] });const removeTask = (i: number) =>1 unmodified lineconst updateTask = (i: number, val: string) =>onChange({ ...config, tasks: tasks.map((t, idx) => (idx === i ? val : t)) });const addOutput = () => onChange({ ...config, output_schema: [...outputs, { key: "", label: "" }] });const removeOutput = (i: number) =>onChange({ ...config, output_schema: outputs.filter((_, idx) => idx !== i) });const updateOutput = (i: number, field: "key" | "label", val: string) =>onChange({ ...config, output_schema: outputs.map((o, idx) => (idx === i ? { ...o, [field]: val } : o)) });return (<div className="space-y-4"><LabeledField label="Goal" required>40 unmodified linesonChange={(e) => onChange({ ...config, extra_instructions: e.target.value })}/></LabeledField><LabeledField label="Expected Outputs (optional)"><div className="space-y-2">{outputs.map((output, i) => (<div key={i} className="flex gap-2"><inputclassName="w-28 rounded-lg border border-border bg-background px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500"placeholder="Key"value={output.key}onChange={(e) => updateOutput(i, "key", e.target.value)}/><inputclassName="flex-1 rounded-lg border border-border bg-background px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-teal-500"placeholder="Label (e.g. Budget Range)"value={output.label}onChange={(e) => updateOutput(i, "label", e.target.value)}/><buttononClick={() => removeOutput(i)}className="p-1.5 rounded-md text-muted-foreground hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-950 transition-colors"><X className="w-3.5 h-3.5" /></button></div>))}<buttononClick={addOutput}className="text-xs text-teal-600 hover:text-teal-700 font-medium">+ Add output field</button></div></LabeledField></div>);}
39 unmodified lines40414243444541 unmodified lines87888990919265 unmodified lines158159160161162163331 unmodified lines49549649749849950050169 unmodified lines571572573574575576577152 unmodified lines73073173273373473573673773873939 unmodified linesconst [qualVersion, setQualVersion] = useState(1);const [isSavingQual, setIsSavingQual] = useState(false);// Form Stateconst [formData, setFormData] = useState({basics: {41 unmodified lines}};const handleSaveQualification = async () => {setIsSavingQual(true);const res = await apiClient.post("/qualification-config", {65 unmodified lines}await fetchKnowledgeFiles();await fetchQualificationConfig();} catch (err: any) {setError("Connectivity error. Please check your internet or try again.");} finally {331 unmodified lines<div className="flex items-center justify-between border-b border-slate-100 pb-4"><div><h2 className="text-lg font-bold text-slate-800">Workspace Knowledge</h2><p className="text-xs text-slate-500">Upload documents (PDFs, TXT, CSV) to provide AI with business context.</p></div><label className="cursor-pointer bg-teal-600 text-white px-4 py-2 rounded-lg text-sm font-bold hover:bg-teal-700 transition-all flex items-center gap-2 shadow-sm">{isUploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}69 unmodified lines<div className="bg-amber-50 border border-amber-100 rounded-xl p-4 flex gap-3"><AlertCircle className="w-4 h-4 text-amber-600 shrink-0" /><p className="text-[11px] text-amber-800 leading-normal"><strong>Pro Tip:</strong> Uploaded files (TXT, CSV, PDF) are automatically extracted and injected into your AI's context. The AI will reference these documents when responding to leads.</p></div></div>152 unmodified lines)}</section><div className="bg-teal-50/50 border border-teal-100 rounded-xl p-4 flex gap-3"><AlertCircle className="w-4 h-4 text-teal-600 shrink-0" /><p className="text-[11px] text-teal-700 leading-normal"><strong>How it works:</strong> Enabled questions are injected into the AI's system prompt. The AI will naturally ask leads for this information during conversation. Statuses can be used to categorize leads in the Contacts page.</p></div></div>39 unmodified lines4041424344454647484941 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213365 unmodified lines199200201202203204205331 unmodified lines53753853954054154254369 unmodified lines613614615616617618619152 unmodified lines77277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988039 unmodified linesconst [qualVersion, setQualVersion] = useState(1);const [isSavingQual, setIsSavingQual] = useState(false);// Qualification criteria state (Mission 29)const [criteria, setCriteria] = useState<any[]>([]);const [savingCriterionId, setSavingCriterionId] = useState<string | null>(null);// Form Stateconst [formData, setFormData] = useState({basics: {41 unmodified lines}};const fetchCriteria = async () => {const res = await apiClient.get("/prompt-studio/qualification");if (res.success && res.data) {setCriteria(res.data);}};const handleCreateCriterion = async () => {setSavingCriterionId("new");const res = await apiClient.post("/prompt-studio/qualification", {label: "New Criterion",criterion_type: "boolean",sort_order: criteria.length,});if (res.success && res.data) {setCriteria([...criteria, res.data]);}setSavingCriterionId(null);};const handleUpdateCriterion = async (id: string, updates: Record<string, any>) => {setSavingCriterionId(id);const res = await apiClient.patch(`/prompt-studio/qualification/${id}`, updates);if (res.success && res.data) {setCriteria(criteria.map(c => c.id === id ? res.data : c));}setSavingCriterionId(null);};const handleDeleteCriterion = async (id: string) => {if (!confirm("Delete this qualification criterion?")) return;const res = await apiClient.delete(`/prompt-studio/qualification/${id}`);if (res.success) {setCriteria(criteria.filter(c => c.id !== id));}};const handleSaveQualification = async () => {setIsSavingQual(true);const res = await apiClient.post("/qualification-config", {65 unmodified lines}await fetchKnowledgeFiles();await fetchQualificationConfig();await fetchCriteria();} catch (err: any) {setError("Connectivity error. Please check your internet or try again.");} finally {331 unmodified lines<div className="flex items-center justify-between border-b border-slate-100 pb-4"><div><h2 className="text-lg font-bold text-slate-800">Workspace Knowledge</h2><p className="text-xs text-slate-500">Upload documents (PDF, DOCX, XLSX, TXT, CSV) to provide AI with business context.</p></div><label className="cursor-pointer bg-teal-600 text-white px-4 py-2 rounded-lg text-sm font-bold hover:bg-teal-700 transition-all flex items-center gap-2 shadow-sm">{isUploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Plus className="w-4 h-4" />}69 unmodified lines<div className="bg-amber-50 border border-amber-100 rounded-xl p-4 flex gap-3"><AlertCircle className="w-4 h-4 text-amber-600 shrink-0" /><p className="text-[11px] text-amber-800 leading-normal"><strong>Pro Tip:</strong> Uploaded files (TXT, CSV, PDF, DOCX, XLSX) are automatically extracted, chunked, and indexed. The AI retrieves the most relevant knowledge snippets when responding to leads.</p></div></div>152 unmodified lines)}</section>{/* Qualification Criteria (Mission 29) */}<section className="space-y-4"><div className="flex items-center justify-between"><div className="flex items-center gap-2 text-slate-800"><Sparkles className="w-4 h-4 text-teal-600" /><h3 className="text-sm font-bold uppercase tracking-wider">Qualification Criteria</h3></div><buttononClick={handleCreateCriterion}disabled={savingCriterionId === "new"}className="text-xs font-bold text-teal-600 hover:text-teal-700 flex items-center gap-1 transition-all disabled:opacity-50"><Plus className="w-3.5 h-3.5" /> Add Criterion</button></div><p className="text-[11px] text-slate-400">Define rules for evaluating and scoring leads. The AI uses these to determine lead quality.</p>{criteria.length === 0 ? (<div className="py-10 flex flex-col items-center justify-center border-2 border-dashed border-slate-200 rounded-xl bg-slate-50 text-slate-400"><Sparkles className="w-8 h-8 mb-3 opacity-20" /><p className="text-sm font-medium">No criteria defined</p><p className="text-[10px] mt-1">Click "Add Criterion" to define lead qualification rules.</p></div>) : (<div className="space-y-3">{criteria.map((c) => (<div key={c.id} className="p-4 bg-white border border-slate-200 rounded-xl group hover:border-teal-400 transition-all space-y-3"><div className="flex items-center gap-3"><inputtype="text"value={c.label}onChange={(e) => setCriteria(criteria.map(cr => cr.id === c.id ? { ...cr, label: e.target.value } : cr))}onBlur={() => handleUpdateCriterion(c.id, { label: c.label })}placeholder="Criterion label"className="flex-1 p-2 bg-slate-50 border border-slate-200 rounded-lg text-sm focus:ring-2 focus:ring-teal-500/20 focus:border-teal-500 outline-none transition-all font-medium"/><selectvalue={c.criterion_type}onChange={(e) => handleUpdateCriterion(c.id, { criterion_type: e.target.value })}className="w-28 p-2 bg-slate-50 border border-slate-200 rounded-lg text-xs outline-none focus:border-teal-500"><option value="boolean">Boolean</option><option value="enum">Enum</option><option value="text">Text</option><option value="score">Score (1-5)</option></select><inputtype="number"min={0}value={c.weight ?? ""}onChange={(e) => setCriteria(criteria.map(cr => cr.id === c.id ? { ...cr, weight: e.target.value === "" ? null : parseInt(e.target.value) } : cr))}onBlur={() => handleUpdateCriterion(c.id, { weight: c.weight })}placeholder="Wt"title="Weight (priority)"className="w-16 p-2 bg-slate-50 border border-slate-200 rounded-lg text-xs outline-none focus:border-teal-500 text-center"/><label className="flex items-center gap-1.5 cursor-pointer select-none"><inputtype="checkbox"checked={c.is_enabled !== false}onChange={(e) => handleUpdateCriterion(c.id, { is_enabled: e.target.checked })}className="w-4 h-4 accent-teal-600"/><span className="text-[10px] font-medium text-slate-500">On</span></label><buttononClick={() => handleDeleteCriterion(c.id)}className="p-1.5 text-slate-300 hover:text-rose-500 hover:bg-rose-50 rounded-lg transition-all opacity-0 group-hover:opacity-100"><Trash2 className="w-3.5 h-3.5" /></button></div><inputtype="text"value={c.description ?? ""}onChange={(e) => setCriteria(criteria.map(cr => cr.id === c.id ? { ...cr, description: e.target.value } : cr))}onBlur={() => handleUpdateCriterion(c.id, { description: c.description })}placeholder="Description (e.g. Lead has budget above $10K)"className="w-full p-2 bg-slate-50/50 border border-slate-100 rounded-lg text-xs text-slate-600 outline-none focus:border-teal-500 transition-all"/>{c.criterion_type === "enum" && (<inputtype="text"value={(c.enum_values || []).join(", ")}onChange={(e) => {const vals = e.target.value.split(",").map((v: string) => v.trim()).filter(Boolean);setCriteria(criteria.map(cr => cr.id === c.id ? { ...cr, enum_values: vals } : cr));}}onBlur={() => handleUpdateCriterion(c.id, { enum_values: c.enum_values })}placeholder="Enum values (comma separated)"className="w-full p-2 bg-amber-50/50 border border-amber-100 rounded-lg text-xs text-amber-800 outline-none focus:border-amber-400 transition-all"/>)}</div>))}</div>)}</section><div className="bg-teal-50/50 border border-teal-100 rounded-xl p-4 flex gap-3"><AlertCircle className="w-4 h-4 text-teal-600 shrink-0" /><p className="text-[11px] text-teal-700 leading-normal"><strong>How it works:</strong> Enabled questions are injected into the AI's system prompt. The AI will naturally ask leads for this information during conversation. Criteria define how the AI evaluates lead quality. Statuses categorize leads in the Contacts page.</p></div></div>
38 unmodified lines394041424344454647484938 unmodified linestry {const response = await fetch(url, { ...options, headers });if (response.status === 401 || response.status === 403) {adminAuth.logout();return { success: false, error: "Admin session expired. Please log in again." };}const contentType = response.headers.get("content-type");if (contentType?.includes("application/json")) {const json = await response.json();38 unmodified lines3940414243444546474849505152535455565758596038 unmodified linestry {const response = await fetch(url, { ...options, headers });// 401 = token expired/invalid → force re-loginif (response.status === 401) {adminAuth.logout();return { success: false, error: "Admin session expired. Please log in again." };}// 403 = forbidden (not superuser, module disabled, etc.) → surface error, don't logoutif (response.status === 403) {const ct = response.headers.get("content-type");if (ct?.includes("application/json")) {const json = await response.json();return { success: false, error: json.error || json.detail || "Access denied (403)." };}return { success: false, error: "Admin access denied (403)." };}const contentType = response.headers.get("content-type");if (contentType?.includes("application/json")) {const json = await response.json();
backend/alembic/versions/i9j0k1l2m3n4_mission_29_knowledge_chunks_qualification.pyAdded+59
backend/app/api/v1/auth.py+5-1
backend/app/api/v1/knowledge.py+51-2
backend/app/api/v1/qualification_criteria.pyAdded+223
backend/app/api/v1/test_chat.py+5-2
backend/app/core/seed.py+76-2
backend/app/domain/runtime.py+20-12
backend/app/models/models.py+30
backend/app/services/knowledge_chunker.pyAdded+188
backend/app/services/prompt_compiler.py+72-20
backend/main.py+4-1
backend/requirements.txt+2
backend/scripts/create_test_user.py+68-1
backend/tests/test_auth_comprehensive.pyAdded+294
backend/tests/test_knowledge_chunks.pyAdded+195
backend/tests/test_prompt_compile_enhanced.pyAdded+206
backend/tests/test_qualification_criteria.pyAdded+201
frontend/src/app/(dashboard)/automations/[id]/NodeConfigPanel.tsx+40
frontend/src/app/(dashboard)/prompt-studio/page.tsx+144-3
frontend/src/lib/admin-api.ts+12-1