Coverage for app / services / ownership.py: 76%
212 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2Moving work into an organisation or project, with what it depends on.
4A personal resource becomes the organisation's — or a project's — by
5``POST /app/ownership/move``. Most work hangs together: an agent retrieves
6through the repositories granted to it, a repository holds sources, a
7skillset bundles skills, a skill runs custom workers, an experiment runs a
8dataset against agents, a dashboard tile runs on an agent. Move the agent
9alone and its personal repository either stops working for everyone else or,
10worse, keeps serving its owner's private sources to every member.
12So a move is planned first (``plan``, served by ``/ownership/preview``):
13starting from the resource, every dependency is classified —
15* **moves** — yours, personally: it goes too;
16* **already there** — owned by the destination, or a platform built-in;
17* **blocker** — someone else's, or another organisation's: the move is
18 refused until it is dealt with, because nobody can move another person's
19 work for them.
21The preview lists all three; the move does exactly what it listed. Each
22moved row writes a version whose changed fields name the owner columns, so
23the edit history says when it changed hands and who moved it.
25Moving is one way — personal to shared — and is for the person who owns the
26work. Moving something in is creating it there, so the caller's level in its
27area must allow that (``app/services/access.py``): writer for most kinds,
28editor for a rule. Anything it does not allow is a blocker, with the reason.
30Each movable type is one class registered in ``MOVABLE``; adding one is a
31class, not a branch.
32"""
34from __future__ import annotations
36from dataclasses import dataclass, field
37from typing import Any, ClassVar
38from uuid import UUID
40from fastapi import HTTPException, status
41from sqlalchemy.exc import IntegrityError
42from sqlalchemy.orm import Session
44from app.db.postgres import models as m
45from app.db.postgres.enums import HistoryEnum, RuleEnum
46from app.dependency.resource_access import verify_list_scope, verify_owner_scope
47from app.services import history
49H = HistoryEnum.ResourceType
52@dataclass(frozen=True)
53class Ref:
54 kind: str
55 id: UUID
58class Movable:
59 """One kind of resource that can change owner."""
61 kind: ClassVar[str]
62 model: ClassVar[type]
63 history_type: ClassVar[H]
64 label: ClassVar[str]
66 def dependencies(self, db: Session, row: Any) -> list[Ref]:
67 return []
69 def name(self, row: Any) -> str:
70 return getattr(row, "name", None) or str(row.id)
72 def prepare(self, row: Any) -> None:
73 """Anything a row must shed before it changes owner."""
76MOVABLE: dict[str, Movable] = {}
79def register(cls: type[Movable]) -> type[Movable]:
80 MOVABLE[cls.kind] = cls()
81 return cls
84def _ids(rows) -> list[UUID]:
85 return [row[0] for row in rows]
88@register
89class AgentMove(Movable):
90 kind, model, history_type, label = "agent", m.Agent, H.agent, "Agent"
92 def dependencies(self, db, row):
93 repos = db.query(m.AgentRepository.repository_id).filter(
94 m.AgentRepository.agent_id == row.id
95 )
96 skillsets = db.query(m.AgentSkillset.skillset_id).filter(
97 m.AgentSkillset.agent_id == row.id
98 )
99 return [Ref("repository", i) for i in _ids(repos.all())] + [
100 Ref("skillset", i) for i in _ids(skillsets.all())
101 ]
104@register
105class RepositoryMove(Movable):
106 kind, model, history_type, label = (
107 "repository",
108 m.KnowledgeRepository,
109 H.knowledge_repository,
110 "Repository",
111 )
113 def dependencies(self, db, row):
114 rows = db.query(m.RepositoryKnowledge.knowledge_id).filter(
115 m.RepositoryKnowledge.repository_id == row.id
116 )
117 return [Ref("knowledge", i) for i in _ids(rows.all())]
120@register
121class KnowledgeMove(Movable):
122 kind, model, history_type, label = (
123 "knowledge",
124 m.Knowledge,
125 H.knowledge,
126 "Knowledge source",
127 )
130@register
131class SkillsetMove(Movable):
132 kind, model, history_type, label = "skillset", m.Skillset, H.skillset, "Skillset"
134 def dependencies(self, db, row):
135 rows = db.query(m.SkillsetSkill.skill_id).filter(
136 m.SkillsetSkill.skillset_id == row.id
137 )
138 return [Ref("skill", i) for i in _ids(rows.all())]
141@register
142class SkillMove(Movable):
143 kind, model, history_type, label = "skill", m.Skill, H.skill, "Skill"
145 def dependencies(self, db, row):
146 from app.services.skill_graph import CUSTOM_WORKER_PREFIX, _agent_nodes
148 names = {
149 str(node.get("agent_name"))
150 for _, node in _agent_nodes(row.graph_definition or {})
151 if str(node.get("agent_name") or "").startswith(CUSTOM_WORKER_PREFIX)
152 }
153 if not names:
154 return []
155 rows = db.query(m.CustomWorker.id).filter(
156 m.CustomWorker.definition_name.in_(names)
157 )
158 return [Ref("worker", i) for i in _ids(rows.all())]
161@register
162class WorkerMove(Movable):
163 kind, model, history_type, label = (
164 "worker",
165 m.CustomWorker,
166 H.custom_worker,
167 "Worker",
168 )
171_RULE_TARGETS = {
172 RuleEnum.Scope.agent: "agent",
173 RuleEnum.Scope.skill: "skill",
174 RuleEnum.Scope.worker: "worker",
175}
178@register
179class RuleMove(Movable):
180 kind, model, history_type, label = "rule", m.Rule, H.rule, "Rule"
182 def dependencies(self, db, row):
183 # A rule pinned to one agent only fires when that agent is invoked,
184 # and an organisation's rule only on the organisation's work: the
185 # agent has to come too, or the rule would govern nothing.
186 target = _RULE_TARGETS.get(row.scope_type)
187 if target and row.scope_id:
188 return [Ref(target, row.scope_id)]
189 return []
192@register
193class DatasetMove(Movable):
194 kind, model, history_type, label = "dataset", m.TestSuite, H.test_suite, "Dataset"
197@register
198class ExperimentMove(Movable):
199 kind, model, history_type, label = (
200 "experiment",
201 m.Experiment,
202 H.experiment,
203 "Evaluation",
204 )
206 def dependencies(self, db, row):
207 from app.services.evaluation.evidence import agent_of
209 refs = [Ref("dataset", row.dataset_id)] if row.dataset_id else []
210 variants = db.query(m.ExperimentVariant).filter(
211 m.ExperimentVariant.experiment_id == row.id
212 )
213 agents = {agent_of(v) for v in variants.all()} - {None}
214 return refs + [Ref("agent", UUID(a)) for a in sorted(agents)]
217@register
218class DashboardMove(Movable):
219 kind, model, history_type, label = (
220 "dashboard",
221 m.Dashboard,
222 H.dashboard,
223 "Dashboard",
224 )
226 def dependencies(self, db, row):
227 from app.services.dashboards.widgets import get_renderer
229 refs: list[Ref] = []
230 widgets = db.query(m.DashboardWidget).filter(
231 m.DashboardWidget.dashboard_id == row.id
232 )
233 for widget in widgets.all():
234 try:
235 declared = get_renderer(widget.widget_type).references(
236 widget.config or {}
237 )
238 except Exception: # noqa: BLE001 — an unknown tile type names nothing
239 continue
240 for ref in declared:
241 try:
242 refs.append(Ref(ref.kind, UUID(str(ref.id))))
243 except ValueError:
244 continue
245 return refs
247 def prepare(self, row):
248 # Home is one board per owner; a moved board is not the
249 # organisation's home.
250 row.is_home = False
253# ── Planning ────────────────────────────────────────────────────────────────
256@dataclass(frozen=True)
257class Destination:
258 organisation_id: UUID | None = None
259 project_id: UUID | None = None
261 def owner(self) -> dict[str, Any]:
262 return {
263 "owner_user_id": None,
264 "owner_organisation_id": self.organisation_id,
265 "owner_project_id": self.project_id,
266 }
268 def owns(self, row: Any) -> bool:
269 if self.organisation_id is not None:
270 return getattr(row, "owner_organisation_id", None) == self.organisation_id
271 return getattr(row, "owner_project_id", None) == self.project_id
274@dataclass
275class Item:
276 kind: str
277 id: UUID
278 name: str
279 reason: str | None = None
281 def as_json(self) -> dict[str, Any]:
282 return {
283 "kind": self.kind,
284 "label": MOVABLE[self.kind].label if self.kind in MOVABLE else self.kind,
285 "id": str(self.id),
286 "name": self.name,
287 **({"reason": self.reason} if self.reason else {}),
288 }
291@dataclass
292class Plan:
293 moves: list[Item] = field(default_factory=list)
294 already_there: list[Item] = field(default_factory=list)
295 blockers: list[Item] = field(default_factory=list)
296 _rows: dict[tuple[str, UUID], Any] = field(default_factory=dict, repr=False)
298 def as_json(self) -> dict[str, Any]:
299 return {
300 "moves": [i.as_json() for i in self.moves],
301 "already_there": [i.as_json() for i in self.already_there],
302 "blockers": [i.as_json() for i in self.blockers],
303 }
306def _destination(body: dict) -> Destination:
307 organisation_id = body.get("organisation_id")
308 project_id = body.get("project_id")
309 if (organisation_id is None) == (project_id is None):
310 raise HTTPException(
311 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
312 detail="Name exactly one destination: an organisation or a project.",
313 )
314 return Destination(
315 UUID(str(organisation_id)) if organisation_id else None,
316 UUID(str(project_id)) if project_id else None,
317 )
320def plan(
321 db: Session, user: m.User, kind: str, resource_id: UUID, dest: Destination
322) -> Plan:
323 """What moving ``kind``/``resource_id`` to ``dest`` would do, without
324 doing it. 404 for a resource the user cannot see, 403 for one that is not
325 theirs to move or a destination they do not belong to."""
326 if kind not in MOVABLE:
327 raise HTTPException(
328 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
329 detail=f"{kind!r} cannot be moved.",
330 )
331 if dest.organisation_id is not None:
332 verify_list_scope(dest.organisation_id, "organisation", user, db)
333 else:
334 verify_list_scope(dest.project_id, "project", user, db)
335 root = db.get(MOVABLE[kind].model, resource_id)
336 if root is None:
337 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found.")
338 if dest.owns(root):
339 raise HTTPException(
340 status_code=status.HTTP_409_CONFLICT, detail="It already belongs there."
341 )
342 if getattr(root, "owner_user_id", None) != user.id:
343 raise HTTPException(
344 status_code=status.HTTP_403_FORBIDDEN,
345 detail="Only its owner can move personal work into an organisation or project.",
346 )
348 result = Plan()
349 seen: set[tuple[str, UUID]] = set()
350 queue: list[Ref] = [Ref(kind, resource_id)]
351 while queue:
352 ref = queue.pop(0)
353 key = (ref.kind, ref.id)
354 if key in seen or ref.kind not in MOVABLE:
355 continue
356 seen.add(key)
357 movable = MOVABLE[ref.kind]
358 row = root if key == (kind, resource_id) else db.get(movable.model, ref.id)
359 if row is None:
360 continue
361 item = Item(ref.kind, ref.id, movable.name(row))
362 if getattr(row, "is_system", False) is True or dest.owns(row):
363 result.already_there.append(item)
364 continue
365 if getattr(row, "owner_user_id", None) != user.id:
366 item.reason = "Owned by someone else, so only they can move it."
367 result.blockers.append(item)
368 continue
369 if ref.kind == "rule" and _blocks_rule_scope(row, dest):
370 item.reason = "It governs a different organisation or project."
371 result.blockers.append(item)
372 continue
373 try:
374 # Moving it in is creating it there: the caller's level in its
375 # area has to allow that (an editor's, for a rule).
376 verify_owner_scope(dest.owner(), user, db, model=movable.model)
377 except HTTPException as exc:
378 item.reason = str(exc.detail)
379 result.blockers.append(item)
380 continue
381 result.moves.append(item)
382 result._rows[key] = row
383 queue.extend(movable.dependencies(db, row))
384 return result
387def _blocks_rule_scope(rule: Any, dest: Destination) -> bool:
388 """A rule pinned to another organisation or project would govern nothing
389 once the destination owns it."""
390 pinned = {
391 RuleEnum.Scope.organisation: dest.organisation_id,
392 RuleEnum.Scope.project: dest.project_id,
393 }
394 return bool(
395 rule.scope_type in pinned
396 and rule.scope_id
397 and rule.scope_id != pinned[rule.scope_type]
398 )
401def move(
402 db: Session, user: m.User, kind: str, resource_id: UUID, dest: Destination
403) -> Plan:
404 """Carry out :func:`plan`. Refused (409, with the plan) while anything
405 blocks it. The caller commits."""
406 result = plan(db, user, kind, resource_id, dest)
407 if result.blockers:
408 raise HTTPException(
409 status_code=status.HTTP_409_CONFLICT,
410 detail={
411 "message": "Some of what this depends on can't be moved by you.",
412 **result.as_json(),
413 },
414 )
415 for item in result.moves:
416 movable = MOVABLE[item.kind]
417 row = result._rows[(item.kind, item.id)]
418 movable.prepare(row)
419 for column, value in dest.owner().items():
420 setattr(row, column, value)
421 # It no longer belongs to the parent its declarations named.
422 from app.services import inheritance
424 inheritance.forget(db, item.kind, row.id)
425 history.record_version(
426 db,
427 resource_type=movable.history_type,
428 model=movable.model,
429 resource=row,
430 action=HistoryEnum.Action.updated,
431 actor=user,
432 )
433 try:
434 db.flush()
435 except IntegrityError as exc:
436 db.rollback()
437 raise HTTPException(
438 status_code=status.HTTP_409_CONFLICT,
439 detail="Something with the same name already belongs there. Rename it first.",
440 ) from exc
441 return result
444def destination(body: dict) -> Destination:
445 """The destination a request names — exactly one of the two."""
446 return _destination(body)