feat: services/skills — widoczność, wersje i archiwizacja skilli (E2.3, 3.2)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tobayah
2026-11-06 00:47:26 +01:00
co-authored by Claude Opus 5.5
parent 7b402a10e0
commit 44b689943b
5 changed files with 388 additions and 3 deletions
+1 -1
View File
@@ -14,7 +14,7 @@
## Etap 3: serwis domenowy (E2.3-E2.4)
- [x] 3.1 W `backend/app/services/settings.py` dodaj do `SPECS` `skills_firm_publish` (CHOICE `approval`|`direct`, domyślnie `approval`) i `skills_firm_export` (CHOICE `administrator`|`everyone`, domyślnie `administrator`), z testem jednostkowym wartości domyślnych i odrzucenia spoza listy. Gotowe gdy: bramka zielona, test przechodzi.
- [ ] 3.2 Utwórz `backend/app/services/skills.py` (docstring opisujący świadome odstępstwo od „authz jedynym autorytetem”): `visible_to(db, user)` (właściciel ∪ `scope=firm`; cudze osobiste → `NotFoundError`), lista, odczyt, tworzenie skilla z wersją 1 i plikami, nowa wersja (zamrożenie, `n+1`, `content_sha256`), archiwizacja; każdy zapis przez `audit.record` (`skill.create`, `skill.version`, `skill.archive`). Testy jednostkowe na logice czystej (np. kolejny `n`, wybór akcji audytu, odmowa dla cudzego osobistego) bez bazy tam, gdzie to możliwe. Gotowe gdy: bramka zielona, w routerach brak nowego SQL, funkcje istnieją z docstringami.
- [x] 3.2 Utwórz `backend/app/services/skills.py` (docstring opisujący świadome odstępstwo od „authz jedynym autorytetem”): `visible_to(db, user)` (właściciel ∪ `scope=firm`; cudze osobiste → `NotFoundError`), lista, odczyt, tworzenie skilla z wersją 1 i plikami, nowa wersja (zamrożenie, `n+1`, `content_sha256`), archiwizacja; każdy zapis przez `audit.record` (`skill.create`, `skill.version`, `skill.archive`). Testy jednostkowe na logice czystej (np. kolejny `n`, wybór akcji audytu, odmowa dla cudzego osobistego) bez bazy tam, gdzie to możliwe. Gotowe gdy: bramka zielona, w routerach brak nowego SQL, funkcje istnieją z docstringami.
- [ ] 3.3 W `services/skills.py` dodaj publikację: przy `approval` → `publish_request` na konkretną wersję, `current_version_id` skilla firmowego rusza dopiero po zgodzie (także dla każdej kolejnej wersji), przy `direct` → od razu; `approve`/`decline` dla administratora; lista oczekujących dla administratora (tylko tu administrator widzi cudze osobiste). Audyt `skill.publish_request`/`skill.publish_approve`/`skill.publish_decline`. Gotowe gdy: bramka zielona i funkcje są wołane z jednego miejsca rozstrzygającego ustawienie `skills_firm_publish`.
- [ ] 3.4 W `services/skills.py` dodaj import (przez `skill_pack.read_pack`; kopia osobista, `origin=imported`, `provenance`, wersja 1, kolizja sluga → `-2`, ta sama suma → odpowiedź „już masz, dodać jako wersję?” bez zapisu, lista rzeczy zapisanych tylko jako informacja) i eksport (`build_pack`; własne zawsze, firmowe wg `skills_firm_export`). Audyt `skill.import`/`skill.export` z sumą paczki, bez treści. Gotowe gdy: bramka zielona, test jednostkowy funkcji wyboru sluga (`x`, `x-2`, `x-3`) przechodzi.
- [ ] 3.5 W `services/skills.py` dodaj agentów: tworzenie, nowa wersja z listą `skill_version_id` (tylko wersje widoczne dla osoby; agent firmowy tylko wersje skilli firmowych — inaczej `ValidationError`), archiwizacja, publikacja (ta sama ścieżka T1 co skille), eksport agenta z przypiętymi skillami (T2 obejmuje też firmowe skille w paczce), import paczki agenta. Audyt `agent.*` analogicznie do `skill.*`. Gotowe gdy: bramka zielona i reguła „agent firmowy tylko ze skillami firmowymi” jest w jednej funkcji z testem jednostkowym.
+2
View File
@@ -15,3 +15,5 @@
- 2.4: `content_sha256(SkillContent)` (kanoniczny SKILL.md: safe_dump sort_keys + NFC + LF, potem `ścieżka\0sha256`), `skill_content(pack, skill)` (pliki z folderu SKILL.md, ścieżki względne), `build_pack(skills, agent=None)` z `atrium-pack.json` (format 1, type, files+sha256), `Pack.agent` z głównego `agent.md`, `Pack.kind`. Manifest weryfikowany w obie strony (plik zmieniony/dodany/brakujący = `pack_manifest_mismatch`) i wycinany z `files`; paczka bez manifestu przechodzi.
- Dla 3.x: `SkillContent` budujesz z wersji w bazie (frontmatter = name/description/license/metadata itd.); agent.md nie ma reguły kebab/długości — tylko wspólne reguły nagłówka (komunikaty `skill_*` mówią teraz „SKILL.md albo agent.md").
- 3.1: `skills_firm_publish` (approval|direct) i `skills_firm_export` (administrator|everyone) w `SPECS`; test w `TestSettings` (test_marketplace_unit.py). Etykiet w konsoli (`SETTING_LABELS` ok. app.js:2197) jeszcze brak — to 6.4.
- 3.2: `services/skills.py` — `can_see`/`can_edit` (Python) + `visible_to` (ta sama reguła w SQL), `readable_version_ids` (nie-edytor czyta tylko `current_version_id`), `checked()` = treść pakowana `build_pack` i czytana `read_pack` (te same reguły co import, suma z paczki), create/new_version/archive z audytem `skill.create|version|archive` (detail: slug vN sha). `skill_pack._bad_path` → `bad_path` (publiczne). 23 testy w `test_skills_unit.py`.
- Dla 3.3: `_add_version` przesuwa `current_version_id` TYLKO dla osobistego; firmowy rusza wyłącznie publikacja. `new_version`: None = przenieś z ostatniej wersji (pliki też), licencja importu nienadpisywalna. Ścieżki plików sprawdzane PRZED pakowaniem (zipfile na Windows zamienia `\`, `a//b` zmieniłoby nazwę); plik `SKILL.md` w `files` = `pack_duplicate_name`.
+2 -2
View File
@@ -189,7 +189,7 @@ def _is_zip64(data: bytes, infos: list[zipfile.ZipInfo]) -> bool:
return False
def _bad_path(name: str) -> bool:
def bad_path(name: str) -> bool:
return (not name or "\\" in name or "\0" in name or name.startswith("/")
or (len(name) > 1 and name[1] == ":")
or any(part == ".." for part in name.split("/")))
@@ -212,7 +212,7 @@ def _open_archive(data: bytes) -> tuple[zipfile.ZipFile, list[zipfile.ZipInfo]]:
raise PackRejected("pack_too_many_files")
names = [i.orig_filename for i in infos]
bad = [n for n in names if _bad_path(n)]
bad = [n for n in names if bad_path(n)]
if bad:
raise PackRejected("pack_bad_path", bad)
links = [i.orig_filename for i in infos if stat.S_ISLNK(i.external_attr >> 16)]
+282
View File
@@ -0,0 +1,282 @@
"""Skills: a person's own instructions and reference files, versioned and frozen.
A deliberate exception to "`authz` is the only access authority"
-----------------------------------------------------------------
Skills (and agents) are not nodes of the org tree — the tree holds units only — so
`authz.assert_can_read` has nothing to say about them. Who may see one is decided HERE, in one
rule: **the owner, plus everybody for a `firm` one**. `visible_to` is that rule as SQL (lists) and
`can_see` the same rule on a loaded row (single reads); every read and write path goes through one
of them. Somebody else's personal skill is a 404, never a 403 — its existence is the owner's
business. An administrator gets no exception here: a personal skill is a lawyer's working notes,
and an administrator sees one only inside a publish request (the publication path, not this one).
Who may CHANGE one (`can_edit`): the owner, and for a firm skill also an administrator. Everybody
else makes a personal copy.
Versions are frozen
-------------------
Changing content is a new `skill_version` (`n + 1`), never an edit; the runtime role holds no
UPDATE or DELETE on the version tables (revision 0010). Every version is validated the way an
import is — it is packed with `skill_pack.build_pack` and read back with `skill_pack.read_pack` — so
a skill typed in the console and one uploaded as a ZIP obey the same rules and hash the same way.
`current_version_id` of a PERSONAL skill follows its newest version. A FIRM skill's is the approved
one, and only publication moves it — a new version of a firm skill stays invisible to everybody but
its editors until then.
"""
from __future__ import annotations
import hashlib
import uuid
from collections.abc import Mapping
from typing import Any
from sqlalchemy import or_, select
from sqlalchemy.orm import Session as DbSession
from ..enums import CatalogStatus, SkillOrigin, SkillScope
from ..errors import AuthorizationError, ConflictError, NotFoundError
from ..models import AppUser, Skill, SkillFile, SkillVersion
from . import audit, skill_pack
from .skill_pack import PackRejected, SkillContent
DEFAULT_LICENSE = "proprietary"
#: The frontmatter keys that have columns of their own; everything else is kept in `metadata`.
_OWN_KEYS = ("name", "description", "license")
MEDIA_TYPES = {
".md": "text/markdown", ".txt": "text/plain", ".csv": "text/csv",
".json": "application/json", ".yaml": "application/yaml", ".yml": "application/yaml",
".pdf": "application/pdf",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}
# ---- who may see and change ------------------------------------------------------------------
def can_see(user: AppUser, item) -> bool:
"""The visibility rule on a loaded skill (or agent: same columns)."""
return item.owner_id == user.id or item.scope == SkillScope.firm
def can_edit(user: AppUser, item) -> bool:
"""Owner, or an administrator for a firm one; everybody else makes a personal copy."""
return item.owner_id == user.id or (item.scope == SkillScope.firm and bool(user.is_admin))
def visible_to(db: DbSession, user: AppUser) -> list[Skill]:
"""Every skill `user` may see — `can_see` as SQL. Archived ones included: an agent may still pin
one, and the console says so."""
return list(db.scalars(
select(Skill).where(or_(Skill.owner_id == user.id, Skill.scope == SkillScope.firm))
.order_by(Skill.name, Skill.id)))
def _get(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
skill = db.get(Skill, skill_id)
if skill is None or not can_see(user, skill):
raise NotFoundError("Skill not found.")
return skill
def _get_editable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
skill = _get(db, user, skill_id)
if not can_edit(user, skill):
# A firm skill is visible, so refusing to change it reveals nothing.
raise AuthorizationError("Only the owner or an administrator may change a firm skill.")
return skill
def readable_version_ids(user: AppUser, skill: Skill, version_ids) -> set[uuid.UUID]:
"""An editor reads every version; anybody else only the current (for a firm skill: approved)."""
if can_edit(user, skill):
return set(version_ids)
return {skill.current_version_id} & set(version_ids)
# ---- content -----------------------------------------------------------------------------------
def next_n(latest: int | None) -> int:
"""The number of the next version; the (skill_id, n) constraint settles a race."""
return (latest or 0) + 1
def frontmatter(slug: str, description: str, license: str, meta: Mapping) -> dict:
"""The SKILL.md frontmatter a version stands for: its own columns win over `metadata`."""
head = {k: v for k, v in meta.items() if k not in _OWN_KEYS}
head.update(name=slug, description=description, license=license)
return head
def version_content(skill: Skill, version: SkillVersion, files) -> SkillContent:
"""A stored version as `content_sha256` and `build_pack` see it (export reads it the same way)."""
return SkillContent(folder=skill.slug,
frontmatter=frontmatter(skill.slug, version.description, version.license,
version.meta),
body=version.body_md, files={f.path: f.content for f in files})
def checked(slug: str, description: str, body: str, license: str, meta: Mapping,
files: Mapping[str, bytes]) -> tuple[skill_pack.SkillDoc, SkillContent, str]:
"""Pack the content and read it back: every import rule applies, `PackRejected` otherwise.
-> (the parsed SKILL.md, the content as it will be stored, its `content_sha256`)."""
# Checked before packing: zipfile rewrites `\` to `/` on Windows, and an empty segment (`a//b`,
# `/a`) would be stored under another name than the one it was given.
bad = [p for p in files if skill_pack.bad_path(p) or "" in p.split("/")]
if bad:
raise PackRejected("pack_bad_path", bad)
if "SKILL.md" in files: # build_pack would let it overwrite the document written from the fields
raise PackRejected("pack_duplicate_name", ["SKILL.md"])
content = SkillContent(folder=slug, frontmatter=frontmatter(slug, description, license, meta),
body=body, files=dict(files))
pack = skill_pack.read_pack(skill_pack.build_pack([content]))
doc = pack.skills[0]
stored = skill_pack.skill_content(pack, doc)
return doc, stored, skill_pack.content_sha256(stored)
def _media_type(path: str) -> str:
name = path.rsplit("/", 1)[-1]
return MEDIA_TYPES[name[name.rfind("."):].lower()] # read_pack has already refused the rest
def _add_version(db: DbSession, actor: AppUser, skill: Skill, n: int, *, description: str,
body: str, license: str, meta: Mapping, files: Mapping[str, bytes],
provenance: dict | None = None) -> SkillVersion:
doc, stored, sha = checked(skill.slug, description, body, license, meta, files)
version = SkillVersion(
skill_id=skill.id, n=n, description=doc.description, body_md=doc.body,
license=doc.frontmatter["license"],
meta={k: v for k, v in doc.frontmatter.items() if k not in _OWN_KEYS},
content_sha256=sha, provenance=provenance, created_by=actor.id)
db.add(version)
db.flush()
for path, data in sorted(stored.files.items()):
db.add(SkillFile(skill_version_id=version.id, path=path, media_type=_media_type(path),
size=len(data), sha256=hashlib.sha256(data).hexdigest(), content=data))
if skill.scope == SkillScope.personal:
skill.current_version_id = version.id
# ponytail: a firm skill's current version moves only through publication (services 3.3).
db.flush()
return version
def _audit(db: DbSession, actor: AppUser, action: str, skill: Skill,
version: SkillVersion | None = None, *, ip: str | None) -> None:
detail = skill.slug if version is None else f"{skill.slug} v{version.n} {version.content_sha256}"
audit.record(db, action=action, entity_type="skill", entity_id=skill.id, actor_id=actor.id,
detail=detail, ip=ip)
# ---- output ------------------------------------------------------------------------------------
def _files(db: DbSession, version_id: uuid.UUID) -> list[SkillFile]:
return list(db.scalars(select(SkillFile).where(SkillFile.skill_version_id == version_id)
.order_by(SkillFile.path)))
def skill_out(user: AppUser, skill: Skill) -> dict[str, Any]:
"""The identity row as the API shows it, with what this person may do to it."""
return {"id": skill.id, "slug": skill.slug, "name": skill.name, "owner_id": skill.owner_id,
"scope": skill.scope, "status": skill.status, "origin": skill.origin,
"current_version_id": skill.current_version_id, "mine": skill.owner_id == user.id,
"editable": can_edit(user, skill)}
def version_out(version: SkillVersion, files: list[SkillFile]) -> dict[str, Any]:
"""One version in full, files listed without their bytes (export carries those)."""
return {"id": version.id, "n": version.n, "description": version.description,
"body": version.body_md, "license": version.license, "metadata": version.meta,
"content_sha256": version.content_sha256, "provenance": version.provenance,
"created_at": version.created_at, "created_by": version.created_by,
"files": [{"path": f.path, "media_type": f.media_type, "size": f.size,
"sha256": f.sha256} for f in files]}
# ---- reads -------------------------------------------------------------------------------------
def list_skills(db: DbSession, user: AppUser) -> list[dict]:
"""Own skills and firm ones; the console splits them into Mine / The firm's."""
return [skill_out(user, s) for s in visible_to(db, user)]
def get_skill(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> dict:
"""The skill, the versions this person may read (newest first) and the current one in full."""
skill = _get(db, user, skill_id)
versions = list(db.scalars(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
.order_by(SkillVersion.n.desc())))
readable = readable_version_ids(user, skill, (v.id for v in versions))
current = next((v for v in versions if v.id == skill.current_version_id), None)
return {**skill_out(user, skill),
"versions": [{"n": v.n, "id": v.id, "created_at": v.created_at,
"content_sha256": v.content_sha256}
for v in versions if v.id in readable],
"current": (version_out(current, _files(db, current.id))
if current is not None and current.id in readable else None)}
def get_version(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int) -> dict:
"""Version `n`, if this person may read it — an unapproved firm version is a 404 to others."""
skill = _get(db, user, skill_id)
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
SkillVersion.n == n))
if version is None or not readable_version_ids(user, skill, [version.id]):
raise NotFoundError("Version not found.")
return version_out(version, _files(db, version.id))
# ---- writes ------------------------------------------------------------------------------------
def create_skill(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | None) -> dict:
"""A personal skill with its version 1. `fields`: slug, name, description, body, and optionally
license, metadata (extra frontmatter) and files (path -> bytes)."""
slug = fields["slug"]
if db.scalar(select(Skill.id).where(Skill.owner_id == actor.id, Skill.slug == slug)):
raise ConflictError(f"You already have a skill called {slug}.")
skill = Skill(slug=slug, name=fields["name"], owner_id=actor.id, scope=SkillScope.personal,
status=CatalogStatus.active, origin=SkillOrigin.authored)
db.add(skill)
db.flush()
version = _add_version(db, actor, skill, 1, description=fields["description"],
body=fields["body"], license=fields.get("license") or DEFAULT_LICENSE,
meta=fields.get("metadata") or {}, files=fields.get("files") or {})
_audit(db, actor, "skill.create", skill, version, ip=ip)
return skill_out(actor, skill)
def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapping, *,
ip: str | None) -> dict:
"""Version `n + 1`. A field that is None is carried over from the newest version (`files`
included — `{}` is how to remove them all). An imported licence is the author's: it stays."""
skill = _get_editable(db, actor, skill_id)
if skill.status == CatalogStatus.archived:
raise ConflictError("An archived skill takes no new versions.")
latest = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
.order_by(SkillVersion.n.desc()).limit(1))
license = fields.get("license") or latest.license
if skill.origin == SkillOrigin.imported:
license = latest.license
files = fields.get("files")
if files is None:
files = {f.path: f.content for f in _files(db, latest.id)}
if fields.get("name"):
skill.name = fields["name"]
version = _add_version(
db, actor, skill, next_n(latest.n),
description=fields.get("description") or latest.description,
body=fields["body"] if fields.get("body") is not None else latest.body_md,
license=license,
meta=fields["metadata"] if fields.get("metadata") is not None else latest.meta,
files=files)
_audit(db, actor, "skill.version", skill, version, ip=ip)
return version_out(version, _files(db, version.id))
def archive_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, *, ip: str | None) -> dict:
"""Archived, not deleted: agents keep running on the versions they pinned (FK RESTRICT)."""
skill = _get_editable(db, actor, skill_id)
if skill.status != CatalogStatus.archived:
skill.status = CatalogStatus.archived
db.flush()
_audit(db, actor, "skill.archive", skill, ip=ip)
return skill_out(actor, skill)
+101
View File
@@ -0,0 +1,101 @@
"""`services/skills.py`: the visibility rule, version numbering and content checks (DB-free)."""
from __future__ import annotations
import uuid
from types import SimpleNamespace
import pytest
from app.errors import AuthorizationError, NotFoundError
from app.models import Skill
from app.services import skill_pack, skills
from app.services.skill_pack import PackRejected
OWNER, OTHER, ADMIN = (SimpleNamespace(id=uuid.uuid4(), is_admin=a) for a in (False, False, True))
def _skill(scope: str, current=None) -> Skill:
return Skill(id=uuid.uuid4(), slug="nda", name="NDA", owner_id=OWNER.id, scope=scope,
status="active", origin="authored", current_version_id=current)
class _Db:
def __init__(self, skill):
self.skill = skill
def get(self, _model, _id):
return self.skill
@pytest.mark.parametrize("user, scope, sees, edits", [
(OWNER, "personal", True, True),
(OTHER, "personal", False, False),
(ADMIN, "personal", False, False), # an administrator gets no look at working notes
(OWNER, "firm", True, True),
(OTHER, "firm", True, False),
(ADMIN, "firm", True, True),
])
def test_visibility_matrix(user, scope, sees, edits):
skill = _skill(scope)
assert skills.can_see(user, skill) is sees
assert skills.can_edit(user, skill) is edits
def test_someone_elses_personal_skill_is_a_404_not_a_403():
db = _Db(_skill("personal"))
for user in (OTHER, ADMIN):
with pytest.raises(NotFoundError):
skills.get_skill(db, user, db.skill.id)
with pytest.raises(NotFoundError):
skills.archive_skill(db, user, db.skill.id, ip=None)
def test_a_firm_skill_is_changed_only_by_its_editors():
db = _Db(_skill("firm"))
with pytest.raises(AuthorizationError):
skills.new_version(db, OTHER, db.skill.id, {}, ip=None)
def test_a_non_editor_reads_only_the_current_version():
approved, pending = uuid.uuid4(), uuid.uuid4()
skill = _skill("firm", current=approved)
assert skills.readable_version_ids(OTHER, skill, [approved, pending]) == {approved}
assert skills.readable_version_ids(OWNER, skill, [approved, pending]) == {approved, pending}
def test_next_n():
assert skills.next_n(None) == 1
assert skills.next_n(4) == 5
def test_frontmatter_columns_win_over_metadata():
head = skills.frontmatter("nda", "Opis", "MIT", {"name": "x", "license": "y", "metadata": {"a": 1}})
assert head == {"name": "nda", "description": "Opis", "license": "MIT", "metadata": {"a": 1}}
def test_checked_hashes_what_an_export_would_carry():
files = {"resources/notes.md": b"# Notatki\n"}
doc, stored, sha = skills.checked("nda", "Przegląd NDA", "Treść\r\n", "proprietary", {}, files)
assert stored.files == files and doc.body == "Treść\n"
assert sha == skill_pack.content_sha256(stored)
pack = skill_pack.read_pack(skill_pack.build_pack([stored]))
assert skill_pack.content_sha256(skill_pack.skill_content(pack, pack.skills[0])) == sha
@pytest.mark.parametrize("slug, files, code", [
("Not Kebab", {}, "skill_bad_name"),
("nda", {"run.sh": b"echo"}, "pack_file_type"),
("nda", {"../escape.md": b"x"}, "pack_bad_path"),
("nda", {"a\\b.md": b"x"}, "pack_bad_path"),
("nda", {"/abs.md": b"x"}, "pack_bad_path"),
("nda", {"a//b.md": b"x"}, "pack_bad_path"),
("nda", {"SKILL.md": b"---\nname: nda\ndescription: x\n---\n"}, "pack_duplicate_name"),
])
def test_checked_applies_the_import_rules(slug, files, code):
with pytest.raises(PackRejected) as caught:
skills.checked(slug, "Opis", "Treść", "proprietary", {}, files)
assert caught.value.code == code
def test_every_allowed_extension_has_a_media_type():
assert set(skills.MEDIA_TYPES) == skill_pack.ALLOWED_TYPES