feat: skill_pack — content_sha256, build_pack z manifestem i paczka agenta (E2.4)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
8cdf8ab70b
commit
7372f275d2
+1
-1
@@ -10,7 +10,7 @@
|
||||
- [x] 2.1 Dodaj `PyYAML` do `backend/requirements.txt` z komentarzem licencji (MIT) i utwórz `backend/app/services/skill_pack.py` z typem odrzucenia (`code` + komunikat PL/EN, wzorem `module_admission_refused`) oraz `read_pack(data: bytes)` sprawdzającym reguły archiwum: ZIP > 10 MB, > 200 plików, suma po rozpakowaniu > 50 MB, kompresja pliku > 100:1, ZIP64, ścieżka z `..`/absolutna/z `\`, dowiązanie, duplikat nazwy, nazwy różniące się tylko wielkością liter. Plik testów `tests/test_skill_pack_unit.py` z jednym testem na każdą regułę na ZIP-ie budowanym w pamięci. Gotowe gdy: bramka (w tym license_gate) zielona i każda z wymienionych reguł ma osobny przechodzący test.
|
||||
- [x] 2.2 Rozszerz `read_pack` o reguły plików: lista rozszerzeń `.md .txt .docx .pdf .xlsx .csv .json .yaml .yml`, sygnatura zgodna z rozszerzeniem (`%PDF-`, ZIP z `[Content_Types].xml` dla DOCX/XLSX), wnętrze DOCX/XLSX sprawdzane `zipfile` tymi samymi limitami, `vbaProject.bin` = odrzucenie, zagnieżdżony ZIP niebędący DOCX/XLSX = odrzucenie. Bez czytania tekstu (wariant b). Gotowe gdy: bramka zielona i każda reguła ma osobny test w `test_skill_pack_unit.py`.
|
||||
- [x] 2.3 Rozszerz `read_pack` o parsowanie SKILL.md: frontmatter > 8 KB, aliasy/kotwice YAML, nie-mapa, brak `name`/`description`, `name` nie kebab ≤64, `description` > 1024, treść > 30 000 znaków = odrzucenie; pola `allowed-tools`, `model`, `hooks`, `mcpServers`, `permissionMode` trafiają do listy „zapisane tylko jako informacja” (D3); wtyczka Claude Code (`.claude-plugin/`) → bierzemy `skills/*/SKILL.md`, a skrypty/hooki/serwery MCP = odrzucenie z listą plików (D1). Gotowe gdy: bramka zielona i każda reguła (w tym kotwica YAML i wtyczka ze skryptem) ma osobny test.
|
||||
- [ ] 2.4 Dodaj `content_sha256(...)` (SKILL.md: UTF-8, NFC, LF, frontmatter kanonicznie z kluczami alfabetycznie + posortowane `ścieżka\0sha256` plików), `build_pack(...) -> bytes` z `atrium-pack.json` (wersja formatu, typ, pliki z sha256) oraz odczyt paczki agenta (`agent.md` + foldery skilli + manifest), z weryfikacją sum z manifestu przy imporcie. Gotowe gdy: bramka zielona; test `content_sha256(read_pack(build_pack(read_pack(x))))` == suma oryginału dla skilla z plikiem `.docx`, test round-trip paczki agenta i test odrzucenia przy niezgodnej sumie w manifeście.
|
||||
- [x] 2.4 Dodaj `content_sha256(...)` (SKILL.md: UTF-8, NFC, LF, frontmatter kanonicznie z kluczami alfabetycznie + posortowane `ścieżka\0sha256` plików), `build_pack(...) -> bytes` z `atrium-pack.json` (wersja formatu, typ, pliki z sha256) oraz odczyt paczki agenta (`agent.md` + foldery skilli + manifest), z weryfikacją sum z manifestu przy imporcie. Gotowe gdy: bramka zielona; test `content_sha256(read_pack(build_pack(read_pack(x))))` == suma oryginału dla skilla z plikiem `.docx`, test round-trip paczki agenta i test odrzucenia przy niezgodnej sumie w manifeście.
|
||||
|
||||
## Etap 3: serwis domenowy (E2.3-E2.4)
|
||||
- [ ] 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.
|
||||
|
||||
@@ -12,3 +12,5 @@
|
||||
- 2.3: `read_pack` parsuje każdy `SKILL.md` do `Pack.skills` (`SkillDoc`: name, description, body, frontmatter, info_only wg D3); 9 nowych kodów `skill_*` + `pack_plugin_code`. Kotwica sama (bez aliasu) też odrzucana; YAML przez `yaml.scan` + `safe_load`, RecursionError (8 KB `[`) = `skill_frontmatter_invalid`. Paczka bez SKILL.md NIE jest odrzucana — to reguła importu (3.4).
|
||||
- Wtyczka: kod = plik spoza listy rozszerzeń, `hooks/`, `scripts/`, `bin/`, `.mcp.json`, `plugin.json` z `hooks`/`mcpServers` — sprawdzane przed regułą rozszerzeń. Pozostałe pliki wtyczki (commands/, agents/) zostają w `files`, nie są wycinane; co z nich zapisać, decyduje 3.4.
|
||||
- 2.3 (dopisek po hooku security): katalog główny wtyczki wyznaczany po segmencie `.claude-plugin`, plik sprawdzany względem KAŻDEGO pasującego katalogu (wtyczka w wtyczce); każdy `.json` w `.claude-plugin/` czytany jak manifest.
|
||||
- 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").
|
||||
|
||||
@@ -12,13 +12,16 @@ on the raw names (`ZipInfo.orig_filename`): on Windows `zipfile` rewrites `\\` t
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import stat
|
||||
import struct
|
||||
import unicodedata
|
||||
import zipfile
|
||||
import zlib
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
import yaml
|
||||
@@ -59,17 +62,22 @@ MESSAGES = {
|
||||
"The pack contains a ZIP archive that is not a Word or Excel document."),
|
||||
"pack_plugin_code": ("Wtyczka zawiera skrypty, hooki albo serwery MCP.",
|
||||
"The plugin contains scripts, hooks or MCP servers."),
|
||||
"skill_not_utf8": ("SKILL.md nie jest zapisany w UTF-8.", "SKILL.md is not UTF-8."),
|
||||
"skill_frontmatter_too_large": ("Nagłówek SKILL.md jest większy niż 8 KB.",
|
||||
"The SKILL.md frontmatter is larger than 8 KB."),
|
||||
"skill_frontmatter_alias": ("Nagłówek SKILL.md używa aliasów albo kotwic YAML.",
|
||||
"The SKILL.md frontmatter uses YAML aliases or anchors."),
|
||||
"skill_frontmatter_invalid": ("Nagłówek SKILL.md nie jest poprawnym YAML.",
|
||||
"The SKILL.md frontmatter is not valid YAML."),
|
||||
"skill_frontmatter_not_mapping": ("Nagłówek SKILL.md nie jest mapą klucz: wartość.",
|
||||
"The SKILL.md frontmatter is not a key: value mapping."),
|
||||
"skill_missing_field": ("SKILL.md nie ma pola name albo description.",
|
||||
"SKILL.md lacks a name or a description."),
|
||||
"pack_manifest_invalid": ("Plik atrium-pack.json jest uszkodzony.",
|
||||
"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."),
|
||||
"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.",
|
||||
"The SKILL.md or agent.md frontmatter is larger than 8 KB."),
|
||||
"skill_frontmatter_alias": ("Nagłówek SKILL.md albo agent.md używa aliasów albo kotwic YAML.",
|
||||
"The SKILL.md or agent.md frontmatter uses YAML aliases or anchors."),
|
||||
"skill_frontmatter_invalid": ("Nagłówek SKILL.md albo agent.md nie jest poprawnym YAML.",
|
||||
"The SKILL.md or agent.md frontmatter is not valid YAML."),
|
||||
"skill_frontmatter_not_mapping": ("Nagłówek SKILL.md albo agent.md nie jest mapą klucz: wartość.",
|
||||
"The SKILL.md or agent.md frontmatter is not a key: value mapping."),
|
||||
"skill_missing_field": ("SKILL.md albo agent.md nie ma pola name albo description.",
|
||||
"SKILL.md or agent.md lacks a name or a description."),
|
||||
"skill_bad_name": ("Pole name musi być w formacie kebab-case, najwyżej 64 znaki.",
|
||||
"The name must be kebab-case, at most 64 characters."),
|
||||
"skill_description_too_long": ("Opis (description) jest dłuższy niż 1024 znaki.",
|
||||
@@ -119,10 +127,35 @@ class SkillDoc:
|
||||
info_only: dict # D3: what the file asked for and was not given
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentDoc:
|
||||
name: str
|
||||
description: str
|
||||
body: str # the instructions
|
||||
frontmatter: dict # `kind`, `tools`, `model` (a hint) — the service decides what to keep
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Pack:
|
||||
files: dict[str, bytes] # path -> content, directories left out
|
||||
files: dict[str, bytes] # path -> content, directories and the manifest left out
|
||||
skills: tuple[SkillDoc, ...] = () # one per SKILL.md, in path order
|
||||
agent: AgentDoc | None = None # from a root `agent.md`
|
||||
kind: str | None = None # the manifest's `type`; None for a pack without one
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SkillContent:
|
||||
"""One skill as it is hashed and packed: its folder name, frontmatter, body and the files beside
|
||||
its SKILL.md (paths relative to the folder). The service builds it from a stored version."""
|
||||
folder: str
|
||||
frontmatter: dict
|
||||
body: str
|
||||
files: dict[str, bytes]
|
||||
|
||||
|
||||
MANIFEST = "atrium-pack.json"
|
||||
FORMAT_VERSION = 1
|
||||
AGENT_DOC = "agent.md"
|
||||
|
||||
|
||||
_ZIP64_EXTRA = 0x0001
|
||||
@@ -307,7 +340,8 @@ def _split_frontmatter(text: str) -> tuple[str, str]:
|
||||
return text[4:end + 1], text[end + 5:]
|
||||
|
||||
|
||||
def _read_skill(path: str, data: bytes) -> SkillDoc:
|
||||
def _read_doc(path: str, data: bytes) -> tuple[dict, str, str, str]:
|
||||
"""The frontmatter rules SKILL.md and agent.md share: -> (frontmatter, name, description, body)."""
|
||||
try:
|
||||
text = data.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
@@ -328,6 +362,11 @@ def _read_skill(path: str, data: bytes) -> SkillDoc:
|
||||
name, description = meta.get("name"), meta.get("description")
|
||||
if not (isinstance(name, str) and name and isinstance(description, str) and description.strip()):
|
||||
raise PackRejected("skill_missing_field", [path])
|
||||
return meta, name, description, body
|
||||
|
||||
|
||||
def _read_skill(path: str, data: bytes) -> SkillDoc:
|
||||
meta, name, description, body = _read_doc(path, data)
|
||||
if len(name) > MAX_NAME or not _KEBAB.fullmatch(name):
|
||||
raise PackRejected("skill_bad_name", [path])
|
||||
if len(description) > MAX_DESCRIPTION:
|
||||
@@ -351,8 +390,88 @@ def read_pack(data: bytes) -> Pack:
|
||||
raise PackRejected("pack_not_zip") from None
|
||||
_check_plugin(files)
|
||||
_check_files(files)
|
||||
kind = _check_manifest(files)
|
||||
# ponytail: a pack with no SKILL.md is not refused here — an agent pack may pin none; whether a
|
||||
# skill import needs one is the import's rule (services/skills.py).
|
||||
skills = tuple(_read_skill(p, d) for p, d in sorted(files.items())
|
||||
if p.rsplit("/", 1)[-1] == "SKILL.md")
|
||||
return Pack(files=files, skills=skills)
|
||||
agent = None
|
||||
if AGENT_DOC in files:
|
||||
meta, name, description, body = _read_doc(AGENT_DOC, files[AGENT_DOC])
|
||||
agent = AgentDoc(name=name, description=description, body=body, frontmatter=meta)
|
||||
return Pack(files=files, skills=skills, agent=agent, kind=kind)
|
||||
|
||||
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _check_manifest(files: dict[str, bytes]) -> str | None:
|
||||
"""Verify `atrium-pack.json` and take it out of `files`. A pack without one (a skill ZIP from
|
||||
elsewhere) is accepted: the sums guard a pack against change on the way, they say nothing of
|
||||
its author, so their absence takes nothing away."""
|
||||
raw = files.pop(MANIFEST, None)
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
manifest = json.loads(raw)
|
||||
listed = {f["path"]: f["sha256"] for f in manifest["files"]}
|
||||
kind = manifest["type"]
|
||||
if manifest["format"] != FORMAT_VERSION or kind not in ("skill", "agent"):
|
||||
raise ValueError
|
||||
except (ValueError, KeyError, TypeError):
|
||||
raise PackRejected("pack_manifest_invalid", [MANIFEST]) from None
|
||||
# Both directions: a file added on the way is as much a change as one altered.
|
||||
wrong = {p for p in listed.keys() | files.keys()
|
||||
if p not in files or listed.get(p) != _sha(files[p])}
|
||||
if wrong:
|
||||
raise PackRejected("pack_manifest_mismatch", wrong)
|
||||
return kind
|
||||
|
||||
|
||||
def skill_content(pack: Pack, skill: SkillDoc) -> SkillContent:
|
||||
"""The skill as `content_sha256` and `build_pack` see it: everything under its SKILL.md's folder."""
|
||||
# ponytail: a SKILL.md nested inside another skill's folder is counted in both; packs this module
|
||||
# builds never nest, and an import keeps one skill per folder.
|
||||
prefix = skill.path[: -len("SKILL.md")]
|
||||
files = {p[len(prefix):]: d for p, d in pack.files.items()
|
||||
if p.startswith(prefix) and p != skill.path and not (prefix == "" and p == AGENT_DOC)}
|
||||
return SkillContent(folder=prefix.rstrip("/").rsplit("/", 1)[-1] or skill.name,
|
||||
frontmatter=skill.frontmatter, body=skill.body, files=files)
|
||||
|
||||
|
||||
def _document(frontmatter: dict, body: str) -> str:
|
||||
"""The canonical text: NFC, LF, the frontmatter re-dumped with its keys in alphabetical order —
|
||||
so a pack that went out and came back in hashes the same however its YAML was spelt."""
|
||||
head = yaml.safe_dump(frontmatter, sort_keys=True, allow_unicode=True, default_flow_style=False)
|
||||
text = f"---\n{head}---\n{body}".replace("\r\n", "\n").replace("\r", "\n")
|
||||
return unicodedata.normalize("NFC", text)
|
||||
|
||||
|
||||
def content_sha256(skill: SkillContent) -> str:
|
||||
"""SHA-256 of the canonical SKILL.md and the sorted `path\\0sha256` lines of its files."""
|
||||
listing = "\n".join(f"{p}\0{_sha(d)}" for p, d in sorted(skill.files.items()))
|
||||
return _sha(_document(skill.frontmatter, skill.body).encode("utf-8") + b"\0\0"
|
||||
+ listing.encode("utf-8"))
|
||||
|
||||
|
||||
def build_pack(skills: Sequence[SkillContent], agent: AgentDoc | None = None) -> bytes:
|
||||
"""A ZIP of one skill (`agent=None`) or of an agent with the skills it pins, each in its own
|
||||
folder, plus `atrium-pack.json` listing every file's sha256. What it writes, `read_pack` reads."""
|
||||
folders = [s.folder for s in skills]
|
||||
if len(set(folders)) != len(folders) or (agent is None and len(skills) != 1):
|
||||
raise ValueError("a pack holds one skill, or an agent with skills in distinct folders")
|
||||
files: dict[str, bytes] = {}
|
||||
for s in skills:
|
||||
files[f"{s.folder}/SKILL.md"] = _document(s.frontmatter, s.body).encode("utf-8")
|
||||
files.update({f"{s.folder}/{p}": d for p, d in s.files.items()})
|
||||
if agent is not None:
|
||||
files[AGENT_DOC] = _document(agent.frontmatter, agent.body).encode("utf-8")
|
||||
manifest = {"format": FORMAT_VERSION, "type": "skill" if agent is None else "agent",
|
||||
"files": [{"path": p, "sha256": _sha(d)} for p, d in sorted(files.items())]}
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for path, data in sorted(files.items()):
|
||||
zf.writestr(path, data)
|
||||
zf.writestr(MANIFEST, json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return buf.getvalue()
|
||||
|
||||
@@ -348,3 +348,62 @@ def test_a_plugin_nested_in_another_is_judged_against_its_own_root():
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(data)
|
||||
assert (caught.value.code, caught.value.files) == ("pack_plugin_code", ["inner/hooks/hooks.json"])
|
||||
|
||||
|
||||
# --- content sum, build_pack, agent packs (2.4) ------------------------------------------------
|
||||
|
||||
_ORIGINAL = ("---\r\nname: nda\r\nmetadata: {version: 2, author: Zespół}\r\ndescription: Przeglăd\r\n"
|
||||
"license: proprietary\r\n---\r\n# Przeglăd NDA\r\n").encode()
|
||||
_DOCX = _office("word/document.xml")
|
||||
|
||||
|
||||
def _sum(pack, i=0):
|
||||
return skill_pack.content_sha256(skill_pack.skill_content(pack, pack.skills[i]))
|
||||
|
||||
|
||||
def test_a_skill_with_a_docx_hashes_the_same_after_export_and_import():
|
||||
original = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx", _DOCX)]))
|
||||
content = skill_pack.skill_content(original, original.skills[0])
|
||||
assert content.folder == "nda" and content.files == {"resources/playbook.docx": _DOCX}
|
||||
again = read_pack(skill_pack.build_pack([content]))
|
||||
assert again.kind == "skill" and "atrium-pack.json" not in again.files
|
||||
assert _sum(again) == _sum(original)
|
||||
# Only spelling is normalised away: a changed file is a changed skill.
|
||||
other = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx",
|
||||
_office("word/other.xml"))]))
|
||||
assert _sum(other) != _sum(original)
|
||||
|
||||
|
||||
def test_an_agent_pack_round_trips_with_its_skills():
|
||||
skills = [skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n",
|
||||
{"r/a.txt": b"x"}),
|
||||
skill_pack.SkillContent("dpa", {"name": "dpa", "description": "e"}, "# b\n", {})]
|
||||
agent = skill_pack.AgentDoc(name="Asystent umów", description="Przegląda umowy", body="Bądź zwięzły.\n",
|
||||
frontmatter={"name": "Asystent umów", "description": "Przegląda umowy",
|
||||
"kind": "assistant", "tools": ["search"], "model": "sonnet"})
|
||||
pack = read_pack(skill_pack.build_pack(skills, agent))
|
||||
assert pack.kind == "agent" and pack.agent == agent
|
||||
assert [skill_pack.skill_content(pack, s) for s in pack.skills] == sorted(skills, key=lambda s: s.folder)
|
||||
|
||||
|
||||
def _tampered(change) -> tuple[str, list[str]]:
|
||||
content = skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n", {"a.txt": b"x"})
|
||||
with zipfile.ZipFile(io.BytesIO(skill_pack.build_pack([content]))) as zf:
|
||||
entries = {n: zf.read(n) for n in zf.namelist()}
|
||||
change(entries)
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip(entries.items()))
|
||||
return caught.value.code, caught.value.files
|
||||
|
||||
|
||||
def test_a_file_whose_sum_differs_from_the_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"nda/a.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/a.txt"])
|
||||
|
||||
|
||||
def test_a_file_missing_from_the_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"nda/b.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/b.txt"])
|
||||
|
||||
|
||||
def test_a_malformed_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"atrium-pack.json": b'{"format": 1}'}))[0] \
|
||||
== "pack_manifest_invalid"
|
||||
|
||||
Reference in New Issue
Block a user