Per-agent ranking: votes, affinity and a taste term; settings are three sub-tabs

Votes on roles and company affinity move to role_votes and agent_companies,
one row per search agent, so two agents rank the same roles differently. The
score gains taste, the cosine to mean(liked) - mean(passed) of the agent's
votes, as newsdesk ranks articles. The API takes agent on roles, votes and
companies and falls back to the default agent, the enabled one with the
lowest id.

Settings become Search agents (a list again, with New and Delete), Sources
(job boards, company boards and runs with the message log, one section per
plugin) and Account. Old paths answer 301 to their section.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-09-28 12:53:41 +02:00
1 parent 515d2250fc
commit a0772519b3
28 files changed
+1461 -668

No files matched your search

+60 -6
View File
@@ -67,10 +67,6 @@ CREATE TABLE IF NOT EXISTS roles (
-- Replies from extract that left this role unanswered. At GIVE_UP_AFTER it
-- is no longer offered. A column, not raw, because every upsert rewrites raw.
extract_tries INTEGER NOT NULL DEFAULT 0,
-- The owner's judgement of the role: NULL unjudged, else -1 pass, 0
-- neutral, 1 like. It moves the rank at read time and never hides a role.
vote INTEGER CHECK (vote IN (-1, 0, 1)),
voted_at TEXT,
-- About 60 words from summarise, and when it wrote them.
summary TEXT NOT NULL DEFAULT '',
summarised_at TEXT,
@@ -87,8 +83,6 @@ CREATE TABLE IF NOT EXISTS companies (
key TEXT PRIMARY KEY,
name TEXT NOT NULL,
domain TEXT NOT NULL DEFAULT '',
-- -1 mute, 0 neutral, 1 interested, 2 favourite.
affinity INTEGER NOT NULL DEFAULT 0 CHECK (affinity BETWEEN -1 AND 2),
status TEXT NOT NULL DEFAULT 'researching',
careers_url TEXT NOT NULL DEFAULT '',
notes TEXT NOT NULL DEFAULT '',
@@ -167,6 +161,29 @@ CREATE TABLE IF NOT EXISTS agents (
intent_vec BLOB
);
-- One agent's stance on a company: -1 hidden, 0 neutral, 1 liked, 2
-- favourite. No row is 0, so the table holds only what somebody set. Per
-- agent, because a company that is noise for one search is the target of
-- another.
CREATE TABLE IF NOT EXISTS agent_companies (
agent_id INTEGER NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
company_key TEXT NOT NULL,
affinity INTEGER NOT NULL CHECK (affinity BETWEEN -1 AND 2),
updated_at TEXT NOT NULL,
PRIMARY KEY (agent_id, company_key)
);
-- One agent's judgement of a role: -1 pass, 0 neutral, 1 like. No row is
-- unjudged. A vote moves the rank at read time, never hides a role, and its
-- vectors shape the agent's taste direction in `score`.
CREATE TABLE IF NOT EXISTS role_votes (
agent_id INTEGER NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
uid TEXT NOT NULL REFERENCES roles(uid) ON DELETE CASCADE,
vote INTEGER NOT NULL CHECK (vote IN (-1, 0, 1)),
voted_at TEXT NOT NULL,
PRIMARY KEY (agent_id, uid)
);
-- A role is scored per agent. A gated role keeps its row, with the reason.
CREATE TABLE IF NOT EXISTS scores (
uid TEXT NOT NULL REFERENCES roles(uid) ON DELETE CASCADE,
@@ -207,6 +224,7 @@ CREATE INDEX IF NOT EXISTS idx_roles_board ON roles(source, subscription_id
CREATE INDEX IF NOT EXISTS idx_application_events
ON application_events(application_id, at);
CREATE INDEX IF NOT EXISTS idx_scores_agent ON scores(agent_id, score DESC);
CREATE INDEX IF NOT EXISTS idx_role_votes_agent ON role_votes(agent_id, vote);
CREATE INDEX IF NOT EXISTS idx_vectors_model ON vectors(model);
"""
@@ -244,6 +262,42 @@ ALTER TABLE roles ADD COLUMN summary TEXT NOT NULL DEFAULT '';
ALTER TABLE roles ADD COLUMN summarised_at TEXT;
ALTER TABLE roles ADD COLUMN article_text TEXT NOT NULL DEFAULT '';
ALTER TABLE roles ADD COLUMN article_at TEXT;
"""),
# Votes and affinities move from the role and company rows to one row per
# agent. What was global goes to the default agent, the enabled one with
# the lowest id (`Store.default_agent`); a file with something to move and
# no agent gets one first, so nothing is lost. The columns are then
# dropped, which SQLite has allowed since 3.35.
(5, "agent_companies and role_votes: affinity and vote become per agent", """
CREATE TABLE agent_companies (
agent_id INTEGER NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
company_key TEXT NOT NULL,
affinity INTEGER NOT NULL CHECK (affinity BETWEEN -1 AND 2),
updated_at TEXT NOT NULL,
PRIMARY KEY (agent_id, company_key)
);
CREATE TABLE role_votes (
agent_id INTEGER NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
uid TEXT NOT NULL REFERENCES roles(uid) ON DELETE CASCADE,
vote INTEGER NOT NULL CHECK (vote IN (-1, 0, 1)),
voted_at TEXT NOT NULL,
PRIMARY KEY (agent_id, uid)
);
INSERT INTO agents (name, intent, gates, weights, enabled, created_at)
SELECT 'My ranking', '', '[]', '{}', 1, strftime('%Y-%m-%dT%H:%M:%S+00:00', 'now')
WHERE NOT EXISTS (SELECT 1 FROM agents)
AND (EXISTS (SELECT 1 FROM roles WHERE vote IS NOT NULL)
OR EXISTS (SELECT 1 FROM companies WHERE affinity <> 0));
INSERT INTO role_votes (agent_id, uid, vote, voted_at)
SELECT (SELECT id FROM agents ORDER BY enabled DESC, id LIMIT 1), uid, vote,
COALESCE(voted_at, strftime('%Y-%m-%dT%H:%M:%S+00:00', 'now'))
FROM roles WHERE vote IS NOT NULL;
INSERT INTO agent_companies (agent_id, company_key, affinity, updated_at)
SELECT (SELECT id FROM agents ORDER BY enabled DESC, id LIMIT 1), key, affinity, updated_at
FROM companies WHERE affinity <> 0;
ALTER TABLE roles DROP COLUMN vote;
ALTER TABLE roles DROP COLUMN voted_at;
ALTER TABLE companies DROP COLUMN affinity;
"""),
)
+156 -89
View File
@@ -51,21 +51,29 @@ _EXTRACT_WAITING = (f"extracted_at IS NULL AND closed_at IS NULL "
#: What a vote may be: 1 like, 0 neither way, -1 pass, None unjudged.
VOTES = (-1, 0, 1, None)
#: The `judged` filter of `Store.roles`, as a `WHERE` on `roles.vote`. A
#: neutral vote is judged, and is neither liked nor passed.
#: The `judged` filter of `Store.roles`, as a `WHERE` on the agent's vote,
#: joined as `v`. A neutral vote is judged, and is neither liked nor passed.
JUDGED: dict[str, str] = {
"liked": "roles.vote = 1",
"unjudged": "roles.vote IS NULL",
"passed": "roles.vote = -1",
"liked": "v.vote = 1",
"unjudged": "v.vote IS NULL",
"passed": "v.vote = -1",
}
#: A ranking's score as `Store.roles` serves and orders it: halved by a pass,
#: lifted a fifth by a like, capped at 1. Applied at read time, so a vote
#: moves the role at once and the stored score stays what `score` computed.
_VOTED_SCORE = ("MIN(1.0, s.score * CASE roles.vote WHEN -1 THEN 0.5 "
_VOTED_SCORE = ("MIN(1.0, s.score * CASE v.vote WHEN -1 THEN 0.5 "
"WHEN 1 THEN 1.2 ELSE 1 END)")
_COMPANY_FIELDS = ("name", "domain", "affinity", "status", "careers_url", "notes")
#: The agent's votes beside every role. With no agent the join matches
#: 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 = ?"
_COMPANY_FIELDS = ("name", "domain", "status", "careers_url", "notes")
#: A company as the store serves it: the row and the asked-for agent's affinity.
_COMPANY_SELECT = """SELECT c.*, COALESCE(ac.affinity, 0) AS affinity FROM companies c
LEFT JOIN agent_companies ac ON ac.company_key = c.key AND ac.agent_id = ?"""
_SUBSCRIPTION_FIELDS = ("label", "company", "board", "params", "subscribed", "fetch",
"show", "target_id")
@@ -280,89 +288,119 @@ class Store:
f"ON CONFLICT(uid) DO UPDATE SET {', '.join(updates)}", row)
return not existed
def role(self, uid: str) -> Role | None:
row = self._row("SELECT * FROM roles WHERE uid=?", (uid,))
def role(self, uid: str, agent_id: int | None = None) -> Role | None:
"""One role, with `vote` and `voted_at` as `agent_id` judged it; None
(unjudged) without an agent."""
row = self._row(f"SELECT roles.*, v.vote, v.voted_at FROM roles {_WITH_VOTES} "
"WHERE roles.uid=?", (agent_id, uid))
return Role.from_row(row) if row else None
def set_vote(self, uid: str, value: int | None) -> Role:
"""Judge one role: 1 like, 0 neither way, -1 pass, None unjudged again.
Stamps `voted_at`, or clears it with the vote. A vote never hides a
role; it moves it in a ranking (see `roles`). Raises ValueError for
another value and KeyError for an unknown uid."""
def set_vote(self, agent_id: int, uid: str, value: int | None) -> Role:
"""One agent's judgement of one role: 1 like, 0 neither way, -1 pass,
None unjudged again, which deletes the row. A vote never hides a
role; it moves it in that agent's ranking (see `roles`) and shapes its
taste direction (see `jobs/score.py`). Returns the role with this
agent's vote. Raises ValueError for another value and KeyError for an
unknown uid or agent."""
if isinstance(value, bool) or value not in VOTES:
raise ValueError(f"a vote is -1, 0 or 1, not {value!r}")
stamp = None if value is None else self.now()
if not self._write("UPDATE roles SET vote=?, voted_at=? WHERE uid=?",
(value, stamp, uid)):
raise KeyError(uid)
role = self.role(uid)
with self.transaction() as conn:
self._known(conn, "roles", "uid", uid)
self._known(conn, "agents", "id", agent_id)
if value is None:
conn.execute("DELETE FROM role_votes WHERE agent_id=? AND uid=?",
(agent_id, uid))
else:
conn.execute(
"""INSERT INTO role_votes (agent_id, uid, vote, voted_at) VALUES (?,?,?,?)
ON CONFLICT(agent_id, uid) DO UPDATE
SET vote=excluded.vote, voted_at=excluded.voted_at""",
(agent_id, uid, value, self.now()))
role = self.role(uid, agent_id)
assert role is not None
return role
def votes(self, agent_id: int) -> dict[str, int]:
"""`uid -> vote` for one agent, open roles and closed alike: a closed
role somebody liked still says what they like."""
return {r["uid"]: int(r["vote"]) for r in self._rows(
"SELECT uid, vote FROM role_votes WHERE agent_id=?", (agent_id,))}
@staticmethod
def _known(conn: sqlite3.Connection, table: str, column: str, value: Any) -> None:
"""KeyError unless the row exists: the caller's 404, rather than the
foreign key's IntegrityError, which does not say which side is unknown."""
if conn.execute(f"SELECT 1 FROM {table} WHERE {column}=?", (value,)).fetchone() is None:
raise KeyError(value)
def roles(self, limit: int = 100, company: str | None = None,
place: str | None = None, open_only: bool = True,
q: str | None = None, function: str | None = None,
remote: str | None = None, days: int | None = None,
hide_muted: bool = False, agent: int | None = None,
gated: bool = False, judged: str | None = None,
offset: int = 0) -> list[ScoredRole]:
by_score: bool = True, gated: bool = False,
judged: str | None = None, offset: int = 0) -> list[ScoredRole]:
"""Newest first by `first_seen`. `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
to. `q` is matched word by word against `title`; a role must match
every word. `function` and `remote` match a gate column exactly.
`days` keeps only roles first seen within that many days of now.
`judged` is a key of `JUDGED`: liked, unjudged or passed.
`hide_muted` excludes a muted company's roles before `limit` is
applied, in SQL rather than after the fact: a company that has
published a lot, all at once — a fresh board added, a re-pull that
finally reached it — can otherwise fill the whole page with roles
that then all turn out to be from the one company someone muted,
leaving nothing to show for a default query that would otherwise
have plenty.
`agent` says whose votes, hidden companies and scores are meant. Each
row carries that agent's `vote` and `voted_at`; `judged` (a key of
`JUDGED`: liked, unjudged or passed) filters on them. `hide_muted`
excludes the companies that agent hid, before `limit` is applied, in
SQL rather than after the fact: a company that has published a lot,
all at once — a fresh board added, a re-pull that finally reached
it — can otherwise fill the whole page with roles that then all turn
out to be from the one company someone hid, leaving nothing to show
for a default query that would otherwise have plenty. With no agent
every vote is None, nothing is hidden and `judged` reads as such.
`agent` orders by that agent's score instead, highest first, and
carries `score` and `gated_reason` on each row. Only roles it has
scored are listed, and a gated one only when `gated` is set. The score
is the stored one moved by the role's vote (`_VOTED_SCORE`), so a vote
shows in the order at once and needs no rescore.
With `agent` and `by_score`, ordered by that agent's score instead,
highest first, carrying `score` and `gated_reason` on each row. Only
roles it has scored are listed, and a gated one only when `gated` is
set. The score is the stored one moved by the agent's vote
(`_VOTED_SCORE`), so a vote shows in the order at once and needs no
rescore. With `by_score` off the order is newest, with the votes and
no score.
`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."""
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, agent=agent, gated=gated,
judged=judged)
if agent is None:
select = "SELECT roles.* "
order = "roles.first_seen DESC, roles.uid"
else:
select = f"SELECT roles.*, {_VOTED_SCORE} AS score, s.gated_reason "
order = "score DESC, roles.first_seen DESC, roles.uid"
remote=remote, days=days, hide_muted=hide_muted, agent=agent,
by_score=by_score, gated=gated, judged=judged)
select = "SELECT roles.*, v.vote, v.voted_at"
order = "roles.first_seen DESC, roles.uid"
if agent is not None and by_score:
select += f", {_VOTED_SCORE} AS score, s.gated_reason"
order = "score DESC, " + order
return [ScoredRole.from_row(r) for r in self._rows(
f"{select}{sql} ORDER BY {order} LIMIT ? OFFSET ?", [*params, limit, offset])]
f"{select} {sql} ORDER BY {order} LIMIT ? OFFSET ?", [*params, limit, offset])]
def count_roles(self, company: str | None = None, place: str | None = None,
open_only: bool = True, q: str | None = None,
function: str | None = None, remote: str | None = None,
days: int | None = None, hide_muted: bool = False,
agent: int | None = None, gated: bool = False,
judged: str | None = None) -> int:
agent: int | None = None, by_score: bool = True,
gated: bool = False, judged: str | None = None) -> 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, agent=agent, gated=gated,
judged=judged)
remote=remote, days=days, hide_muted=hide_muted, agent=agent,
by_score=by_score, gated=gated, judged=judged)
row = self._row(f"SELECT COUNT(*) AS n {sql}", params)
return int(row["n"]) if row else 0
def _roles_from(self, *, company: str | None, place: str | None, open_only: bool,
q: str | None, function: str | None, remote: str | None,
days: int | None, hide_muted: bool, agent: int | None,
gated: bool, judged: str | None) -> tuple[str, list[Any]]:
by_score: bool, gated: bool, judged: str | None) -> tuple[str, list[Any]]:
"""The `FROM ... WHERE ...` that `roles` and `count_roles` share, with
its parameters in order."""
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."""
where: list[str] = []
params: list[Any] = []
if company:
@@ -389,14 +427,14 @@ class Store:
where.append(JUDGED[judged])
if open_only:
where.append("closed_at IS NULL")
if hide_muted:
where.append("company_key NOT IN "
"(SELECT key FROM companies WHERE affinity = -1)")
joins: list[Any] = []
if agent is None:
sql = "FROM roles"
else:
sql = "FROM roles JOIN scores s ON s.uid = roles.uid AND s.agent_id = ?"
if hide_muted and agent is not None:
where.append("company_key NOT IN (SELECT company_key FROM agent_companies "
"WHERE agent_id = ? AND affinity = -1)")
params.append(agent)
sql = f"FROM roles {_WITH_VOTES}"
joins: list[Any] = [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)
if not gated:
where.append("s.gated_reason = ''")
@@ -520,8 +558,9 @@ class Store:
"""The `WHERE` for a role `summarise` may be sent: no summary yet and
some text to summarise. Given `uids`, those of them and nothing else,
open or not and given up or not, because somebody asked for them.
Otherwise open, not of a hidden company, not given up, and among the
`per_agent` best ungated scores of an enabled agent."""
Otherwise open, not given up, and among the `per_agent` best ungated
scores of an enabled agent. A company an agent hid needs no clause:
`score` writes no rows for it under that agent."""
where = ["r.summary = ''",
"(TRIM(r.article_text) <> '' OR TRIM(r.description) <> '')"]
if uids is not None:
@@ -529,7 +568,6 @@ class Store:
return " AND ".join(where), [json.dumps(list(uids))]
where += [
"r.closed_at IS NULL",
"r.company_key NOT IN (SELECT key FROM companies WHERE affinity = -1)",
f"""NOT EXISTS (SELECT 1 FROM state
WHERE key = '{self._SUMMARY_MISSED}' || r.uid
AND CAST(value AS INTEGER) >= {GIVE_UP_AFTER})""",
@@ -652,6 +690,12 @@ class Store:
row = self._row("SELECT * FROM agents WHERE id=?", (agent_id,))
return Agent.from_row(row) if row else None
def default_agent(self) -> Agent | None:
"""The agent a vote or an affinity goes to when none is named: the
enabled one with the lowest id, else the lowest id, else None."""
row = self._row("SELECT * FROM agents ORDER BY enabled DESC, id LIMIT 1")
return Agent.from_row(row) if row else None
def save_agent(self, name: str, intent: str = "", gates: Sequence[Gate] = (),
weights: Weights | None = None, enabled: bool = True,
agent_id: int | None = None) -> Agent:
@@ -682,7 +726,7 @@ class Store:
return found
def delete_agent(self, agent_id: int) -> bool:
"""Its scores go with it, by the foreign key."""
"""Its scores, votes and affinities go with it, by the foreign keys."""
return self._write("DELETE FROM agents WHERE id=?", (agent_id,)) > 0
def intent_vector(self, agent_id: int, key: str) -> np.ndarray | None:
@@ -699,11 +743,12 @@ class Store:
# --------------------------------------------------------------- scores
def score_candidates(self, gates: Sequence[Gate]) -> list[Candidate]:
"""Every open role of a company that is not muted, with how it meets
each gate: 1 match, 0 no match, -1 the column is empty. The gates are
evaluated here, in SQL, so a `require` gate is the `WHERE` it reads
as, written as a column so a gated role keeps its row and reason."""
def score_candidates(self, agent_id: int, gates: Sequence[Gate]) -> list[Candidate]:
"""Every open role of a company this agent has not hidden, with the
agent's affinity for the company and how the role meets each gate: 1
match, 0 no match, -1 the column is empty. The gates are evaluated
here, in SQL, so a `require` gate is the `WHERE` it reads as, written
as a column so a gated role keeps its row and reason."""
columns: list[str] = []
params: list[Any] = []
for n, gate in enumerate(gates):
@@ -712,12 +757,13 @@ class Store:
f"CASE WHEN {empty} THEN -1 WHEN {match} THEN 1 ELSE 0 END AS g{n}")
params += values
select = ", ".join(["r.uid", "r.first_seen",
"COALESCE(c.affinity, 0) AS affinity", *columns])
"COALESCE(ac.affinity, 0) AS affinity", *columns])
rows = self._rows(
f"""SELECT {select} FROM roles r
LEFT JOIN companies c ON c.key = r.company_key
WHERE r.closed_at IS NULL AND COALESCE(c.affinity, 0) <> -1""",
params)
LEFT JOIN agent_companies ac
ON ac.company_key = r.company_key AND ac.agent_id = ?
WHERE r.closed_at IS NULL AND COALESCE(ac.affinity, 0) <> -1""",
[*params, agent_id])
return [Candidate(uid=r["uid"], first_seen=r["first_seen"],
affinity=int(r["affinity"]),
gates=[int(r[f"g{n}"]) for n in range(len(gates))])
@@ -748,40 +794,61 @@ class Store:
# ------------------------------------------------------------ companies
def add_company(self, name: str, *, key: str = "", domain: str = "",
affinity: int = 0, status: str = "researching",
careers_url: str = "", notes: str = "") -> Company:
"""Raises ValueError on a key already taken or an affinity out of range."""
status: str = "researching", careers_url: str = "",
notes: str = "") -> Company:
"""Raises ValueError on a key already taken."""
name = name.strip()
key = key or company_key(name)
if not key:
raise ValueError("a company needs a name")
_check_affinity(affinity)
stamp = self.now()
try:
self._write(
"""INSERT INTO companies (key, name, domain, affinity, status,
careers_url, notes, created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?,?)""",
(key, name, domain, affinity, status, careers_url, notes, stamp, stamp))
"""INSERT INTO companies (key, name, domain, status, careers_url, notes,
created_at, updated_at)
VALUES (?,?,?,?,?,?,?,?)""",
(key, name, domain, status, careers_url, notes, stamp, stamp))
except sqlite3.IntegrityError as exc:
raise ValueError(f"company {key!r} already exists") from exc
return self._company(key)
def company(self, key: str) -> Company | None:
row = self._row("SELECT * FROM companies WHERE key=?", (key,))
def company(self, key: str, agent_id: int | None = None) -> Company | None:
"""One company, with `affinity` as `agent_id` set it; 0 without an agent."""
row = self._row(f"{_COMPANY_SELECT} WHERE c.key=?", (agent_id, key))
return Company.from_row(row) if row else None
def companies(self) -> list[Company]:
return [Company.from_row(r)
for r in self._rows("SELECT * FROM companies ORDER BY name COLLATE NOCASE")]
def companies(self, agent_id: int | None = None) -> list[Company]:
"""Every company by name, with `affinity` as `agent_id` set it."""
return [Company.from_row(r) for r in self._rows(
f"{_COMPANY_SELECT} ORDER BY c.name COLLATE NOCASE", (agent_id,))]
def set_affinity(self, agent_id: int, key: str, affinity: int) -> Company:
"""One agent's stance on a company: -1 hidden, 0 neutral, 1 liked, 2
favourite. 0 deletes the row, since no row means neutral. Returns the
company with this agent's affinity. Raises ValueError for another
value and KeyError for an unknown company or agent."""
_check_affinity(affinity)
with self.transaction() as conn:
self._known(conn, "companies", "key", key)
self._known(conn, "agents", "id", agent_id)
if affinity == 0:
conn.execute("DELETE FROM agent_companies WHERE agent_id=? AND company_key=?",
(agent_id, key))
else:
conn.execute(
"""INSERT INTO agent_companies (agent_id, company_key, affinity, updated_at)
VALUES (?,?,?,?)
ON CONFLICT(agent_id, company_key) DO UPDATE
SET affinity=excluded.affinity, updated_at=excluded.updated_at""",
(agent_id, key, affinity, self.now()))
return self._company(key, agent_id)
def update_company(self, key: str, **fields: Any) -> Company:
"""Change any of name, domain, affinity, status, careers_url, notes."""
"""Change any of name, domain, status, careers_url, notes. Affinity is
per agent: `set_affinity`."""
unknown = set(fields) - set(_COMPANY_FIELDS)
if unknown:
raise ValueError(f"not a company field: {', '.join(sorted(unknown))}")
if "affinity" in fields:
_check_affinity(fields["affinity"])
if fields:
sets = ", ".join(f"{f}=?" for f in fields)
changed = self._write(f"UPDATE companies SET {sets}, updated_at=? WHERE key=?",
@@ -793,8 +860,8 @@ class Store:
def remove_company(self, key: str) -> bool:
return self._write("DELETE FROM companies WHERE key=?", (key,)) > 0
def _company(self, key: str) -> Company:
found = self.company(key)
def _company(self, key: str, agent_id: int | None = None) -> Company:
found = self.company(key, agent_id)
if found is None:
raise KeyError(key)
return found
@@ -986,5 +1053,5 @@ def _check_status(status: str) -> None:
def _check_affinity(affinity: Any) -> None:
if not isinstance(affinity, int) or affinity not in AFFINITY:
if isinstance(affinity, bool) or not isinstance(affinity, int) or affinity not in AFFINITY:
raise ValueError(f"affinity is -1, 0, 1 or 2, not {affinity!r}")