feat: services/skills — import i eksport skilli (E2.3, 3.4)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
e341da9924
commit
4a356b6d94
+1
-1
@@ -16,7 +16,7 @@
|
||||
- [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.
|
||||
- [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.
|
||||
- [x] 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.
|
||||
- [x] 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.
|
||||
|
||||
## Etap 4: API (E2.5)
|
||||
|
||||
@@ -19,3 +19,5 @@
|
||||
- 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`.
|
||||
- 3.3: publikacja w `services/skills.py` — `_publish` jedynym czytelnikiem `skills_firm_publish` (approval → `publish_request` na wersję, direct → `_make_current` od razu), `publish_skill(n=None → najnowsza)`, `decide_publish` (blokada wiersza, notatka = decyzja administratora), `pending_publish_requests` z `version` i `base` (aktualna wersja firmy) pod diff w 6.4. Administrator sprawdzany też w serwisie.
|
||||
- Decyzje bez specu (drobne): przy `direct` audyt `skill.publish_approve` z detalem „direct” (spec nie ma osobnej akcji); zatwierdzenie wersji starszej niż aktualna firmowa = 409. Dla 3.5: `_resolve` i `_request_out` obsługują na razie tylko `kind=skill` (agent → NotImplementedError).
|
||||
- 3.4: `import_skills(data, filename, add_version=False)` — każdy SKILL.md paczki = osobny skill osobisty (`origin=imported`, v1, `free_slug` x/x-2/x-3 ≤64), `provenance` {filename, path, pack_sha256, content_sha256 źródła}; duplikat = własny AKTYWNY skill z wersją o tej sumie (`content_sha256` albo `provenance->>content_sha256`, bo `name`=slug i domyślna licencja zmieniają sumę) → `status: duplicate` bez zapisu, `add_version=True` dokłada wersję. Zwraca `info_only` per skill i `ignored` (pliki spoza folderów skilli, np. commands/ wtyczki). Nowe kody `pack_no_skill`, `pack_is_agent` (agent → 3.5). `may_export` (T2, czysta, do reużycia przez agenta) + `export_skill(n=None → aktualna)` → (nazwa, ZIP). Audyt z sumą paczki.
|
||||
- Bramka: `tests/test_deploy_init_add.py` wiesza się lokalnie (skrypty powłoki) — pełny zestaw zielony bez niego; venv: `projects/lw-venv-skille`. Ruff na całym repo ma 127 starych błędów, nowe pliki czyste.
|
||||
|
||||
@@ -66,6 +66,9 @@ MESSAGES = {
|
||||
"The atrium-pack.json file is malformed."),
|
||||
"pack_manifest_mismatch": ("Pliki paczki nie zgadzają się z sumami w atrium-pack.json.",
|
||||
"The pack's files do not match the sums in atrium-pack.json."),
|
||||
"pack_no_skill": ("Paczka nie zawiera pliku SKILL.md.", "The pack contains no SKILL.md."),
|
||||
"pack_is_agent": ("To paczka agenta — zaimportuj ją jako agenta.",
|
||||
"This is an agent pack — import it as an agent."),
|
||||
"skill_not_utf8": ("SKILL.md albo agent.md nie jest zapisany w UTF-8.",
|
||||
"SKILL.md or agent.md is not UTF-8."),
|
||||
"skill_frontmatter_too_large": ("Nagłówek SKILL.md albo agent.md jest większy niż 8 KB.",
|
||||
|
||||
@@ -410,3 +410,117 @@ def pending_publish_requests(db: DbSession, actor: AppUser) -> list[dict]:
|
||||
rows = db.scalars(select(PublishRequest).where(
|
||||
PublishRequest.status == PublishRequestStatus.pending).order_by(PublishRequest.created_at))
|
||||
return [_request_out(db, r) for r in rows]
|
||||
|
||||
|
||||
# ---- import and export -------------------------------------------------------------------------
|
||||
|
||||
def free_slug(taken, slug: str) -> str:
|
||||
"""`slug`, or the first of `slug-2`, `slug-3`… nobody in `taken` has — trimmed to stay ≤ 64."""
|
||||
n, candidate = 1, slug
|
||||
while candidate in taken:
|
||||
n += 1
|
||||
suffix = f"-{n}"
|
||||
candidate = slug[: skill_pack.MAX_NAME - len(suffix)].rstrip("-") + suffix
|
||||
return candidate
|
||||
|
||||
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _already_have(db: DbSession, actor: AppUser, sha: str) -> SkillVersion | None:
|
||||
"""A version of one of `actor`'s active skills with this content — stored as it was imported
|
||||
(`provenance`), or exported from here and coming back (`content_sha256`)."""
|
||||
return db.scalar(
|
||||
select(SkillVersion).join(Skill, Skill.id == SkillVersion.skill_id)
|
||||
.where(Skill.owner_id == actor.id, Skill.status == CatalogStatus.active,
|
||||
or_(SkillVersion.content_sha256 == sha,
|
||||
SkillVersion.provenance["content_sha256"].astext == sha))
|
||||
.order_by(SkillVersion.created_at.desc()).limit(1))
|
||||
|
||||
|
||||
def import_skills(db: DbSession, actor: AppUser, data: bytes, filename: str | None = None, *,
|
||||
add_version: bool = False, ip: str | None) -> dict:
|
||||
"""Every SKILL.md of an uploaded pack becomes a personal copy of `actor`'s: `origin=imported`,
|
||||
version 1, a free slug (`x`, `x-2`…). Nothing updates itself: if `actor` already has one of
|
||||
them (same `content_sha256`), nothing is written and the answer is `duplicate` — call again
|
||||
with `add_version=True` to add those as a new version of the skill they match.
|
||||
|
||||
-> {"status": "imported" | "duplicate", "skills": [one per SKILL.md: path, its sum, the match
|
||||
or the skill written, and `info_only` — what it asked for and was not given (D3)], "ignored":
|
||||
files of the pack that belong to no skill (a plugin's commands/, agents/…)}"""
|
||||
pack = skill_pack.read_pack(data)
|
||||
if pack.agent is not None or pack.kind == "agent":
|
||||
raise PackRejected("pack_is_agent", [skill_pack.AGENT_DOC])
|
||||
if not pack.skills:
|
||||
raise PackRejected("pack_no_skill")
|
||||
pack_sha = _sha(data)
|
||||
found = []
|
||||
for doc in pack.skills:
|
||||
content = skill_pack.skill_content(pack, doc)
|
||||
found.append((doc, content, skill_pack.content_sha256(content)))
|
||||
matches = {sha: _already_have(db, actor, sha) for _, _, sha in found}
|
||||
used = {doc.path[: -len("SKILL.md")] for doc in pack.skills}
|
||||
ignored = sorted(p for p in pack.files
|
||||
if p != skill_pack.AGENT_DOC and not any(p.startswith(u) for u in used))
|
||||
if any(matches.values()) and not add_version:
|
||||
return {"status": "duplicate", "ignored": ignored, "skills": [
|
||||
{"path": doc.path, "content_sha256": sha, "info_only": doc.info_only,
|
||||
"match": ({**skill_out(actor, db.get(Skill, matches[sha].skill_id)),
|
||||
"n": matches[sha].n} if matches[sha] else None)}
|
||||
for doc, _, sha in found]}
|
||||
|
||||
taken = set(db.scalars(select(Skill.slug).where(Skill.owner_id == actor.id)))
|
||||
out = []
|
||||
for doc, content, sha in found:
|
||||
provenance = {"filename": filename, "path": doc.path, "pack_sha256": pack_sha,
|
||||
"content_sha256": sha}
|
||||
fields = dict(description=doc.description, body=doc.body,
|
||||
license=str(doc.frontmatter.get("license") or DEFAULT_LICENSE),
|
||||
meta={k: v for k, v in doc.frontmatter.items() if k not in _OWN_KEYS},
|
||||
files=content.files, provenance=provenance)
|
||||
match = matches[sha]
|
||||
if match is not None:
|
||||
skill = db.get(Skill, match.skill_id)
|
||||
latest = db.scalar(select(SkillVersion.n).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = _add_version(db, actor, skill, next_n(latest), **fields)
|
||||
else:
|
||||
slug = free_slug(taken, doc.name)
|
||||
taken.add(slug)
|
||||
skill = Skill(slug=slug, name=doc.name, owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, origin=SkillOrigin.imported)
|
||||
db.add(skill)
|
||||
db.flush()
|
||||
version = _add_version(db, actor, skill, 1, **fields)
|
||||
# The pack's own sum, so the audit row names the file that came in; never its content.
|
||||
audit.record(db, action="skill.import", entity_type="skill", entity_id=skill.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{skill.slug} v{version.n} {version.content_sha256} pack {pack_sha}")
|
||||
out.append({"path": doc.path, "content_sha256": version.content_sha256,
|
||||
"info_only": doc.info_only, "skill": skill_out(actor, skill), "n": version.n})
|
||||
return {"status": "imported", "ignored": ignored, "skills": out}
|
||||
|
||||
|
||||
def may_export(user: AppUser, item, firm_export: str) -> bool:
|
||||
"""T2. One's own: always. A firm one: an administrator, or everybody under `everyone`."""
|
||||
return (item.owner_id == user.id or bool(user.is_admin) or firm_export == "everyone")
|
||||
|
||||
|
||||
def export_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> tuple[str, bytes]:
|
||||
"""The pack of version `n` (default: the current one) -> (file name, ZIP bytes)."""
|
||||
skill = _get(db, actor, skill_id) # somebody else's personal one is a 404 before T2 is asked
|
||||
if not may_export(actor, skill, settings.get(db, "skills_firm_export")):
|
||||
raise AuthorizationError("Only an administrator may export the firm's skills.")
|
||||
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.where(SkillVersion.id == skill.current_version_id))
|
||||
version = db.scalar(query)
|
||||
if version is None or not readable_version_ids(actor, skill, [version.id]):
|
||||
raise NotFoundError("Version not found.")
|
||||
data = skill_pack.build_pack([version_content(skill, version, _files(db, version.id))])
|
||||
audit.record(db, action="skill.export", entity_type="skill", entity_id=skill.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{skill.slug} v{version.n} {version.content_sha256} pack {_sha(data)}")
|
||||
return f"{skill.slug}-v{version.n}.zip", data
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""`services/skills.py`: the visibility rule, version numbering and content checks (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import uuid
|
||||
import zipfile
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -173,3 +175,35 @@ def test_approving_an_older_version_is_refused():
|
||||
def test_only_an_administrator_decides(call):
|
||||
with pytest.raises(AuthorizationError):
|
||||
call()
|
||||
|
||||
|
||||
def test_an_imported_slug_takes_the_first_free_number():
|
||||
assert skills.free_slug(set(), "x") == "x"
|
||||
assert skills.free_slug({"x"}, "x") == "x-2"
|
||||
assert skills.free_slug({"x", "x-2"}, "x") == "x-3"
|
||||
long = "a" * 64
|
||||
assert skills.free_slug({long}, long) == "a" * 62 + "-2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("user, firm_export, allowed", [
|
||||
(OWNER, "administrator", True), # one's own: always
|
||||
(OTHER, "administrator", False),
|
||||
(ADMIN, "administrator", True),
|
||||
(OTHER, "everyone", True),
|
||||
])
|
||||
def test_t2_decides_who_exports_a_firm_skill(user, firm_export, allowed):
|
||||
assert skills.may_export(user, _skill("firm"), firm_export) is allowed
|
||||
|
||||
|
||||
def test_an_agent_pack_or_a_pack_without_skill_md_is_not_a_skill_import():
|
||||
agent = skill_pack.build_pack([], skill_pack.AgentDoc(
|
||||
name="a", description="d", body="b", frontmatter={"name": "a", "description": "d"}))
|
||||
with pytest.raises(PackRejected) as err:
|
||||
skills.import_skills(None, OWNER, agent, ip=None)
|
||||
assert err.value.code == "pack_is_agent"
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as zf:
|
||||
zf.writestr("notes.md", "hi")
|
||||
with pytest.raises(PackRejected) as err:
|
||||
skills.import_skills(None, OWNER, buf.getvalue(), ip=None)
|
||||
assert err.value.code == "pack_no_skill"
|
||||
|
||||
Reference in New Issue
Block a user