skills: anyone may propose a firm skill version; a version may replace one file

A new version on an active firm skill is a proposal from anyone (can_propose); archive stays with editors. A proposer's publish is always a request, even in direct mode. file_updates replaces or adds single files and carries the rest over byte for byte.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJYwbXKWMeNZfrFuXq
This commit is contained in:
tobayah
2026-11-19 15:16:31 +01:00
co-authored by Claude Opus 5.5
parent b9b718d7e1
commit b97bbc49cb
4 changed files with 213 additions and 28 deletions
+2
View File
@@ -339,6 +339,8 @@ class SkillVersionIn(BaseModel):
license: str | None = Field(default=None, max_length=200)
metadata: SmallJson = None
files: SkillFiles = Field(default=None, max_length=200)
# path -> base64: the previous version's files with these replaced or added. Not with `files`.
file_updates: SkillFiles = Field(default=None, max_length=200)
class SkillCreateIn(SkillVersionIn):
+38 -12
View File
@@ -84,6 +84,14 @@ def can_edit(user: AppUser, item) -> bool:
return item.owner_id == user.id or (item.scope == SkillScope.firm and bool(user.is_admin))
def can_propose(item, user: AppUser) -> bool:
"""Whoever may edit, and anybody for an active firm skill: a new version is a proposal there
(`_add_version` never moves a firm skill's current version; only an approval does).
Argument order is (item, user), unlike `can_edit`."""
return can_edit(user, item) or (item.scope == SkillScope.firm
and item.status == CatalogStatus.active)
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."""
@@ -107,9 +115,17 @@ def _get_editable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
return skill
def _get_proposable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
skill = _get(db, user, skill_id)
if not can_propose(skill, user):
raise AuthorizationError("Only the owner or an administrator may change this 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):
"""Whoever may propose reads every version, so a proposer sees their own; anybody else only the
current one (for a firm skill: approved)."""
if can_propose(skill, user):
return set(version_ids)
return {skill.current_version_id} & set(version_ids)
@@ -200,7 +216,8 @@ def skill_out(user: AppUser, skill: Skill) -> dict[str, Any]:
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)}
"editable": can_edit(user, skill),
"proposable": can_propose(skill, user)}
def version_out(version: SkillVersion, files: list[SkillFile]) -> dict[str, Any]:
@@ -294,10 +311,15 @@ def create_skill(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | No
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)
included — `{}` is how to remove them all). `file_updates` (path -> bytes) instead replaces or
adds just those files and carries every other one over byte for byte, so a caller that holds
one file need not hold the rest. An imported licence is the author's: it stays. On a firm skill
this is a proposal: it waits for publication like any other new version."""
skill = _get_proposable(db, actor, skill_id)
if skill.status == CatalogStatus.archived:
raise ConflictError("An archived skill takes no new versions.")
if fields.get("files") is not None and fields.get("file_updates") is not None:
raise ValidationError("Send files or file_updates, not both.")
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
@@ -306,7 +328,9 @@ def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapp
files = fields.get("files")
if files is None:
files = {f.path: f.content for f in _files(db, latest.id)}
if fields.get("name"):
files.update(fields.get("file_updates") or {})
# The name sits on the identity row, outside versioning: a proposal must not rename a firm skill.
if fields.get("name") and can_edit(actor, skill):
skill.name = fields["name"]
version = _add_version(
db, actor, skill, next_n(latest.n),
@@ -339,15 +363,16 @@ def _make_current(item, version) -> None:
def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
ip: str | None) -> dict:
ip: str | None, request_only: bool = False) -> dict:
"""`approval` -> a request for THIS version (every version, not only the first); `direct` ->
published now. The item stays where it was until an administrator says yes."""
published now. The item stays where it was until an administrator says yes. `request_only`:
a proposer who may not edit never publishes on their own, whatever the setting says."""
if item.status == CatalogStatus.archived:
raise ConflictError("An archived item cannot be published.")
if item.scope == SkillScope.firm and item.current_version_id == version.id:
raise ConflictError("This version is already published.")
target = f"{getattr(item, 'slug', item.name)} v{version.n}"
if settings.get(db, "skills_firm_publish") == "direct":
if not request_only and settings.get(db, "skills_firm_publish") == "direct":
_make_current(item, version)
db.flush()
# No request and nobody else's yes: the setting is the approval, the detail says so.
@@ -370,15 +395,16 @@ def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
def publish_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
ip: str | None) -> dict:
"""Publish version `n` (default: the newest) to the firm — by the owner, or for a firm skill
also by an administrator."""
skill = _get_editable(db, actor, skill_id)
also by an administrator. Anybody else who proposed a version may only ask: always a request."""
skill = _get_proposable(db, actor, skill_id)
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
query = (query.where(SkillVersion.n == n) if n is not None
else query.order_by(SkillVersion.n.desc()).limit(1))
version = db.scalar(query)
if version is None:
raise NotFoundError("Version not found.")
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip),
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip,
request_only=not can_edit(actor, skill)),
"skill": skill_out(actor, skill)}
+28 -10
View File
@@ -109,14 +109,31 @@ def test_a_firm_skill_is_everybodys_to_read(admin_client, client, owner, other,
assert r.json()["current"]["n"] == 1
assert any(s["id"] == sid for s in api.get(SKILLS, headers=who).json())
# Reading is not changing: anybody else may not touch it.
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Hijacked\n"},
headers=bearer(other["token"]))
assert r.status_code == 403, r.text
# Archiving stays with the editors; a new version from anybody else is a proposal (below).
assert client.post(f"{SKILLS}/{sid}/archive",
headers=bearer(other["token"])).status_code == 403
def test_other_user_proposes_on_a_firm_skill(admin_client, client, owner, other, firm_skill):
"""A proposal is a new version; it never moves the firm's current one, and a proposer's own
publish is a request even where the firm publishes directly."""
sid, me = firm_skill["id"], bearer(other["token"])
with settings_set(admin_client, skills_firm_publish="direct"):
r = client.post(f"{SKILLS}/{sid}/versions", json={"body": "# Proposal\n"}, headers=me)
assert r.status_code == 201, r.text
n = r.json()["n"]
seen = client.get(f"{SKILLS}/{sid}", headers=me).json()
assert seen["current"]["n"] == n - 1 and n in [v["n"] for v in seen["versions"]]
assert (seen["editable"], seen["proposable"]) == (False, True)
both = client.post(f"{SKILLS}/{sid}/versions", headers=me,
json={"files": {}, "file_updates": {"a.md": "eA=="}})
assert both.status_code == 422, both.text
r = client.post(f"{SKILLS}/{sid}/publish", params={"n": n}, headers=me)
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
assert client.get(f"{SKILLS}/{sid}", headers=me).json()["current"]["n"] == n - 1
_approve(admin_client, sid)
def test_a_missing_skill_is_404(client, owner):
assert client.get(f"{SKILLS}/{uuid.uuid4()}", headers=bearer(owner["token"])).status_code == 404
@@ -135,10 +152,11 @@ def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client,
out = client.get(f"{SKILLS}/{sid}", headers=bearer(other["token"])).json()
return out["current"]["n"], [v["n"] for v in out["versions"]]
# Written is not published: everybody else still reads the approved version, only.
assert seen_by_other() == (n - 1, [n - 1])
assert client.get(f"{SKILLS}/{sid}/versions/{n}",
headers=bearer(other["token"])).status_code == 404
# Written is not published: everybody else still has the approved version as current, and
# may read the proposal beside it (anyone may propose, so anyone may see what is proposed).
assert seen_by_other() == (n - 1, list(range(n, 0, -1)))
got = client.get(f"{SKILLS}/{sid}/versions/{n}", headers=bearer(other["token"]))
assert got.status_code == 200 and got.json()["approved_for_firm"] is False
owner_view = client.get(f"{SKILLS}/{sid}", headers=bearer(owner["token"])).json()
assert owner_view["current"]["n"] == n - 1 and n in [v["n"] for v in owner_view["versions"]]
@@ -146,7 +164,7 @@ def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client,
assert r.status_code == 200 and r.json()["status"] == "pending", r.text
again = client.post(f"{SKILLS}/{sid}/publish", headers=bearer(owner["token"]))
assert again.status_code == 409 # already waiting
assert seen_by_other() == (n - 1, [n - 1])
assert seen_by_other() == (n - 1, list(range(n, 0, -1)))
# The administrator's queue shows both sides of the diff.
request = next(q for q in admin_client.get(REQUESTS).json() if q["item"]["id"] == sid)
@@ -155,7 +173,7 @@ def test_a_new_firm_version_stays_invisible_until_approved(admin_client, client,
decided = _approve(admin_client, sid)
assert decided["status"] == "approved"
assert seen_by_other() == (n, [n])
assert seen_by_other() == (n, list(range(n, 0, -1)))
assert admin_client.post(f"{REQUESTS}/{request['id']}/approve").status_code == 409
+145 -6
View File
@@ -1,6 +1,7 @@
"""`services/skills.py`: the visibility rule, version numbering and content checks (DB-free)."""
from __future__ import annotations
import hashlib
import io
import uuid
import zipfile
@@ -9,7 +10,7 @@ from types import SimpleNamespace
import pytest
from app.errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
from app.models import Skill
from app.models import Skill, SkillFile
from app.services import skill_pack, skills
from app.services.skill_pack import PackRejected
@@ -52,19 +53,156 @@ def test_someone_elses_personal_skill_is_a_404_not_a_403():
skills.archive_skill(db, user, db.skill.id, ip=None)
def test_a_firm_skill_is_changed_only_by_its_editors():
def test_a_firm_skill_is_archived_only_by_its_editors():
db = _Db(_skill("firm"))
with pytest.raises(AuthorizationError):
skills.new_version(db, OTHER, db.skill.id, {}, ip=None)
skills.archive_skill(db, OTHER, db.skill.id, ip=None)
def test_a_non_editor_reads_only_the_current_version():
def test_a_proposer_reads_every_firm_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(OTHER, skill, [approved, pending]) == {approved, pending}
assert skills.readable_version_ids(OWNER, skill, [approved, pending]) == {approved, pending}
def test_a_stranger_reads_only_the_current_version_of_an_archived_firm_skill():
approved, pending = uuid.uuid4(), uuid.uuid4()
skill = _skill("firm", current=approved)
skill.status = "archived"
assert skills.readable_version_ids(OTHER, skill, [approved, pending]) == {approved}
class _VersionDb:
"""What `new_version` touches: the skill, the newest version, and the files of a version
(the newest one's first, then whatever was just added)."""
def __init__(self, skill, latest, latest_files):
self.skill, self.latest, self._latest_files = skill, latest, list(latest_files)
self.added, self._scalars_calls = [], 0
def get(self, _model, _id):
return self.skill
def scalar(self, _stmt):
return self.latest
def scalars(self, _stmt):
self._scalars_calls += 1
if self._scalars_calls == 1:
return iter(self._latest_files)
return iter(a for a in self.added if isinstance(a, SkillFile))
def add(self, row):
self.added.append(row)
def flush(self):
pass
def _stored(path, data):
return SimpleNamespace(path=path, content=data)
def _latest():
return SimpleNamespace(id=uuid.uuid4(), n=1, description="Opis", body_md="Treść", license="MIT",
meta={})
def test_anyone_proposes_on_a_firm_skill_without_moving_current(audited):
v1 = _latest()
skill = _skill("firm", current=v1.id)
out = skills.new_version(_VersionDb(skill, v1, []), OTHER, skill.id, {"body": "Nowa"}, ip=None)
assert out["n"] == 2 and skill.current_version_id == v1.id
assert audited == ["skill.version"]
def test_a_proposal_does_not_rename_a_firm_skill(audited):
v1 = _latest()
skill = _skill("firm", current=v1.id)
skills.new_version(_VersionDb(skill, v1, []), OTHER, skill.id, {"name": "Hijacked"}, ip=None)
assert skill.name == "NDA"
def test_nobody_proposes_on_someone_elses_personal_skill():
db = _VersionDb(_skill("personal"), _latest(), [])
for user in (OTHER, ADMIN):
with pytest.raises(NotFoundError):
skills.new_version(db, user, db.skill.id, {}, ip=None)
def test_an_archived_firm_skill_takes_no_proposal():
skill = _skill("firm")
skill.status = "archived"
assert not skills.can_propose(skill, OTHER)
with pytest.raises(AuthorizationError):
skills.new_version(_VersionDb(skill, _latest(), []), OTHER, skill.id, {}, ip=None)
def test_file_updates_keep_the_other_files_byte_identical(audited):
note, old_yaml = "Notatka\n".encode(), b"wersja_formatu: 1\n"
v1 = _latest()
skill = _skill("firm", current=v1.id)
db = _VersionDb(skill, v1, [_stored("notatka.md", note), _stored("sprawdzanie.yaml", old_yaml)])
new_yaml = b"wersja_formatu: 1\nkroki: []\n"
out = skills.new_version(db, OTHER, skill.id, {"file_updates": {"sprawdzanie.yaml": new_yaml}},
ip=None)
sha = {f["path"]: f["sha256"] for f in out["files"]}
assert sha["notatka.md"] == hashlib.sha256(note).hexdigest()
assert sha["sprawdzanie.yaml"] == hashlib.sha256(new_yaml).hexdigest()
assert set(sha) == {"notatka.md", "sprawdzanie.yaml"}
def test_files_and_file_updates_together_are_refused():
v1 = _latest()
skill = _skill("firm", current=v1.id)
with pytest.raises(ValidationError) as err:
skills.new_version(_VersionDb(skill, v1, []), OTHER, skill.id,
{"files": {}, "file_updates": {"a.md": b"x"}}, ip=None)
assert str(err.value) == "Send files or file_updates, not both."
class _ProposerPublishDb:
def __init__(self, skill, version):
self.skill, self._queue, self.added = skill, [version, None], []
def get(self, _model, _id):
return self.skill
def scalar(self, _stmt):
return self._queue.pop(0)
def add(self, row):
self.added.append(row)
def flush(self):
pass
def test_a_proposers_publish_is_a_request_even_when_direct(monkeypatch, audited):
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "direct")
skill = _skill("firm", current=uuid.uuid4())
version = _version(2)
out = skills.publish_skill(_ProposerPublishDb(skill, version), OTHER, skill.id, 2, ip=None)
assert out["status"] == "pending" and skill.current_version_id != version.id
assert audited == ["skill.publish_request"]
def test_an_editors_publish_stays_direct_in_direct_mode(monkeypatch, audited):
monkeypatch.setattr(skills.settings, "get", lambda _db, _key: "direct")
skill = _skill("firm", current=uuid.uuid4())
version = _version(2)
out = skills.publish_skill(_ProposerPublishDb(skill, version), ADMIN, skill.id, 2, ip=None)
assert out["status"] == "published" and skill.current_version_id == version.id
def test_skill_out_says_who_may_propose():
firm = _skill("firm")
assert skills.skill_out(OTHER, firm)["proposable"] is True
assert skills.skill_out(OTHER, firm)["editable"] is False
assert skills.skill_out(OTHER, _skill("personal"))["proposable"] is False
def test_next_n():
assert skills.next_n(None) == 1
assert skills.next_n(4) == 5
@@ -222,7 +360,7 @@ def _sv(skill, current=False):
(OWNER, "personal", "personal", True, True), # one's own working notes
(OTHER, "personal", "personal", True, False), # somebody else's: invisible
(OTHER, "personal", "firm", True, True), # the firm's published version
(OTHER, "personal", "firm", False, False), # ...but not one still waiting for approval
(OTHER, "personal", "firm", False, True), # a proposal too: anyone may propose, so read
(OWNER, "personal", "firm", False, True), # its editor reads every version
(OWNER, "firm", "personal", True, False), # a firm agent never carries a personal skill
(ADMIN, "firm", "personal", True, False),
@@ -352,6 +490,7 @@ def test_get_file_returns_the_bytes_of_a_readable_version():
def test_get_file_is_404_for_a_version_the_person_cannot_read():
pending = _full_version(2)
skill = _skill("firm", current=uuid.uuid4())
skill.status = "archived" # nobody proposes on it any more, so a stranger reads only current
stored = SimpleNamespace(media_type="application/yaml", content=b"x")
with pytest.raises(NotFoundError):
skills.get_file(_ReadDb(skill, [pending, stored]), OTHER, skill.id, 2, "sprawdzanie.yaml")