Coverage for app / services / copying.py: 45%
97 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"""
2Copying a resource into a workspace, as an editable copy of its own.
4Inheritance (``app/services/inheritance.py``) lets a project *use* its
5parent's work by reference, read-only. A copy is the other thing a project
6wants: its parent's agent, rule, board or dataset as a starting point it
7owns and changes — "the organisation's support agent, tuned for this
8project". A copy is independent: the original changing never reaches it,
9and its ``cloned_from_id`` / ``cloned_from_version`` say what it started
10from (``ClonableMixin``).
12What a copy needs from the parent comes along **by reference**: a copied
13agent keeps its repository and skillset grants, and the project inherits
14each of those it didn't already (an instance declaration), so the copy can
15reach them — retrieving from one knowledge base is not a reason to duplicate
16it. A skillset's skills are copied with it, since a skill is not inherited
17on its own.
19Copies go from a project's parent into the project, or within one
20workspace (a duplicate). Each kind is one ``Copyable``.
21"""
23from __future__ import annotations
25from collections.abc import Callable
26from dataclasses import dataclass
27from typing import Any
28from uuid import uuid4
30from fastapi import HTTPException, status
31from sqlalchemy.orm import Session
33from app.db.postgres import models as m
34from app.db.postgres.enums import HistoryEnum
35from app.services import history, inheritance
36from app.services import workspace as workspace_service
38H = HistoryEnum.ResourceType
40#: Columns a copy never takes from its original.
41_NOT_COPIED = frozenset(
42 {
43 "id",
44 "owner_user_id",
45 "owner_organisation_id",
46 "owner_project_id",
47 "created_at",
48 "updated_at",
49 "is_system",
50 "is_ai_generated",
51 "generation_id",
52 "generated_by_agent_id",
53 "cloned_from_id",
54 "cloned_from_version",
55 "based_on_rule_id",
56 "based_on_version",
57 "is_home",
58 "required_for_projects",
59 }
60)
63def _columns(row: Any, *, exclude: frozenset[str] = frozenset()) -> dict[str, Any]:
64 return {
65 column.name: getattr(row, column.name)
66 for column in type(row).__table__.columns
67 if column.name not in _NOT_COPIED and column.name not in exclude
68 }
71@dataclass(frozen=True)
72class Copyable:
73 key: str
74 model: type
75 history_type: H
76 label: str
77 #: Copies the rows that come with it (tiles, cases, grants…) onto the
78 #: new row, already flushed. ``ws`` is where it is going.
79 children: Callable[[Session, Any, Any, Any, Any], None] | None = None
82def _agent_children(db: Session, original: Any, copy: Any, ws: Any, user: Any) -> None:
83 """Its grants, by reference — and the project inherits what it grants."""
84 for model, column, kind in (
85 (m.AgentRepository, "repository_id", "repository"),
86 (m.AgentSkillset, "skillset_id", "skillset"),
87 ):
88 for grant in db.query(model).filter(model.agent_id == original.id).all():
89 target_model = inheritance.INHERITABLE[kind].model
90 target = db.get(target_model, getattr(grant, column))
91 if target is None:
92 continue
93 _make_reachable(db, target, kind, ws, user)
94 db.add(
95 model(
96 agent_id=copy.id,
97 **{column: getattr(grant, column)},
98 config=getattr(grant, "config", None),
99 )
100 )
103def _make_reachable(db: Session, row: Any, kind: str, ws: Any, user: Any) -> None:
104 """Declare that project ``ws`` inherits ``row`` when it is the parent's
105 and not already reachable — the reference a copy's grant needs."""
106 if getattr(row, "is_system", False) is True or ws.owns_row(row):
107 return
108 if ws.parent is None or not ws.parent.owns_row(row):
109 return
110 if inheritance.visible(db, row, ws):
111 return
112 db.add(
113 m.WorkspaceInheritance(
114 id=uuid4(),
115 project_id=ws.id,
116 kind=kind,
117 resource_id=row.id,
118 declared_by_user_id=user.id,
119 )
120 )
123def _dashboard_children(
124 db: Session, original: Any, copy: Any, ws: Any, user: Any
125) -> None:
126 W = m.DashboardWidget
127 for tile in db.query(W).filter(W.dashboard_id == original.id).all():
128 db.add(
129 W(
130 **_columns(tile, exclude=frozenset({"dashboard_id"})),
131 dashboard_id=copy.id,
132 )
133 )
136def _dataset_children(
137 db: Session, original: Any, copy: Any, ws: Any, user: Any
138) -> None:
139 C = m.TestCase
140 for case in db.query(C).filter(C.test_suite_id == original.id).all():
141 db.add(
142 C(
143 **_columns(case, exclude=frozenset({"test_suite_id"})),
144 test_suite_id=copy.id,
145 )
146 )
149def _skillset_children(
150 db: Session, original: Any, copy: Any, ws: Any, user: Any
151) -> None:
152 """Its skills, copied too: a skill is not inherited on its own, so the
153 copy could not otherwise reach the parent's. Built-in skills are bundled
154 as they are."""
155 S = m.SkillsetSkill
156 for member in db.query(S).filter(S.skillset_id == original.id).all():
157 skill = db.get(m.Skill, member.skill_id)
158 if skill is None:
159 continue
160 if getattr(skill, "is_system", False) is True or ws.owns_row(skill):
161 target = skill
162 else:
163 target = _copy_row(db, COPYABLE["skill"], skill, ws, user)
164 db.add(S(skillset_id=copy.id, skill_id=target.id))
167COPYABLE: dict[str, Copyable] = {
168 entry.key: entry
169 for entry in (
170 Copyable("agent", m.Agent, H.agent, "agent", _agent_children),
171 Copyable("skill", m.Skill, H.skill, "skill"),
172 Copyable("skillset", m.Skillset, H.skillset, "skillset", _skillset_children),
173 Copyable("rule", m.Rule, H.rule, "rule"),
174 Copyable("dataset", m.TestSuite, H.test_suite, "dataset", _dataset_children),
175 Copyable(
176 "dashboard", m.Dashboard, H.dashboard, "dashboard", _dashboard_children
177 ),
178 )
179}
182def _free_name(db: Session, entry: Copyable, ws: Any, name: str) -> str:
183 """``name``, or ``name (copy)``, ``name (copy 2)``… — whichever ``ws``
184 doesn't have. Checked here: the owner/name unique constraints never fire
185 with their NULL owner columns."""
186 M = entry.model
187 taken = {
188 n for (n,) in db.query(M.name).filter(ws.owns(M), M.name.like(f"{name}%")).all()
189 }
190 if name not in taken:
191 return name
192 candidate, n = f"{name} (copy)", 2
193 while candidate in taken:
194 candidate, n = f"{name} (copy {n})", n + 1
195 return candidate
198def _copy_row(db: Session, entry: Copyable, original: Any, ws: Any, user: Any) -> Any:
199 from app.dependency.resource_access import verify_owner_scope
201 owner = ws.owner_columns()
202 verify_owner_scope(owner, user, db, model=entry.model)
203 values = _columns(original)
204 if "name" in values and values["name"]:
205 values["name"] = _free_name(db, entry, ws, values["name"])
206 copy = entry.model(
207 id=uuid4(),
208 **values,
209 **owner,
210 cloned_from_id=original.id,
211 cloned_from_version=history.current_version(
212 db, entry.history_type, original.id
213 ),
214 )
215 db.add(copy)
216 db.flush()
217 if entry.children is not None:
218 entry.children(db, original, copy, ws, user)
219 db.flush()
220 history.record_version(
221 db,
222 resource_type=entry.history_type,
223 model=entry.model,
224 resource=copy,
225 action=HistoryEnum.Action.created,
226 actor=user,
227 )
228 return copy
231def copy(db: Session, user: Any, kind: str, resource_id: Any, ws: Any) -> Any:
232 """Copy one resource into workspace ``ws`` and return the copy. The
233 caller commits.
235 The original must be readable by ``user`` and belong either to ``ws``
236 itself (a duplicate) or to ``ws``'s parent (copying down into a
237 project); ``user`` must be able to create one in ``ws``. A built-in is
238 not copied here — a built-in rule or dataset has its own way to start
239 from it."""
240 from app.dependency.resource_access import verify_resource_read
242 entry = COPYABLE.get(kind)
243 if entry is None:
244 raise HTTPException(
245 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
246 detail=f"{kind!r} can't be copied. Copyable: " + ", ".join(COPYABLE),
247 )
248 original = db.get(entry.model, resource_id)
249 if original is None:
250 raise HTTPException(
251 status_code=status.HTTP_404_NOT_FOUND,
252 detail=f"{entry.label.capitalize()} not found",
253 )
254 verify_resource_read(original, user, db)
255 home = workspace_service.home_of(db, original)
256 if home is None:
257 raise HTTPException(
258 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
259 detail="Built-in resources aren't copied this way.",
260 )
261 if home.key != ws.key and (ws.parent is None or ws.parent.key != home.key):
262 raise HTTPException(
263 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
264 detail="Copies go into the same workspace, or from a project's "
265 "parent into the project.",
266 )
267 return _copy_row(db, entry, original, ws, user)