From 14076e988d160ecfb12093d1792e4995dadd72d6 Mon Sep 17 00:00:00 2001 From: Wolf Date: Sat, 3 Oct 2026 22:04:54 +0200 Subject: [PATCH] Serve Best CV match, Closing soon, the language flag and the deadline in the feed, and suggest an agent's languages from its CV Co-Authored-By: Claude Opus 5.5 --- app/models.py | 4 +- app/storage/store.py | 93 +++++++++++++++++----- app/web/api.py | 70 ++++++++++++++--- tests/test_cv_feed.py | 178 ++++++++++++++++++++++++++++++++++++++++++ tests/test_storage.py | 2 +- 5 files changed, 313 insertions(+), 34 deletions(-) create mode 100644 tests/test_cv_feed.py diff --git a/app/models.py b/app/models.py index 2dce3f5..decaa13 100644 --- a/app/models.py +++ b/app/models.py @@ -954,7 +954,7 @@ class RoleLanguage(Model): kind: LanguageKind = "required" -def _role_languages(value: Any) -> list[RoleLanguage]: +def role_languages(value: Any) -> list[RoleLanguage]: out = [] for item in _json_list(value): try: @@ -966,7 +966,7 @@ def _role_languages(value: Any) -> list[RoleLanguage]: #: `roles.languages_required`: NULL (never read) and [] are both no language. -RoleLanguages = Annotated[list[RoleLanguage], BeforeValidator(_role_languages)] +RoleLanguages = Annotated[list[RoleLanguage], BeforeValidator(role_languages)] LangFlag = Literal["missing", "below", "plus", ""] diff --git a/app/storage/store.py b/app/storage/store.py index 383fdc4..4e15439 100644 --- a/app/storage/store.py +++ b/app/storage/store.py @@ -26,7 +26,7 @@ from app.models import ( AFFINITY, HAND_REASONS, LEVELS, STATUSES, Agent, Application, ApplicationEvent, Candidate, Company, CvLanguage, Gate, Judgement, Limits, Prompt, Role, RoleCopy, RolePlace, RoleRow, ScoredRole, cv_languages as normal_languages, cv_score, - language_flag, + language_flag, role_languages, Subscription, Weights, check_prompts, company_fold, company_key, country_of, excerpt, place_key, fetch_terms as normal_terms, host_word, iso_day, posted_at, posted_host, remote_of, title_key, ) @@ -119,6 +119,18 @@ _VOTED_SCORE = ("MIN(1.0, s.score * CASE v.vote WHEN -1 THEN 0.5 " #: nothing, so `vote` and `voted_at` are NULL: one query shape either way. _WITH_VOTES = "LEFT JOIN role_votes v ON v.uid = roles.uid AND v.agent_id = ?" +#: The agent's `judge` readings beside every role, the same way: `j.cv_score` +#: is NULL for a role not judged and with no agent. +_WITH_JUDGEMENTS = ("LEFT JOIN role_judgements j ON j.uid = roles.uid AND j.agent_id = ? " + "AND j.judged_at IS NOT NULL") + +#: The order of Best CV match: the judged roles by `cv_score`, then the rest +#: by score, as `roles` orders them. +_BY_CV = "j.cv_score IS NULL, j.cv_score DESC, " + +#: How many days after today the feed's Closing soon filter reaches. +CLOSING_DAYS = 4 + #: What `roles_page` reads for `RoleRow.excerpt`: the summary when there is #: one, else the description's opening. A `SUBSTR` of the source column, not #: the column itself, so a big `description` never leaves SQLite whole for a @@ -867,7 +879,8 @@ class Store: def role(self, uid: str, agent_id: int | None = None) -> ScoredRole | None: """One role with its tags, and with `vote`, `voted_at`, `score`, - `gated_reason` and `prompt` as `agent_id` judged and scored it; None + `gated_reason` and `prompt` as `agent_id` judged and scored it, and + its `judgement`, `cv_score` and language flag for that agent; None (unjudged, unscored) without an agent. The score is moved by the vote as `roles` serves it.""" row = self._row( @@ -883,6 +896,10 @@ class Store: role.copies = self._copies_of(uid) role.places = self.role_places(uid) role.remote_where = self._remote_where([uid]).get(uid, "") + role.judgement = self.judgement(agent_id, uid) + role.cv_score = role.judgement.cv_score if role.judgement else None + role.lang_flag, role.lang_note = language_flag(role.languages_required, + self._languages_of(agent_id)) return role def _copies_of(self, uid: str) -> list[RoleCopy]: @@ -1059,7 +1076,8 @@ class Store: judged: str | None = None, pay: str | None = None, company_keys: Sequence[str] = (), places: Sequence[str] = (), seniority: Sequence[str] = (), seniority_unknown: bool = True, - pay_unknown: bool = False, offset: int = 0) -> list[ScoredRole]: + pay_unknown: bool = False, by_cv: bool = False, closing: bool = False, + offset: int = 0) -> list[ScoredRole]: """Newest first by `posted_at`. `company` and `place` are case-insensitive substrings of the columns a board wrote — not the key, so a search does not have to know the exact slug a company folds @@ -1102,6 +1120,13 @@ class Store: rescore. With `by_score` off the order is newest, with the votes and no score. + With `by_cv` as well, the roles the agent's `judge` read come first + by `cv_score`, then the others by score (Best CV match). Every row + carries the agent's `cv_score` (None when not judged) and the + language flag of its languages against the agent's + (`language_flag`). `closing` keeps the roles whose `deadline` falls + today or in the next `CLOSING_DAYS` days. + `offset` skips that many rows of the same order, for the page that loads the next 60 as it is scrolled; `count_roles` is the total. Every returned role carries its tags, read with one extra query for @@ -1111,13 +1136,14 @@ class Store: remote=remote, days=days, hide_muted=hide_muted, include_read=include_read, tags=tags, tag_mode=tag_mode, agent=agent, by_score=by_score, gated=gated, judged=judged, pay=pay, company_keys=company_keys, places=places, - seniority=seniority, seniority_unknown=seniority_unknown, pay_unknown=pay_unknown) - select = "SELECT roles.*, v.vote, v.voted_at" + seniority=seniority, seniority_unknown=seniority_unknown, pay_unknown=pay_unknown, + closing=closing) + select = "SELECT roles.*, v.vote, v.voted_at, j.cv_score" order = "roles.posted_at DESC, roles.uid" scored = agent is not None and by_score if scored: select += f", {_VOTED_SCORE} AS score, s.gated_reason, s.prompt" - order = "score DESC, " + order + order = (_BY_CV if by_cv else "") + "score DESC, " + order elif open_only: # Newest first, open only: idx_roles_posted covers this exactly # (posted_at DESC, uid, WHERE closed_at IS NULL), so it earns the @@ -1131,11 +1157,18 @@ class Store: f"{select} {sql} ORDER BY {order} LIMIT ? OFFSET ?", [*params, limit, offset])] by_uid = self._tags_by_uid([r.uid for r in found]) areas = self._remote_where([r.uid for r in found]) + mine = self._languages_of(agent) for r in found: r.tags = by_uid.get(r.uid, []) r.remote_where = areas.get(r.uid, "") + r.lang_flag, r.lang_note = language_flag(r.languages_required, mine) return found + def _languages_of(self, agent_id: int | None) -> list[CvLanguage]: + """The languages the agent's CV states, [] with no agent.""" + found = self.agent(agent_id) if agent_id is not None else None + return found.cv_languages if found else [] + def roles_page(self, limit: int = 100, company: str | None = None, place: str | None = None, open_only: bool = True, q: str | None = None, function: str | None = None, @@ -1146,7 +1179,8 @@ class Store: judged: str | None = None, pay: str | None = None, company_keys: Sequence[str] = (), places: Sequence[str] = (), seniority: Sequence[str] = (), seniority_unknown: bool = True, - pay_unknown: bool = False, offset: int = 0) -> list[RoleRow]: + pay_unknown: bool = False, by_cv: bool = False, closing: bool = False, + offset: int = 0) -> list[RoleRow]: """What `GET /api/roles` serves: the same rows `roles` would, in the same order, with the same filters and paging, but only the fields a row draws (see `RoleRow`) — never `description`, `feed_text`, `raw` @@ -1154,6 +1188,9 @@ class Store: or not a page ever renders them. The reader still gets the whole role by uid, see `role`. + `lang_flag` and `lang_note` are the role's languages against the + agent's (`language_flag`), and `cv_score` its `judge` total. + `excerpt` is `app.models.excerpt` over a `SUBSTR` of `_EXCERPT_SOURCE` (`_EXCERPT_RAW` characters, trimmed further in Python), so the source column itself never crosses out of SQLite for a list.""" @@ -1162,29 +1199,33 @@ class Store: remote=remote, days=days, hide_muted=hide_muted, include_read=include_read, tags=tags, tag_mode=tag_mode, agent=agent, by_score=by_score, gated=gated, judged=judged, pay=pay, company_keys=company_keys, places=places, - seniority=seniority, seniority_unknown=seniority_unknown, pay_unknown=pay_unknown) + seniority=seniority, seniority_unknown=seniority_unknown, pay_unknown=pay_unknown, + closing=closing) select = ( "SELECT roles.uid, roles.company_key, roles.company, roles.title, roles.place, " "roles.country, roles.remote, roles.function, roles.seniority, roles.salary_min, " "roles.salary_max, roles.currency, roles.salary_text, roles.original_url, " - "roles.posting_url, roles.posted_at, roles.read_at, " - "v.vote, v.voted_at, " + "roles.posting_url, roles.posted_at, roles.read_at, roles.deadline, " + "roles.languages_required, v.vote, v.voted_at, j.cv_score, " f"SUBSTR({_EXCERPT_SOURCE}, 1, {_EXCERPT_RAW}) AS excerpt") order = "roles.posted_at DESC, roles.uid" scored = agent is not None and by_score if scored: select += f", {_VOTED_SCORE} AS score, s.gated_reason, s.prompt" - order = "score DESC, " + order + order = (_BY_CV if by_cv else "") + "score DESC, " + order elif open_only: # Same reasoning as `roles`: the planner otherwise sorts every # open role before applying LIMIT. sql = sql.replace("FROM roles ", "FROM roles INDEXED BY idx_roles_posted ", 1) rows = self._rows(f"{select} {sql} ORDER BY {order} LIMIT ? OFFSET ?", [*params, limit, offset]) + mine = self._languages_of(agent) found = [] for r in rows: row = dict(r) row["excerpt"] = excerpt(row["excerpt"]) + row["lang_flag"], row["lang_note"] = language_flag( + role_languages(row.pop("languages_required")), mine) found.append(RoleRow.from_row(row)) by_uid = self._tags_by_uid([f.uid for f in found]) copies = self._copy_counts([f.uid for f in found]) @@ -1206,14 +1247,16 @@ class Store: gated: bool = False, judged: str | None = None, pay: str | None = None, company_keys: Sequence[str] = (), places: Sequence[str] = (), seniority: Sequence[str] = (), - seniority_unknown: bool = True, pay_unknown: bool = False) -> int: + seniority_unknown: bool = True, pay_unknown: bool = False, + by_cv: bool = False, closing: bool = False) -> int: """How many roles `roles` would list with the same filters and no limit.""" sql, params = self._roles_from( company=company, place=place, open_only=open_only, q=q, function=function, remote=remote, days=days, hide_muted=hide_muted, include_read=include_read, tags=tags, tag_mode=tag_mode, agent=agent, by_score=by_score, gated=gated, judged=judged, pay=pay, company_keys=company_keys, places=places, - seniority=seniority, seniority_unknown=seniority_unknown, pay_unknown=pay_unknown) + seniority=seniority, seniority_unknown=seniority_unknown, pay_unknown=pay_unknown, + closing=closing) row = self._row(f"SELECT COUNT(*) AS n {sql}", params) return int(row["n"]) if row else 0 @@ -1227,7 +1270,8 @@ class Store: pay: str | None = None, company_keys: Sequence[str] = (), places: Sequence[str] = (), seniority: Sequence[str] = (), seniority_unknown: bool = True, - pay_unknown: bool = False) -> dict[str, list[tuple[str, int]]]: + pay_unknown: bool = False, by_cv: bool = False, + closing: bool = False) -> dict[str, list[tuple[str, int]]]: """How many roles `roles` would list at each seniority level and each pay state, each counted with every other filter and its own left out, so the rail can say what a click would add. `seniority` is every @@ -1239,7 +1283,7 @@ class Store: "function": function, "remote": remote, "days": days, "hide_muted": hide_muted, "include_read": include_read, "tags": tags, "tag_mode": tag_mode, "agent": agent, "by_score": by_score, "gated": gated, "judged": judged, - "company_keys": company_keys, "places": places} + "company_keys": company_keys, "places": places, "closing": closing} by_level, level_params = self._roles_from( **shared, pay=pay, pay_unknown=pay_unknown) by_pay, pay_params = self._roles_from( @@ -1261,12 +1305,15 @@ class Store: pay: str | None = None, company_keys: Sequence[str] = (), places: Sequence[str] = (), seniority: Sequence[str] = (), seniority_unknown: bool = True, - pay_unknown: bool = False) -> tuple[str, list[Any]]: + pay_unknown: bool = False, + closing: bool = False) -> tuple[str, list[Any]]: """The `FROM ... WHERE ...` that `roles` and `count_roles` share, with its parameters in order. The agent's votes are always joined as `v` - (see `_WITH_VOTES`); its scores as `s` only when ordering by them. A - copy of another role (`rebuild_dupes`) is never listed: its kept role - stands for it and counts its copies.""" + (see `_WITH_VOTES`) and its judgements as `j` (`_WITH_JUDGEMENTS`); + its scores as `s` only when ordering by them. A copy of another role + (`rebuild_dupes`) is never listed: its kept role stands for it and + counts its copies. `closing` keeps the roles whose deadline is + today or within `CLOSING_DAYS` after it.""" where: list[str] = ["roles.dup_of IS NULL"] params: list[Any] = [] if company: @@ -1312,6 +1359,10 @@ class Store: params.append(agent) if not include_read: where.append("roles.read_at IS NULL") + if closing: + today = self.clock().date() + where.append("roles.deadline BETWEEN ? AND ?") + params += [today.isoformat(), (today + timedelta(days=CLOSING_DAYS)).isoformat()] if tags: marks = ", ".join("?" for _ in tags) if tag_mode == "all": @@ -1331,8 +1382,8 @@ class Store: clause, values = _places_sql(places, self.gazetteer(), scope=self._scope(agent)) where.append(clause) params += values - sql = f"FROM roles {_WITH_VOTES}" - joins: list[Any] = [agent] + sql = f"FROM roles {_WITH_VOTES} {_WITH_JUDGEMENTS}" + joins: list[Any] = [agent, agent] if agent is not None and by_score: sql += " JOIN scores s ON s.uid = roles.uid AND s.agent_id = ?" joins.append(agent) diff --git a/app/web/api.py b/app/web/api.py index 768d575..66f0002 100644 --- a/app/web/api.py +++ b/app/web/api.py @@ -16,11 +16,13 @@ from pydantic import BaseModel, Field from app import jobs, places from app.models import ( - AFFINITY, RUNGS, TRACKS, Agent, Application, Company, FetchTerms, Gate, Limits, Prompts, Role, RoleRow, + AFFINITY, RUNGS, TRACKS, Agent, Application, Company, CvLanguage, CvLanguages, FetchTerms, + Gate, Limits, Prompts, Role, RoleRow, HandReason, ScoredRole, Status, Subscription, Weights, company_key, levels_between, ) from app.storage import Store from app.web.deps import ConfigDep, StoreDep +from desk.notices import classify from desk.tools import agent from pipeline import Job from pipeline.web import QueueDep @@ -72,7 +74,7 @@ def _feed_filters( tags: list[str] = Query(default=[]), tag_mode: Literal["any", "all"] = "any", agent: int | None = None, - order: Literal["score", "newest"] = "score", + order: Literal["score", "newest", "cv"] = "score", gated: bool = False, judged: Literal["", "liked", "unjudged", "passed"] = "", pay: Literal["", "stated", "normalised", "stated_only"] = "", @@ -83,13 +85,16 @@ def _feed_filters( track: str = "", seniority_unknown: bool = True, pay_unknown: bool = False, + closing: bool = False, ) -> dict[str, Any]: """The feed's filters, as `Store.roles_page`, `count_roles` and `role_facets` take them, read from the query of `GET /api/roles` and `GET /api/roles/facets` alike. A place token that names nothing, a rung outside `RUNGS` and a track outside `TRACKS` are a 422 sentence, not an empty feed. The three seniority parameters become the levels between - them (`levels_between`), which is what the store filters on.""" + them (`levels_between`), which is what the store filters on. `order=cv` + is the score order with the agent's judged roles first by `cv_score` + (`by_cv`).""" for token in tokens: if not places.known(token): raise HTTPException(422, f"No place is known as {token!r}.") @@ -110,10 +115,11 @@ def _feed_filters( "function": function or None, "remote": remote or None, "days": days, "hide_muted": not show_muted, "include_read": include_read, "tags": tags, "tag_mode": tag_mode, "agent": _agent_id(store, agent), - "by_score": agent is not None and order == "score", "gated": gated, + "by_score": agent is not None and order in ("score", "cv"), + "by_cv": agent is not None and order == "cv", "gated": gated, "judged": judged or None, "pay": pay or None, "company_keys": company_keys, "places": tokens, "seniority": list(levels), "seniority_unknown": seniority_unknown, - "pay_unknown": pay_unknown} + "pay_unknown": pay_unknown, "closing": closing} FeedFilters = Annotated[dict[str, Any], Depends(_feed_filters)] @@ -145,7 +151,8 @@ def role_facets(store: StoreDep, filters: FeedFilters) -> Facets: @router.get("/roles/{uid}") def get_role(uid: str, store: StoreDep, agent: int | None = None) -> ScoredRole: """One role, open or closed, for the read page, with `agent`'s vote and - score, and the prompt that gave its fit (the default agent's when absent; + score, the prompt that gave its fit, its `judgement` against the agent's + CV and the language flag (the default agent's when absent; None when there is no agent). `copies` lists the open copies of a kept role (`RoleCopy`, for "Also posted"); a copy itself opens too, with `dup_of` naming its kept role.""" @@ -224,7 +231,9 @@ def list_roles( passed. With `order=score` (the default) the roles are the ones that agent scored, best first, carrying `score` and `gated_reason`, a gated one only with `gated=1`; with `order=newest` every open role, newest - first, with no score. Without `agent` the default agent's votes and + first, with no score; with `order=cv` (Best CV match) the scored roles + the agent's `judge` read come first by `cv_score`, the rest after them + by score. Without `agent` the default agent's votes and hidden companies apply, the order is newest and there is no score; with no agent at all, every vote is None and nothing is hidden. @@ -233,7 +242,12 @@ def list_roles( `tag_mode=all`, every one. `pay` keeps only roles whose `salary_state` is stated or normalised, normalised only, or stated but not normalised (`Store.PAY`); `pay_unknown` lets the roles that state no pay through - as well. + as well. `closing=1` keeps the roles whose `deadline` is today or in + the next four days (Closing soon). + + Each row carries `deadline`, the agent's `cv_score` (None when not + judged), and `lang_flag` and `lang_note`, the posting's languages + against the agent's (`app.models.language_flag`). `company` and `place` are substrings, kept for links from other pages. The rail's fields are `company_keys` (repeated, exact keys) and @@ -1189,7 +1203,10 @@ class AgentBody(BaseModel): `intent` is the body from before an agent had prompts: without `prompts` it is stored as one prompt named after the agent. `fetch_terms` narrow what big boards send (`app/jobs/reach.py`); `[]` narrows nothing, and - leaving the key out keeps an existing agent's.""" + leaving the key out keeps an existing agent's. `cv_text`, + `cv_languages`, `avoid_text` and `must_text` are what `judge` reads a + role against (`app/jobs/judge.py`), kept the same way when left out or + null.""" id: int | None = None name: str = Field(min_length=1) @@ -1199,9 +1216,40 @@ class AgentBody(BaseModel): weights: Weights = Weights() limits: Limits = Limits() fetch_terms: FetchTerms | None = None + cv_text: str | None = None + cv_languages: CvLanguages | None = None + avoid_text: str | None = None + must_text: str | None = None enabled: bool = True +class CvText(BaseModel): + cv_text: str = Field(min_length=1) + + +class CvLanguagesOut(BaseModel): + languages: list[CvLanguage] + + +@router.post("/agents/cv-languages") +def cv_languages(body: CvText, config: ConfigDep) -> CvLanguagesOut: + """The languages a CV states, each with a level, from one model call + (`jobs.judge.suggest_languages`), for the owner to edit before saving. + Nothing is stored. 503 when no model is reachable, 502 when the call + gives no answer.""" + if not body.cv_text.strip(): + raise HTTPException(422, "Paste a CV first.") + if not agent.backend(config.agent): + raise HTTPException(503, "No model is reachable from here, so nothing can read the " + "languages. Set up the API key or Claude Code.") + try: + found = jobs.judge.suggest_languages(config, body.cv_text) + except agent.AgentError as exc: + raise HTTPException(502, classify(exc, backend=agent.backend(config.agent)).text) \ + from exc + return CvLanguagesOut(languages=found) + + @router.post("/agents") def save_agent(body: AgentBody, store: StoreDep, queue: QueueDep) -> Agent: """Queues the rescore, which the page's `POST /api/score` after a save @@ -1209,7 +1257,9 @@ def save_agent(body: AgentBody, store: StoreDep, queue: QueueDep) -> Agent: try: saved = store.save_agent(body.name, body.intent, body.gates, body.weights, body.enabled, agent_id=body.id, limits=body.limits, - prompts=body.prompts, fetch_terms=body.fetch_terms) + prompts=body.prompts, fetch_terms=body.fetch_terms, + cv_text=body.cv_text, cv_languages=body.cv_languages, + avoid_text=body.avoid_text, must_text=body.must_text) except ValueError as exc: raise HTTPException(409, str(exc)) from exc except KeyError: diff --git a/tests/test_cv_feed.py b/tests/test_cv_feed.py new file mode 100644 index 0000000..57d09a0 --- /dev/null +++ b/tests/test_cv_feed.py @@ -0,0 +1,178 @@ +"""The CV match in the feed and the API: Best CV match, Closing soon, the +new row and role fields, the agent's CV fields over `/api/agents`, and the +languages suggested from a CV. Nothing here reaches a model.""" + +from __future__ import annotations + +import json +from collections.abc import Iterator +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from app.config import Config, ServerConfig +from app.main import create_app +from app.models import CvLanguage, Prompt +from app.storage import Store +from desk.models import Item +from desk.tools import agent +from prepped import upsert + + +def posting(source_id: str, **raw: object) -> Item: + item = Item(source_id=source_id, location=f"https://boards.example/{source_id}", + title=f"Head of Data {source_id}", body="Lead the data team.", + published_at=datetime(2026, 9, 20, tzinfo=UTC), raw=dict(raw)) + item.source = "search" + return item + + +@pytest.fixture +def app(tmp_path: Path) -> FastAPI: + return create_app(Config(server=ServerConfig(host="127.0.0.1", port=0), + database=tmp_path / "roledesk.db")) + + +@pytest.fixture +def store(app: FastAPI) -> Store: + found: Store = app.state.store + found.clock = lambda: datetime(2026, 10, 3, 9, 0, tzinfo=UTC) + return found + + +@pytest.fixture +def client(app: FastAPI) -> Iterator[TestClient]: + with TestClient(app) as c: + yield c + + +def setup(store: Store) -> tuple[Any, dict[str, str]]: + """Four roles scored a > b > c > d for an agent with a CV and languages; + c is judged 90 and b 60, a and d not at all; d is gated.""" + owner = store.save_agent("Data", prompts=[Prompt(name="Lead", text="Head of data")], + cv_text="VP Data.", + cv_languages=[CvLanguage(language="da", level="native"), + CvLanguage(language="de", level="professional")]) + uid = {} + for sid, deadline in (("a", "2026-10-03"), ("b", "2026-10-07"), ("c", "2026-10-08"), + ("d", "2026-10-04")): + upsert(store, posting(sid, applicationDeadline=deadline)) + uid[sid] = posting(sid).uid + store.replace_scores(owner.id, [(uid["a"], 0.9, ""), (uid["b"], 0.8, ""), + (uid["c"], 0.7, ""), (uid["d"], 0.6, "gated")]) + store.set_judgement(owner.id, uid["c"], "k", 90, 90, 90, ["Leads data."], ["Small team."]) + store.set_judgement(owner.id, uid["b"], "k", 60, 60, 60, ["Data."], ["Junior."]) + with store.transaction() as conn: + conn.execute("UPDATE roles SET languages_required = ? WHERE uid = ?", (json.dumps( + [{"language": "sv", "level": "fluent", "kind": "required"}]), uid["a"])) + conn.execute("UPDATE roles SET languages_required = ? WHERE uid = ?", (json.dumps( + [{"language": "de", "level": "fluent", "kind": "required"}]), uid["b"])) + conn.execute("UPDATE roles SET languages_required = ? WHERE uid = ?", (json.dumps( + [{"language": "da", "level": "", "kind": "plus"}]), uid["c"])) + return owner, uid + + +def test_best_cv_match_puts_the_judged_first_by_cv_score( + client: TestClient, store: Store) -> None: + owner, uid = setup(store) + page = client.get("/api/roles", params={"agent": owner.id, "order": "cv"}).json() + assert [r["uid"] for r in page["items"]] == [uid["c"], uid["b"], uid["a"]] + assert [r["cv_score"] for r in page["items"]] == [90.0, 60.0, None] + assert page["total"] == 3 + scored = client.get("/api/roles", params={"agent": owner.id}).json()["items"] + assert [r["uid"] for r in scored] == [uid["a"], uid["b"], uid["c"]] + assert scored[1]["cv_score"] == 60.0, "the total rides on every order" + assert client.get("/api/roles", params={"agent": owner.id, + "order": "best"}).status_code == 422 + + +def test_a_row_carries_the_deadline_and_the_language_flag( + client: TestClient, store: Store) -> None: + owner, uid = setup(store) + rows = {r["uid"]: r for r in + client.get("/api/roles", params={"agent": owner.id}).json()["items"]} + assert rows[uid["a"]]["deadline"] == "2026-10-03" + assert (rows[uid["a"]]["lang_flag"], rows[uid["a"]]["lang_note"]) == \ + ("missing", "requires Swedish (fluent); yours: none") + assert (rows[uid["b"]]["lang_flag"], rows[uid["b"]]["lang_note"]) == \ + ("below", "requires German (fluent); yours: professional") + assert (rows[uid["c"]]["lang_flag"], rows[uid["c"]]["lang_note"]) == \ + ("plus", "Danish is a plus; yours: native") + + +def test_closing_soon_keeps_today_to_four_days_on(client: TestClient, store: Store) -> None: + owner, uid = setup(store) + params = {"agent": owner.id, "order": "newest", "closing": 1} + page = client.get("/api/roles", params=params).json() + assert sorted(r["uid"] for r in page["items"]) == sorted([uid["a"], uid["b"], uid["d"]]) + assert page["total"] == 3 + facets = client.get("/api/roles/facets", params=params).json() + assert sum(f["count"] for f in facets["pay"]) == 3 + + +def test_the_role_carries_its_judgement_and_languages( + client: TestClient, store: Store) -> None: + owner, uid = setup(store) + role = client.get(f"/api/roles/{uid['c']}", params={"agent": owner.id}).json() + judgement = role["judgement"] + assert (judgement["skills"], judgement["cv_score"]) == (90, 90.0) + assert judgement["strengths"] == ["Leads data."] and judgement["gaps"] == ["Small team."] + assert judgement["judged_at"] + assert role["cv_score"] == 90.0 and role["lang_flag"] == "plus" + assert role["languages_required"] == [{"language": "da", "level": "", "kind": "plus"}] + assert role["deadline"] == "2026-10-08" + plain = client.get(f"/api/roles/{uid['a']}", params={"agent": owner.id}).json() + assert plain["judgement"] is None and plain["cv_score"] is None + + +def test_an_agent_without_languages_flags_nothing(client: TestClient, store: Store) -> None: + owner, uid = setup(store) + store.save_agent("Data", prompts=owner.prompts, agent_id=owner.id, cv_languages=[]) + rows = client.get("/api/roles", params={"agent": owner.id}).json()["items"] + assert {r["lang_flag"] for r in rows} == {""} + + +def test_the_cv_fields_round_trip_and_are_kept_when_left_out(client: TestClient) -> None: + body = {"name": "Data", "cv_text": "VP Data.", "avoid_text": "Reporting.", + "must_text": "Permanent.", + "cv_languages": [{"language": "da", "level": "native"}, + {"language": "EN", "level": "fluent"}]} + made = client.post("/api/agents", json=body).json() + assert made["cv_languages"] == [{"language": "da", "level": "native"}, + {"language": "en", "level": "fluent"}] + kept = client.post("/api/agents", json={"id": made["id"], "name": "Data"}).json() + assert (kept["cv_text"], kept["avoid_text"], kept["must_text"]) == \ + ("VP Data.", "Reporting.", "Permanent.") + assert len(kept["cv_languages"]) == 2 + nulls = client.post("/api/agents", json={"id": made["id"], "name": "Data", + "cv_text": None, "cv_languages": None}).json() + assert nulls["cv_text"] == "VP Data." and len(nulls["cv_languages"]) == 2 + bad = client.post("/api/agents", json={"name": "Bad", "cv_languages": [ + {"language": "da", "level": "good"}]}) + assert bad.status_code == 422 + + +def test_the_languages_of_a_cv_are_suggested_and_nothing_stored( + client: TestClient, store: Store, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(agent, "backend", lambda settings: "api") + monkeypatch.setattr(agent, "ask_json", lambda settings, **kwargs: agent.Reply( + data={"languages": [{"language": "da", "level": "native"}]}, backend="api")) + res = client.post("/api/agents/cv-languages", json={"cv_text": "Dansk modersmål."}) + assert res.status_code == 200 + assert res.json() == {"languages": [{"language": "da", "level": "native"}]} + assert store.agents() == [] + assert client.post("/api/agents/cv-languages", json={"cv_text": " "}).status_code == 422 + + def fails(settings: Any, **kwargs: Any) -> agent.Reply: + raise agent.AgentError("timed out") + + monkeypatch.setattr(agent, "ask_json", fails) + assert client.post("/api/agents/cv-languages", json={"cv_text": "CV"}).status_code == 502 + + monkeypatch.setattr(agent, "backend", lambda settings: "") + res = client.post("/api/agents/cv-languages", json={"cv_text": "CV"}) + assert res.status_code == 503 and "No model is reachable" in res.json()["detail"] diff --git a/tests/test_storage.py b/tests/test_storage.py index 626cf38..a4c30e1 100644 --- a/tests/test_storage.py +++ b/tests/test_storage.py @@ -1011,7 +1011,7 @@ def test_the_newest_feed_query_uses_the_partial_posted_at_index( assert "INDEXED BY idx_roles_posted" in captured[0] with sqlite3.connect(store.path) as conn: plan = " ".join(row[3] for row in - conn.execute("EXPLAIN QUERY PLAN " + captured[0], [None, 10, 0])) + conn.execute("EXPLAIN QUERY PLAN " + captured[0], [None, None, 10, 0])) assert "USING INDEX idx_roles_posted" in plan and "TEMP B-TREE" not in plan # open_only=False cannot use it: the index is partial on closed_at IS NULL.