Coverage for app / services / workspace.py: 78%
217 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"""
2Workspaces: where a resource lives, and where work happens.
4Every ownable resource belongs to exactly one owner (``OwnableMixin``): a
5user, an organisation or a project. Seen from the product, each owner is a
6**workspace** with its own agents, knowledge, rules, evaluations and
7dashboards, and every page shows exactly one of them.
9================= ==================================== ===================
10Workspace Owner columns Parent
11================= ==================================== ===================
12Personal ``owner_user_id`` none
13Organisation ``owner_organisation_id`` none
14Personal project ``owner_project_id`` → user-owned the owner's personal
15Org project ``owner_project_id`` → org-owned its organisation
16================= ==================================== ===================
18Projects are one level deep: a project is owned by a user or an
19organisation, never by another project (``ck_projects_not_nested``).
21A workspace's **key** names it in requests and responses —
22``user:<id>``, ``organisation:<id>`` or ``project:<id>``; a request may
23also say ``personal`` for the caller's own. ``resolve`` turns a key into a
24``Workspace`` the caller belongs to (404 for a missing one, 403 for one
25they don't), and ``in_scope`` is the filter a list applies to show what is
26in it.
27"""
29from __future__ import annotations
31from dataclasses import dataclass
32from enum import StrEnum
33from typing import Any
34from uuid import UUID
36from fastapi import HTTPException, status
37from sqlalchemy import or_
38from sqlalchemy.orm import Session
40from app.db.postgres.models import (
41 Organisation,
42 Project,
43 Role,
44 User,
45 UserOrganisation,
46 UserProject,
47)
50class WorkspaceKind(StrEnum):
51 personal = "personal"
52 organisation = "organisation"
53 project = "project"
56#: The owner column each kind of workspace fills.
57OWNER_COLUMN: dict[WorkspaceKind, str] = {
58 WorkspaceKind.personal: "owner_user_id",
59 WorkspaceKind.organisation: "owner_organisation_id",
60 WorkspaceKind.project: "owner_project_id",
61}
63#: How a key spells each kind. A personal workspace is a user's.
64_KEY_PREFIX: dict[WorkspaceKind, str] = {
65 WorkspaceKind.personal: "user",
66 WorkspaceKind.organisation: "organisation",
67 WorkspaceKind.project: "project",
68}
69_KIND_OF_PREFIX = {prefix: kind for kind, prefix in _KEY_PREFIX.items()}
71#: What a request may say for the caller's own workspace.
72PERSONAL = "personal"
75@dataclass(frozen=True)
76class Workspace:
77 kind: WorkspaceKind
78 #: The user's id for a personal workspace; otherwise the organisation's
79 #: or project's.
80 id: UUID
81 name: str | None = None
82 #: A project's owner: the personal workspace or organisation it sits in.
83 parent: Workspace | None = None
85 @property
86 def key(self) -> str:
87 return f"{_KEY_PREFIX[self.kind]}:{self.id}"
89 @property
90 def owner_column(self) -> str:
91 return OWNER_COLUMN[self.kind]
93 def owner_columns(self) -> dict[str, UUID | None]:
94 """The owner columns of something created here."""
95 return {
96 column: (self.id if kind is self.kind else None)
97 for kind, column in OWNER_COLUMN.items()
98 }
100 def owns(self, model: Any):
101 """SQL: ``model``'s rows that this workspace owns."""
102 return getattr(model, self.owner_column) == self.id
104 def owns_row(self, row: Any) -> bool:
105 return getattr(row, self.owner_column, None) == self.id
107 def filed_under(self, model: Any):
108 """SQL on a record that names its owner in all three columns at once
109 (a review flag, a background event — the invoker or subject *and*
110 the workspace): its rows filed under this workspace. A personal one
111 is the person's with no organisation or project beside it."""
112 from sqlalchemy import and_
114 if self.kind is WorkspaceKind.personal:
115 return and_(
116 model.owner_user_id == self.id,
117 model.owner_organisation_id.is_(None),
118 model.owner_project_id.is_(None),
119 )
120 return self.owns(model)
122 def made_here(self, model: Any):
123 """SQL on a record of something a person did in a workspace and
124 keeps as their own (a conversation, a skill run, a generation run),
125 stamped ``workspace_organisation_id`` / ``workspace_project_id``:
126 its rows done here. A project's row may name its organisation too,
127 so the organisation's are those with no project; Personal's name
128 neither. The caller narrows to the person."""
129 from sqlalchemy import and_
131 if self.kind is WorkspaceKind.project:
132 return model.workspace_project_id == self.id
133 if self.kind is WorkspaceKind.organisation:
134 return and_(
135 model.workspace_organisation_id == self.id,
136 model.workspace_project_id.is_(None),
137 )
138 return and_(
139 model.workspace_organisation_id.is_(None),
140 model.workspace_project_id.is_(None),
141 )
143 # -- governing an invocation here ------------------------------------
145 def refs(self) -> list:
146 """The rule-scope references work here carries: a project and its
147 organisation, or an organisation. So a rule scoped to the
148 organisation governs its projects' invocations too."""
149 from app.db.postgres.enums import RuleEnum
150 from app.services.rules.scopes import ScopeRef
152 if self.kind is WorkspaceKind.organisation:
153 return [ScopeRef(RuleEnum.Scope.organisation, self.id)]
154 if self.kind is WorkspaceKind.project:
155 refs = [ScopeRef(RuleEnum.Scope.project, self.id)]
156 if (
157 self.parent is not None
158 and self.parent.kind is WorkspaceKind.organisation
159 ):
160 refs.append(ScopeRef(RuleEnum.Scope.organisation, self.parent.id))
161 return refs
162 return []
164 def ledger_stamp(self) -> dict[str, UUID | None]:
165 """The workspace columns a ledger, activity or review row carries for
166 work done here. A project's row names its organisation too, and a
167 personal project's its owner, so the parent's quotas count it."""
168 parent = self.parent
169 if self.kind is WorkspaceKind.personal:
170 return {
171 "owner_project_id": None,
172 "owner_organisation_id": None,
173 "workspace_user_id": self.id,
174 }
175 if self.kind is WorkspaceKind.organisation:
176 return {
177 "owner_project_id": None,
178 "owner_organisation_id": self.id,
179 "workspace_user_id": None,
180 }
181 return {
182 "owner_project_id": self.id,
183 "owner_organisation_id": parent.id
184 if parent is not None and parent.kind is WorkspaceKind.organisation
185 else None,
186 "workspace_user_id": parent.id
187 if parent is not None and parent.kind is WorkspaceKind.personal
188 else None,
189 }
191 def stamped(self, model: Any, *, projects: bool = True):
192 """SQL on a stamped table (the usage ledger, the activity log): its
193 rows for work done here — and, with ``projects``, in this
194 workspace's projects, which is what a parent's quota counts."""
195 from sqlalchemy import and_
197 if self.kind is WorkspaceKind.project:
198 return model.owner_project_id == self.id
199 column = (
200 model.workspace_user_id
201 if self.kind is WorkspaceKind.personal
202 else model.owner_organisation_id
203 )
204 if projects:
205 return column == self.id
206 return and_(column == self.id, model.owner_project_id.is_(None))
209def _bad_key(key: str) -> HTTPException:
210 return HTTPException(
211 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
212 detail=f"Not a workspace: {key!r}. Use personal, organisation:<id> "
213 "or project:<id>.",
214 )
217def parse_key(key: str) -> tuple[WorkspaceKind, UUID | None]:
218 """``(kind, id)`` from a key; the id is None for ``personal``."""
219 if key == PERSONAL:
220 return WorkspaceKind.personal, None
221 prefix, _, raw = key.partition(":")
222 kind = _KIND_OF_PREFIX.get(prefix)
223 if kind is None:
224 raise _bad_key(key)
225 try:
226 return kind, UUID(raw)
227 except ValueError:
228 raise _bad_key(key) from None
231def _not_found(kind: WorkspaceKind) -> HTTPException:
232 return HTTPException(
233 status_code=status.HTTP_404_NOT_FOUND,
234 detail=f"{kind.value.capitalize()} not found",
235 )
238def _project_workspace(db: Session, project: Project) -> Workspace:
239 return Workspace(
240 WorkspaceKind.project,
241 project.id,
242 name=project.name,
243 parent=home_of(db, project, named=True),
244 )
247def resolve(db: Session, key: str, user: User) -> Workspace:
248 """The workspace ``key`` names, which ``user`` must belong to: their own
249 personal one, an organisation they are a member of, or a project they
250 are a member or an admin by position of."""
251 from app.dependency.resource_access import verify_list_scope
253 kind, id = parse_key(key)
254 if kind is WorkspaceKind.personal:
255 if id is not None and id != user.id and not user.is_superuser:
256 raise HTTPException(
257 status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden"
258 )
259 return Workspace(kind, id or user.id, name="Personal")
260 if kind is WorkspaceKind.organisation:
261 organisation = db.get(Organisation, id)
262 if organisation is None:
263 raise _not_found(kind)
264 verify_list_scope(id, "organisation", user, db)
265 return Workspace(kind, id, name=organisation.name)
266 project = db.get(Project, id)
267 if project is None:
268 raise _not_found(kind)
269 verify_list_scope(id, "project", user, db)
270 return _project_workspace(db, project)
273def from_key(db: Session, key: str) -> Workspace:
274 """The workspace a key names, without checking who may open it — for a
275 key a request already resolved (``resolve``) and handed on, as a rule
276 evaluation context does. A personal key must carry its id."""
277 kind, id = parse_key(key)
278 if id is None:
279 raise _bad_key(key)
280 if kind is WorkspaceKind.project:
281 project = db.get(Project, id)
282 if project is None:
283 raise _not_found(kind)
284 return Workspace(kind, id, name=project.name, parent=home_of(db, project))
285 return Workspace(kind, id)
288def from_chain(db: Session, links: Any, invoker_id: Any) -> Workspace:
289 """The workspace an invocation that didn't name one happens in: the
290 project its chain of governed resources reaches, else the organisation,
291 else the invoker's own. That is where the resource lives, so the
292 resource's own workspace governs it — never the invoker's personal rules
293 following them into an organisation's agent."""
294 from app.db.postgres.enums import RuleEnum
296 by_kind = {}
297 for link in links or ():
298 if link.scope_id is not None:
299 by_kind.setdefault(link.scope_type, link.scope_id)
300 project_id = by_kind.get(RuleEnum.Scope.project)
301 if project_id is not None:
302 project = db.get(Project, project_id)
303 if isinstance(project, Project):
304 return Workspace(
305 WorkspaceKind.project, project.id, parent=home_of(db, project)
306 )
307 org_id = by_kind.get(RuleEnum.Scope.organisation)
308 if org_id is not None:
309 return Workspace(WorkspaceKind.organisation, org_id)
310 return Workspace(
311 WorkspaceKind.personal,
312 invoker_id if isinstance(invoker_id, UUID) else UUID(str(invoker_id)),
313 )
316def governing_rules(ws: Workspace):
317 """SQL: the rules that govern work in ``ws`` — its own, and for a
318 project the parent's it inherits: Required, pinned to it, or declared."""
319 from app.db.postgres.models import Rule
320 from app.services import inheritance
322 clauses = [ws.owns(Rule)]
323 if ws.parent is not None:
324 clauses.append(inheritance.inherited_clause(Rule, ws))
325 return or_(*clauses)
328def home_of(db: Session, row: Any, *, named: bool = False) -> Workspace | None:
329 """The workspace that owns ``row`` — None for a built-in, which belongs
330 to every workspace and none. ``named`` loads the owner's name."""
331 if getattr(row, "owner_user_id", None) is not None:
332 return Workspace(WorkspaceKind.personal, row.owner_user_id, name="Personal")
333 org_id = getattr(row, "owner_organisation_id", None)
334 if org_id is not None:
335 name = None
336 if named:
337 organisation = db.get(Organisation, org_id)
338 name = organisation.name if organisation is not None else None
339 return Workspace(WorkspaceKind.organisation, org_id, name=name)
340 project_id = getattr(row, "owner_project_id", None)
341 if project_id is not None:
342 project = db.get(Project, project_id)
343 if project is None:
344 return Workspace(WorkspaceKind.project, project_id)
345 return (
346 _project_workspace(db, project)
347 if named
348 else Workspace(
349 WorkspaceKind.project,
350 project_id,
351 name=project.name,
352 parent=home_of(db, project),
353 )
354 )
355 return None
358def made_in(
359 db: Session,
360 *,
361 organisation_id: Any = None,
362 project_id: Any = None,
363 user_id: Any = None,
364) -> Workspace | None:
365 """The workspace a record stamped ``workspace_organisation_id`` /
366 ``workspace_project_id`` was made in (a generation run, a skill run) —
367 the inverse of :meth:`Workspace.made_here`. Neither stamped: the
368 person's Personal, or None with no person either."""
369 if project_id is not None:
370 project = db.get(Project, project_id)
371 if isinstance(project, Project):
372 return Workspace(
373 WorkspaceKind.project,
374 project.id,
375 name=project.name,
376 parent=home_of(db, project),
377 )
378 return Workspace(WorkspaceKind.project, project_id)
379 if organisation_id is not None:
380 return Workspace(WorkspaceKind.organisation, organisation_id)
381 if user_id is not None:
382 return Workspace(WorkspaceKind.personal, user_id, name="Personal")
383 return None
386def in_scope(model: Any, ws: Workspace, *, inherited: bool = True, system: bool = True):
387 """SQL: what a list in ``ws`` shows of ``model`` — the rows the
388 workspace owns; for a project, what it inherits from its parent
389 (``app/services/inheritance.py``); and (``system``) the platform's
390 built-ins, which belong to every workspace."""
391 from app.services import inheritance
393 clauses = [ws.owns(model)]
394 if inherited and ws.parent is not None:
395 clauses.append(inheritance.inherited_clause(model, ws))
396 if system and hasattr(model, "is_system"):
397 clauses.append(model.is_system.is_(True))
398 return or_(*clauses)
401# ── The caller's workspaces ─────────────────────────────────────────────────
404@dataclass(frozen=True)
405class Entry:
406 """One workspace the caller can open, for the switcher."""
408 workspace: Workspace
409 role: str | None
410 #: Their level per area there (``access.to_json``); every area editor
411 #: for an admin.
412 access: dict[str, str] | None
413 #: An admin by position (``membership.implicit_admin``), not by a row.
414 implicit: bool = False
417def workspaces_of(db: Session, user: User) -> list[Entry]:
418 """Every workspace ``user`` can open: their personal one and its
419 projects; each organisation they belong to and the projects of it they
420 are a member of — every one, for its admins."""
421 from app.services import access
422 from app.services.membership import MemberRole
424 admin = MemberRole.admin.value
425 personal = Workspace(WorkspaceKind.personal, user.id, name="Personal")
426 entries = [Entry(personal, admin, access.to_json(access.ADMIN_ACCESS))]
428 def _access(role: str, stored: Any) -> dict[str, str]:
429 return access.to_json(
430 access.ADMIN_ACCESS if role == admin else access.normalise(stored)
431 )
433 orgs = (
434 db.query(Organisation, Role.name, UserOrganisation.access)
435 .join(UserOrganisation, UserOrganisation.organisation_id == Organisation.id)
436 .join(Role, Role.id == UserOrganisation.role_id)
437 .filter(UserOrganisation.user_id == user.id)
438 .order_by(Organisation.name)
439 .all()
440 )
441 org_ws = {
442 o.id: Workspace(WorkspaceKind.organisation, o.id, name=o.name)
443 for o, _, _ in orgs
444 }
445 administered = {o.id for o, role, _ in orgs if role == admin}
447 joined = {
448 project_id: (role, stored)
449 for project_id, role, stored in (
450 db.query(UserProject.project_id, Role.name, UserProject.access)
451 .join(Role, Role.id == UserProject.role_id)
452 .filter(UserProject.user_id == user.id)
453 .all()
454 )
455 }
456 projects = (
457 db.query(Project)
458 .filter(
459 or_(
460 Project.id.in_(list(joined)) if joined else False,
461 Project.owner_user_id == user.id,
462 Project.owner_organisation_id.in_(list(administered))
463 if administered
464 else False,
465 )
466 )
467 .order_by(Project.name)
468 .all()
469 )
470 by_parent: dict[str, list[Entry]] = {}
471 for project in projects:
472 if project.owner_user_id == user.id:
473 parent, implicit = personal, project.id not in joined
474 elif project.owner_organisation_id in org_ws:
475 parent = org_ws[project.owner_organisation_id]
476 implicit = project.owner_organisation_id in administered and (
477 project.id not in joined or joined[project.id][0] != admin
478 )
479 elif project.owner_user_id is not None:
480 # Someone else's personal project, joined by invite.
481 owner = db.get(User, project.owner_user_id)
482 parent, implicit = (
483 Workspace(
484 WorkspaceKind.personal,
485 project.owner_user_id,
486 name=(owner.name or owner.email) if owner is not None else None,
487 ),
488 False,
489 )
490 else:
491 # An org project they joined but whose organisation they left —
492 # leaving removes project memberships, so only a stale row.
493 continue
494 role, stored = (admin, None) if implicit else joined[project.id]
495 ws = Workspace(
496 WorkspaceKind.project, project.id, name=project.name, parent=parent
497 )
498 by_parent.setdefault(parent.key, []).append(
499 Entry(ws, role, _access(role, stored), implicit)
500 )
502 entries += by_parent.pop(personal.key, [])
503 for o, role, stored in orgs:
504 ws = org_ws[o.id]
505 entries.append(Entry(ws, role, _access(role, stored)))
506 entries += by_parent.pop(ws.key, [])
507 # Other people's personal projects come last.
508 for rest in by_parent.values():
509 entries += rest
510 return entries