Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions server/backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ dependencies = [
"cq-sdk~=0.9.1",
]

[project.optional-dependencies]
semsearch = [
"sqlite_vec",
"numpy",
"httpx",
]

[project.scripts]
cq-server = "cq_server.app:main"

Expand Down
28 changes: 14 additions & 14 deletions server/backend/src/cq_server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def health() -> dict[str, str]:


@api_router.get("/query")
def query_units(
async def query_units(
domains: Annotated[list[str], Query()],
languages: Annotated[list[str] | None, Query()] = None,
frameworks: Annotated[list[str] | None, Query()] = None,
Expand All @@ -103,7 +103,7 @@ def query_units(
) -> list[KnowledgeUnit]:
"""Search knowledge units by domain tags with relevance ranking."""
store = _get_store()
return store.query(
return await store.query(
domains,
languages=languages,
frameworks=frameworks,
Expand All @@ -113,7 +113,7 @@ def query_units(


@api_router.post("/propose", status_code=201)
def propose_unit(
async def propose_unit(
request: ProposeRequest,
username: str = Depends(require_api_key),
) -> KnowledgeUnit:
Expand All @@ -133,42 +133,42 @@ def propose_unit(
tier=Tier.PRIVATE,
created_by=username,
)
store.insert(unit)
await store.insert(unit)
return unit


@api_router.post("/confirm/{unit_id}")
def confirm_unit(unit_id: str, _username: str = Depends(require_api_key)) -> KnowledgeUnit:
async def confirm_unit(unit_id: str, _username: str = Depends(require_api_key)) -> KnowledgeUnit:
"""Confirm a knowledge unit, boosting its confidence."""
store = _get_store()
unit = store.get(unit_id)
unit = await store.get(unit_id)
if unit is None:
raise HTTPException(status_code=404, detail="Knowledge unit not found")
confirmed = apply_confirmation(unit)
store.update(confirmed)
await store.update(confirmed)
return confirmed


@api_router.post("/flag/{unit_id}")
def flag_unit(unit_id: str, request: FlagRequest, _username: str = Depends(require_api_key)) -> KnowledgeUnit:
async def flag_unit(unit_id: str, request: FlagRequest, _username: str = Depends(require_api_key)) -> KnowledgeUnit:
"""Flag a knowledge unit, reducing its confidence."""
store = _get_store()
unit = store.get(unit_id)
unit = await store.get(unit_id)
if unit is None:
raise HTTPException(status_code=404, detail="Knowledge unit not found")
flagged = apply_flag(unit, request.reason)
store.update(flagged)
await store.update(flagged)
return flagged


@api_router.get("/stats")
def stats() -> StatsResponse:
async def stats() -> StatsResponse:
"""Return store statistics."""
store = _get_store()
return StatsResponse(
total_units=store.count(),
tiers=store.counts_by_tier(),
domains=store.domain_counts(),
total_units=await store.count(),
tiers=await store.counts_by_tier(),
domains=await store.domain_counts(),
)


Expand Down
24 changes: 12 additions & 12 deletions server/backend/src/cq_server/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def get_current_user(request: Request) -> str:


@router.post("/login")
def login(request: LoginRequest, store: RemoteStore = Depends(get_store)) -> LoginResponse:
async def login(request: LoginRequest, store: RemoteStore = Depends(get_store)) -> LoginResponse:
"""Authenticate a user and return a JWT token.

Args:
Expand All @@ -182,15 +182,15 @@ def login(request: LoginRequest, store: RemoteStore = Depends(get_store)) -> Log
Raises:
HTTPException: With status 401 if credentials are invalid.
"""
user = store.get_user(request.username)
user = await store.get_user(request.username)
if user is None or not verify_password(request.password, user["password_hash"]):
raise HTTPException(status_code=401, detail="Invalid username or password")
token = create_token(request.username, secret=_get_jwt_secret())
return LoginResponse(token=token, username=request.username)


@router.get("/me")
def me(username: str = Depends(get_current_user), store: RemoteStore = Depends(get_store)) -> MeResponse:
async def me(username: str = Depends(get_current_user), store: RemoteStore = Depends(get_store)) -> MeResponse:
"""Return the current user's info.

Args:
Expand All @@ -203,26 +203,26 @@ def me(username: str = Depends(get_current_user), store: RemoteStore = Depends(g
Raises:
HTTPException: With status 404 if the user no longer exists.
"""
user = store.get_user(username)
user = await store.get_user(username)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return MeResponse(username=user["username"], created_at=user["created_at"])


def _require_user_id(store: RemoteStore, username: str) -> int:
async def _require_user_id(store: RemoteStore, username: str) -> int:
"""Return the integer user id for the authenticated caller.

Raises:
HTTPException: 404 if the user record has been removed while the JWT remains valid.
"""
user = store.get_user(username)
user = await store.get_user(username)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return int(user["id"])


@router.post("/api-keys", status_code=201)
def create_api_key_route(
async def create_api_key_route(
request: CreateApiKeyRequest,
username: str = Depends(get_current_user),
store: RemoteStore = Depends(get_store),
Expand All @@ -242,7 +242,7 @@ def create_api_key_route(
duration = parse_ttl(request.ttl)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc)) from exc
user_id = _require_user_id(store, username)
user_id = await _require_user_id(store, username)
if store.count_active_api_keys_for_user(user_id) >= MAX_ACTIVE_API_KEYS_PER_USER:
raise HTTPException(
status_code=409,
Expand All @@ -265,17 +265,17 @@ def create_api_key_route(


@router.get("/api-keys")
def list_api_keys_route(
async def list_api_keys_route(
username: str = Depends(get_current_user),
store: RemoteStore = Depends(get_store),
) -> list[ApiKeyPublic]:
"""Return the authenticated user's API keys. Never returns plaintext."""
user_id = _require_user_id(store, username)
user_id = await _require_user_id(store, username)
return [_to_public(row) for row in store.list_api_keys_for_user(user_id)]


@router.delete("/api-keys/{key_id}", status_code=204)
def revoke_api_key_route(
async def revoke_api_key_route(
key_id: str,
username: str = Depends(get_current_user),
store: RemoteStore = Depends(get_store),
Expand All @@ -286,7 +286,7 @@ def revoke_api_key_route(
204. A 404 is returned only when the key does not exist or is owned by
a different user (uniform response, no enumeration oracle).
"""
user_id = _require_user_id(store, username)
user_id = await _require_user_id(store, username)
if store.get_api_key_for_user(user_id=user_id, key_id=key_id) is None:
raise HTTPException(status_code=404, detail="API key not found")
store.revoke_api_key(user_id=user_id, key_id=key_id)
44 changes: 22 additions & 22 deletions server/backend/src/cq_server/review.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def _build_decision(unit_id: str, row: dict[str, str | None]) -> ReviewDecisionR


@router.get("/queue")
def review_queue(
async def review_queue(
limit: int = 20,
offset: int = 0,
_user: str = Depends(get_current_user),
Expand All @@ -102,8 +102,8 @@ def review_queue(
Returns:
A paginated list of pending knowledge units with review metadata.
"""
items = store.pending_queue(limit=limit, offset=offset)
total = store.pending_count()
items = await store.pending_queue(limit=limit, offset=offset)
total = await store.pending_count()
return ReviewQueueResponse(
items=[
ReviewItem(
Expand All @@ -121,7 +121,7 @@ def review_queue(


@router.post("/{unit_id}/approve")
def approve_unit(
async def approve_unit(
unit_id: str,
username: str = Depends(get_current_user),
store: RemoteStore = Depends(get_store),
Expand All @@ -140,19 +140,19 @@ def approve_unit(
HTTPException: With status 404 if the unit does not exist.
HTTPException: With status 409 if the unit has already been reviewed.
"""
status = store.get_review_status(unit_id)
status = await store.get_review_status(unit_id)
if status is None:
raise HTTPException(status_code=404, detail="Knowledge unit not found")
if status["status"] != "pending":
raise HTTPException(status_code=409, detail=f"Knowledge unit already {status['status']}")
store.set_review_status(unit_id, "approved", username)
updated = store.get_review_status(unit_id)
await store.set_review_status(unit_id, "approved", username)
updated = await store.get_review_status(unit_id)
assert updated is not None # Unit exists; we just wrote to it.
return _build_decision(unit_id, updated)


@router.post("/{unit_id}/reject")
def reject_unit(
async def reject_unit(
unit_id: str,
username: str = Depends(get_current_user),
store: RemoteStore = Depends(get_store),
Expand All @@ -171,19 +171,19 @@ def reject_unit(
HTTPException: With status 404 if the unit does not exist.
HTTPException: With status 409 if the unit has already been reviewed.
"""
status = store.get_review_status(unit_id)
status = await store.get_review_status(unit_id)
if status is None:
raise HTTPException(status_code=404, detail="Knowledge unit not found")
if status["status"] != "pending":
raise HTTPException(status_code=409, detail=f"Knowledge unit already {status['status']}")
store.set_review_status(unit_id, "rejected", username)
updated = store.get_review_status(unit_id)
await store.set_review_status(unit_id, "rejected", username)
updated = await store.get_review_status(unit_id)
assert updated is not None # Unit exists; we just wrote to it.
return _build_decision(unit_id, updated)


@router.get("/stats")
def review_stats(
async def review_stats(
_user: str = Depends(get_current_user),
store: RemoteStore = Depends(get_store),
) -> ReviewStatsResponse:
Expand All @@ -197,24 +197,24 @@ def review_stats(
Aggregated counts by status, domain distribution, confidence
distribution, recent activity, and daily trend data.
"""
counts = store.counts_by_status()
counts = await store.counts_by_status()
return ReviewStatsResponse(
counts={
"pending": counts.get("pending", 0),
"approved": counts.get("approved", 0),
"rejected": counts.get("rejected", 0),
},
domains=store.domain_counts(),
confidence_distribution=store.confidence_distribution(),
recent_activity=store.recent_activity(),
domains=await store.domain_counts(),
confidence_distribution=await store.confidence_distribution(),
recent_activity=await store.recent_activity(),
trends=TrendsResponse(
daily=[DailyCount(**d) for d in store.daily_counts()],
daily=[DailyCount(**d) for d in await store.daily_counts()],
),
)


@router.get("/units")
def list_units(
async def list_units(
domain: str | None = None,
confidence_min: float | None = None,
confidence_max: float | None = None,
Expand All @@ -238,7 +238,7 @@ def list_units(
Returns:
List of knowledge units with review metadata.
"""
items = store.list_units(
items = await store.list_units(
domain=domain,
confidence_min=confidence_min,
confidence_max=confidence_max,
Expand All @@ -257,7 +257,7 @@ def list_units(


@router.get("/{unit_id}")
def get_unit(
async def get_unit(
unit_id: str,
_user: str = Depends(get_current_user),
store: RemoteStore = Depends(get_store),
Expand All @@ -275,10 +275,10 @@ def get_unit(
Raises:
HTTPException: With status 404 if the unit does not exist.
"""
ku = store.get_any(unit_id)
ku = await store.get_any(unit_id)
if ku is None:
raise HTTPException(status_code=404, detail="Knowledge unit not found")
review = store.get_review_status(unit_id)
review = await store.get_review_status(unit_id)
assert review is not None # Unit exists; get_any just returned it.
return ReviewItem(
knowledge_unit=ku,
Expand Down
Loading
Loading