Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(skills): drop a skill folder onto the window to install it

Haraldc7b9fc17d253
diff --git a/jarvis/core/uploads.py b/jarvis/core/uploads.py
new file mode 100644
index 0000000000..51da7d619c
--- /dev/null
+++ b/jarvis/core/uploads.py
@@ -0,0 +1,332 @@
+"""Staging for uploads that arrive as a folder or an archive.
+
+The desktop UI lets the owner drop a whole folder (or a ``.zip`` / ``.tar.gz``)
+onto a dropzone. What reaches the server is a flat list of ``(path, bytes)``
+pairs whose paths come straight from the browser — which means they are
+untrusted: a crafted archive can carry ``../../.ssh/authorized_keys`` just as
+easily as ``SKILL.md``.
+
+This module turns that list into a real directory on disk, and it is the ONLY
+place that decides what a legal upload path is. Everything it does is
+fail-closed:
+
+- a path that escapes the destination (``..``, a leading ``/``, a drive
+ letter) rejects the whole upload rather than being silently dropped, because
+ a traversal entry is an attack, not a typo,
+- OS clutter (``.git/``, ``__MACOSX/``, ``.DS_Store``, ``Thumbs.db``) is
+ removed and REPORTED, so the owner sees why the file count shrank,
+- a shared top-level folder is stripped, so dropping ``my-skill/`` and
+ dropping its contents give the same result,
+- size and count ceilings are checked against the archive's own headers
+ BEFORE anything is written, so a zip bomb never reaches the disk.
+
+The caller decides what the staged folder means (a skill, a plugin, a
+wallpaper); this module only guarantees that the folder is a faithful,
+harmless copy of what was uploaded.
+"""
+from __future__ import annotations
+
+import io
+import logging
+import tarfile
+import zipfile
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+#: Ceilings mirroring the ones the public skill catalogs use. They are checked
+#: per file AND in total, because fifty small files can hurt as much as one
+#: large one.
+MAX_UPLOAD_FILE_BYTES = 10 * 1024 * 1024
+MAX_UPLOAD_TOTAL_BYTES = 50 * 1024 * 1024
+#: A folder with more entries than this is a mistaken drop (a home directory,
+#: a ``node_modules``), not a skill or a plugin.
+MAX_UPLOAD_FILE_COUNT = 2000
+
+#: Suffixes that make a single uploaded file an archive to expand rather than
+#: a file to store. Ordered longest-first so ``.tar.gz`` wins over ``.gz``.
+ARCHIVE_SUFFIXES: tuple[str, ...] = (".tar.gz", ".zip", ".tgz")
+
+_METADATA_DIRS = frozenset({".git", "__macosx", ".svn", ".hg"})
+_METADATA_FILES = frozenset({".ds_store", "thumbs.db", "desktop.ini"})
+
+
+class UploadRejected(Exception):
+ """An upload that must not be staged, with the reason the owner will read.
+
+ ``status_code`` travels along so a route can hand it to the client
+ unchanged instead of re-deriving it from the message.
+ """
+
+ def __init__(self, message: str, status_code: int = 400) -> None:
+ super().__init__(message)
+ self.message = message
+ self.status_code = status_code
+
+
+@dataclass(frozen=True)
+class StagedUpload:
+ """What ``stage_upload`` produced, in the words the UI needs.
+
+ ``files`` are the paths as they now exist under ``root`` — normalized,
+ filtered and with the shared folder already stripped. ``ignored`` and
+ ``stripped_root`` exist so the UI can explain the difference between what
+ was dropped and what was kept, instead of quietly showing fewer files.
+ """
+
+ root: Path
+ files: tuple[str, ...]
+ ignored: tuple[str, ...]
+ stripped_root: str | None
+ total_bytes: int
+
+ def to_json(self) -> dict[str, object]:
+ return {
+ "files": list(self.files),
+ "ignored": list(self.ignored),
+ "stripped_root": self.stripped_root,
+ "total_bytes": self.total_bytes,
+ }
+
+
+def is_archive_name(name: str) -> bool:
+ """True when a single uploaded file should be expanded, not stored."""
+ lowered = name.strip().lower()
+ return any(lowered.endswith(suffix) for suffix in ARCHIVE_SUFFIXES)
+
+
+def is_local_metadata_path(path: str) -> bool:
+ """True for editor/OS clutter that no upload should ever carry."""
+ segments = [segment for segment in path.lower().split("/") if segment]
+ if not segments:
+ return False
+ if any(segment in _METADATA_DIRS for segment in segments[:-1]):
+ return True
+ basename = segments[-1]
+ if basename in _METADATA_DIRS:
+ return True
+ return basename in _METADATA_FILES or basename.startswith("._")
+
+
+def normalize_upload_path(raw: str) -> str:
+ """The POSIX-style relative path of an uploaded entry.
+
+ Returns ``""`` for an entry that carries no usable path (an empty name, a
+ bare directory marker) — the caller skips those. Raises
+ ``UploadRejected`` for a path that tries to leave the destination, because
+ that is never a mistake worth tolerating.
+ """
+ cleaned = raw.replace("\x00", "").replace("\\", "/").strip()
+ while cleaned.startswith("./"):
+ cleaned = cleaned[2:]
+ cleaned = cleaned.lstrip("/")
+ if not cleaned or cleaned.endswith("/"):
+ return ""
+
+ segments = [segment for segment in cleaned.split("/") if segment and segment != "."]
+ if not segments:
+ return ""
+ if any(segment == ".." for segment in segments):
+ raise UploadRejected(f"Upload path {raw!r} points outside the folder.")
+ # A Windows drive letter survives the slash normalisation above and would
+ # make pathlib discard the destination on join.
+ if ":" in segments[0]:
+ raise UploadRejected(f"Upload path {raw!r} is not a relative path.")
+ return "/".join(segments)
+
+
+def strip_shared_root(paths: Sequence[str]) -> tuple[list[str], str | None]:
+ """Removes the one folder every path shares, if there is one.
+
+ Dropping ``my-skill/`` and dropping the three files inside it must not
+ produce different results — only this function decides which of the two
+ the upload was.
+ """
+ if not paths:
+ return list(paths), None
+ split = [path.split("/") for path in paths]
+ if any(len(parts) < 2 for parts in split):
+ return list(paths), None
+ first = split[0][0]
+ if any(parts[0] != first for parts in split):
+ return list(paths), None
+ return ["/".join(parts[1:]) for parts in split], first
+
+
+def expand_archive(name: str, data: bytes) -> list[tuple[str, bytes]]:
+ """Unpacks a ``.zip`` / ``.tar.gz`` / ``.tgz`` into ``(path, bytes)`` pairs.
+
+ The declared sizes in the archive headers are checked first, so a bomb is
+ refused before a single byte is decompressed.
+ """
+ lowered = name.strip().lower()
+ if lowered.endswith(".zip"):
+ return _expand_zip(name, data)
+ if lowered.endswith(".tar.gz") or lowered.endswith(".tgz"):
+ return _expand_tar(name, data)
+ raise UploadRejected(f"{name!r} is not a supported archive (.zip, .tar.gz, .tgz).")
+
+
+def _expand_zip(name: str, data: bytes) -> list[tuple[str, bytes]]:
+ try:
+ archive = zipfile.ZipFile(io.BytesIO(data))
+ except zipfile.BadZipFile as exc:
+ raise UploadRejected(f"{name!r} is not a readable ZIP archive.") from exc
+
+ with archive:
+ members = [info for info in archive.infolist() if not info.is_dir()]
+ _check_declared_sizes(
+ [(info.filename, info.file_size) for info in members], name
+ )
+ out: list[tuple[str, bytes]] = []
+ for info in members:
+ try:
+ out.append((info.filename, archive.read(info)))
+ except (OSError, zipfile.BadZipFile) as exc:
+ raise UploadRejected(
+ f"{name!r} could not be unpacked: {exc}"
+ ) from exc
+ return out
+
+
+def _expand_tar(name: str, data: bytes) -> list[tuple[str, bytes]]:
+ try:
+ archive = tarfile.open(fileobj=io.BytesIO(data), mode="r:gz")
+ except (tarfile.TarError, OSError) as exc:
+ raise UploadRejected(f"{name!r} is not a readable tar.gz archive.") from exc
+
+ with archive:
+ # Only regular files travel. Links, devices and fifos are dropped
+ # rather than rejected: an archive of a real project may legitimately
+ # carry a symlink, and refusing the whole upload over one would be
+ # useless to the owner. What matters is that none of them is written.
+ members = [member for member in archive.getmembers() if member.isfile()]
+ _check_declared_sizes([(member.name, member.size) for member in members], name)
+ out: list[tuple[str, bytes]] = []
+ for member in members:
+ handle = archive.extractfile(member)
+ if handle is None: # unreadable member — skip, do not fail the upload
+ logger.warning("upload: skipping unreadable tar member %r", member.name)
+ continue
+ out.append((member.name, handle.read()))
+ return out
+
+
+def _check_declared_sizes(entries: Sequence[tuple[str, int]], archive_name: str) -> None:
+ """Refuses an archive on its own headers, before anything is decompressed."""
+ if len(entries) > MAX_UPLOAD_FILE_COUNT:
+ raise UploadRejected(
+ f"{archive_name!r} contains {len(entries)} files — "
+ f"the limit is {MAX_UPLOAD_FILE_COUNT}."
+ )
+ total = 0
+ for path, size in entries:
+ if size > MAX_UPLOAD_FILE_BYTES:
+ raise UploadRejected(_file_too_large_message(path))
+ total += size
+ if total > MAX_UPLOAD_TOTAL_BYTES:
+ raise UploadRejected(_total_too_large_message())
+
+
+def _file_too_large_message(path: str) -> str:
+ limit_mb = MAX_UPLOAD_FILE_BYTES // (1024 * 1024)
+ return f"'{path}' is larger than {limit_mb} MB."
+
+
+def _total_too_large_message() -> str:
+ limit_mb = MAX_UPLOAD_TOTAL_BYTES // (1024 * 1024)
+ return f"The upload is larger than {limit_mb} MB in total."
+
+
+def stage_upload(
+ entries: Iterable[tuple[str, bytes]],
+ dest: Path,
+ *,
+ expand_archives: bool = True,
+) -> StagedUpload:
+ """Writes an uploaded folder or archive into ``dest`` and reports what happened.
+
+ ``dest`` is created if it does not exist and is expected to be empty and
+ owned by the caller (a temporary directory in practice) — nothing here
+ guards against writing into a directory that already holds files.
+ """
+ pairs = list(entries)
+ if expand_archives and len(pairs) == 1 and is_archive_name(pairs[0][0]):
+ name, data = pairs[0]
+ if len(data) > MAX_UPLOAD_TOTAL_BYTES:
+ raise UploadRejected(_total_too_large_message())
+ pairs = expand_archive(name, data)
+
+ if not pairs:
+ raise UploadRejected("The upload contains no files.")
+
+ kept: list[tuple[str, bytes]] = []
+ ignored: list[str] = []
+ for raw_path, data in pairs:
+ path = normalize_upload_path(raw_path)
+ if not path:
+ continue
+ if is_local_metadata_path(path):
+ ignored.append(path)
+ continue
+ kept.append((path, data))
+
+ if not kept:
+ raise UploadRejected("The upload contains no usable files.")
+ if len(kept) > MAX_UPLOAD_FILE_COUNT:
+ raise UploadRejected(
+ f"The upload contains {len(kept)} files — "
+ f"the limit is {MAX_UPLOAD_FILE_COUNT}."
+ )
+
+ total = 0
+ for path, data in kept:
+ if len(data) > MAX_UPLOAD_FILE_BYTES:
+ raise UploadRejected(_file_too_large_message(path))
+ total += len(data)
+ if total > MAX_UPLOAD_TOTAL_BYTES:
+ raise UploadRejected(_total_too_large_message())
+
+ stripped_paths, stripped_root = strip_shared_root([path for path, _ in kept])
+
+ root = dest.resolve()
+ root.mkdir(parents=True, exist_ok=True)
+ written: list[str] = []
+ for path, (_, data) in zip(stripped_paths, kept, strict=True):
+ target = (root / path).resolve()
+ # Belt and braces: normalize_upload_path already refused traversal, but
+ # a write outside the staging root must be impossible even if it ever
+ # grows a hole.
+ if target != root and root not in target.parents:
+ raise UploadRejected(f"Upload path {path!r} points outside the folder.")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ target.write_bytes(data)
+ except OSError as exc:
+ raise UploadRejected(
+ f"Could not store '{path}': {exc}", status_code=500
+ ) from exc
+ written.append(path)
+
+ return StagedUpload(
+ root=root,
+ files=tuple(written),
+ # Reported in the same words as the kept files. Clutter is filtered
+ # before the shared folder is found, so a path only loses the wrapper
+ # when it actually sat inside it — a stray ``__MACOSX/`` NEXT to the
+ # skill folder keeps its own name.
+ ignored=tuple(dict.fromkeys(_strip_prefix(ignored, stripped_root))),
+ stripped_root=stripped_root,
+ total_bytes=total,
+ )
+
+
+def _strip_prefix(paths: Sequence[str], prefix: str | None) -> list[str]:
+ if not prefix:
+ return list(paths)
+ marker = f"{prefix}/"
+ return [
+ path[len(marker):] if path.startswith(marker) else path for path in paths
+ ]
diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.py
index ee514678f1..52e0252588 100644
--- a/jarvis/ui/web/skills_routes.py
+++ b/jarvis/ui/web/skills_routes.py
@@ -23,16 +23,22 @@ from dataclasses import replace
from pathlib import Path
from typing import Any
-from fastapi import APIRouter, HTTPException, Request
+from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel, Field
from jarvis.core.paths import user_skills_dir
+from jarvis.core.uploads import UploadRejected, stage_upload
from jarvis.skills.builtin import BUILTIN_SKILL_NAMES
from jarvis.skills.finder import SearchFilters, SkillFinder
from jarvis.skills.loader import parse_skill
from jarvis.skills.origin import read_origin
from jarvis.skills.schema import RESOURCE_KINDS, Skill, SkillLifecycleState
+from jarvis.ui.web.upload_intake import (
+ read_upload_entries,
+ upload_http_error,
+ upload_limits,
+)
router = APIRouter(prefix="/api/skills", tags=["skills"])
@@ -103,6 +109,12 @@ def _skill_to_summary(s: Skill) -> dict[str, Any]:
"tags": list(fm.tags) if fm else [],
"resources": resources,
"resource_count": resource_count,
+ # Read through the portable adapter: a SKILL.md written for the open
+ # Agent Skills format, not for Jarvis. The ignored keys travel with it
+ # — the owner of the file has to be able to see what was dropped from
+ # it, which is the whole difference between tolerant and sloppy.
+ "portable": s.portable,
+ "ignored_fields": list(s.ignored_fields),
}
@@ -722,6 +734,220 @@ async def import_skill_from_path(
return detail
+# ----------------------------------------------------------------------
+# Upload — a skill folder or archive dropped onto the UI
+# ----------------------------------------------------------------------
+
+def _locate_skill_root(staged_root: Path) -> Path:
+ """The folder inside a staged upload that actually holds the skill.
+
+ People drop three different things and mean the same one: the skill
+ folder, its contents, or a repository ZIP where the skill sits a few
+ levels down (``repo-main/skills/my-skill/``). Staging already strips one
+ shared wrapper; this walks the rest of the way.
+
+ A single ``SKILL.md`` anywhere in the tree names the skill. Several mean
+ the upload holds a catalog rather than one skill — that is refused with
+ the paths listed, because guessing which one was meant is exactly the kind
+ of silent choice that installs the wrong thing.
+ """
+ candidates = sorted(
+ path
+ for path in staged_root.rglob("*")
+ if path.is_file() and path.name.lower() == "skill.md"
+ )
+ if not candidates:
+ raise HTTPException(
+ status_code=400,
+ detail="No SKILL.md found in the upload.",
+ )
+ if len(candidates) > 1:
+ listed = ", ".join(
+ str(path.relative_to(staged_root)).replace("\\", "/")
+ for path in candidates[:5]
+ )
+ suffix = ", ..." if len(candidates) > 5 else ""
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"The upload holds {len(candidates)} skills ({listed}{suffix}). "
+ "Upload one skill folder at a time."
+ ),
+ )
+
+ found = candidates[0]
+ # The loader looks for the exact name ``SKILL.md``. A drop from a
+ # case-insensitive filesystem may spell it ``Skill.md``; renaming here
+ # keeps that upload working instead of failing on a detail nobody typed.
+ if found.name != "SKILL.md":
+ renamed = found.with_name("SKILL.md")
+ try:
+ found.replace(renamed)
+ except OSError as exc:
+ raise HTTPException(
+ status_code=500,
+ detail=f"Could not normalize {found.name}: {exc}",
+ ) from exc
+ found = renamed
+ return found.parent
+
+
+def _describe_staged_skill(folder: Path, reg: Any) -> dict[str, Any]:
+ """What this upload would install — read, parsed, but nothing written.
+
+ Deliberately returns problems instead of raising: the inspect route feeds
+ a form the owner is still filling in, and a form that reports three issues
+ at once beats one that dies on the first.
+ """
+ from jarvis.skills.authoring.draft_writer import safe_lint_skill_body
+
+ problems: list[str] = []
+ parsed = parse_skill(folder / "SKILL.md")
+ if parsed.frontmatter is None:
+ return {
+ "skill": None,
+ "lint_findings": [],
+ "problems": [f"SKILL.md could not be read: {parsed.error}"],
+ "ready": False,
+ }
+
+ name = parsed.name
+ if name in BUILTIN_SKILL_NAMES:
+ problems.append(f"'{name}' is a built-in skill name and cannot be imported.")
+ else:
+ try:
+ reg.get(name)
+ except KeyError: # free — the normal case for a fresh upload
+ pass
+ else:
+ problems.append(f"Skill '{name}' already exists.")
+ if not _IMPORT_NAME_RE.match(name or ""):
+ problems.append(
+ f"Skill name {name!r} is not a valid slug "
+ "(letters, digits, '-', '_'; max 64 chars)."
+ )
+
+ lint_findings: list[str] = []
+ try:
+ lint_findings = list(safe_lint_skill_body(parsed.body))
+ except Exception: # noqa: BLE001 — a missing lint module must not block preview
+ lint_findings = []
+
+ fm = parsed.frontmatter
+ resources = {
+ kind: [entry for entry in (folder / kind).iterdir() if entry.is_file()]
+ for kind in RESOURCE_KINDS
+ if (folder / kind).is_dir()
+ }
+ return {
+ "skill": {
+ "name": name,
+ "description": fm.description,
+ "category": fm.category,
+ "version": fm.version,
+ "tags": list(fm.tags),
+ # A lint finding does not block the install — it lands as a draft.
+ # Saying so up front is the difference between an informed yes and
+ # a surprise.
+ "state": (
+ SkillLifecycleState.DRAFT.value if lint_findings else parsed.state.value
+ ),
+ "resource_count": sum(len(entries) for entries in resources.values()),
+ },
+ "lint_findings": lint_findings,
+ "problems": problems,
+ "ready": not problems,
+ }
+
+
[email protected]("/upload/inspect", openapi_extra={"x-jarvis-readonly": True})
+async def inspect_skill_upload(
+ request: Request,
+ files: list[UploadFile] = File(...), # noqa: B008 — FastAPI dependency default
+ paths: str | None = Form(default=None), # noqa: B008 — same
+) -> dict[str, Any]:
+ """Reports what a dropped folder or archive holds, without installing it.
+
+ This is what lets the publish form fill itself in: the upload is staged in
+ a temporary directory, parsed, then thrown away. Nothing reaches the
+ skills directory on this route.
+ """
+ import tempfile
+
+ reg = _require_registry(request)
+ entries = await read_upload_entries(files, paths)
+
+ def _work() -> dict[str, Any]:
+ with tempfile.TemporaryDirectory(prefix="jarvis-skill-inspect-") as tmp:
+ try:
+ staged = stage_upload(entries, Path(tmp) / "skill")
+ except UploadRejected as exc:
+ raise upload_http_error(exc) from exc
+ folder = _locate_skill_root(staged.root)
+ described = _describe_staged_skill(folder, reg)
+ # Paths are reported relative to the located skill root, so the UI
+ # shows what will be installed rather than what was dropped.
+ described["files"] = sorted(
+ str(path.relative_to(folder)).replace("\\", "/")
+ for path in folder.rglob("*")
+ if path.is_file()
+ )
+ described["ignored"] = list(staged.ignored)
+ described["stripped_root"] = staged.stripped_root
+ described["total_bytes"] = staged.total_bytes
+ described["limits"] = upload_limits()
+ return described
+
+ return await asyncio.to_thread(_work)
+
+
+async def upload_skill(
+ request: Request,
+ files: list[UploadFile] = File(...), # noqa: B008 — FastAPI dependency default
+ paths: str | None = Form(default=None), # noqa: B008 — same
+) -> dict[str, Any]:
+ """Installs a skill folder or archive dropped onto the UI.
+
+ Trust model matches ``POST /import-local``: the owner picked these files
+ from their own machine, so a lint-clean skill is honored as parsed, while
+ a body that fails the promotion safety lint is stamped DRAFT with the
+ findings returned. Staging (``jarvis.core.uploads``) is what keeps a
+ crafted archive from writing outside the temporary folder; the install
+ itself reuses the very same code path the local-folder import uses.
+ """
+ import tempfile
+
+ reg = _require_registry(request)
+ entries = await read_upload_entries(files, paths)
+
+ def _work() -> tuple[str, list[str], dict[str, Any]]:
+ with tempfile.TemporaryDirectory(prefix="jarvis-skill-upload-") as tmp:
+ try:
+ staged = stage_upload(entries, Path(tmp) / "skill")
+ except UploadRejected as exc:
+ raise upload_http_error(exc) from exc
+ folder = _locate_skill_root(staged.root)
+ name, lint_findings = _import_skill_folder(str(folder), reg)
+ return name, lint_findings, staged.to_json()
+
+ name, lint_findings, staged_json = await asyncio.to_thread(_work)
+
+ # A real reload rather than a dict insert, for the reason spelled out on
+ # ``/import-local``: the match index has to rebuild or the skill is listed
+ # but invisible to the paraphrase channel.
+ try:
+ await reg.reload()
+ except Exception: # noqa: BLE001 — fall back to the minimal insert
+ installed = parse_skill(user_skills_dir() / name / "SKILL.md")
+ reg._skills[name] = installed # type: ignore[attr-defined]
+
+ detail = _skill_to_detail(reg.get(name))
+ detail["lint_findings"] = lint_findings
+ detail["upload"] = staged_json
+ return detail
+
+
# NB: registered BEFORE ``/{name}`` so a ``PUT /order`` is not captured by the
# ``PUT /{name}`` path-param route (which would treat "order" as a skill name).
@router.put("/order")
diff --git a/jarvis/ui/web/upload_intake.py b/jarvis/ui/web/upload_intake.py
new file mode 100644
index 0000000000..1cbd0278d1
--- /dev/null
+++ b/jarvis/ui/web/upload_intake.py
@@ -0,0 +1,118 @@
+"""Turning a multipart upload into the ``(path, bytes)`` pairs staging wants.
+
+The browser sends one part per file. A folder drop needs the relative path of
+each file too, and ``webkitRelativePath`` is not part of what a multipart body
+carries — so the UI sends a parallel ``paths`` field holding a JSON array in
+the same order as the files.
+
+Reading happens with a ceiling rather than whole: ``UploadFile`` spools to
+disk, so an oversized upload has to be refused while it is being absorbed, not
+after. The count is checked before the first read, because refusing a dropped
+home directory should not cost two thousand file reads first.
+
+This module is deliberately the only bridge between FastAPI and
+``jarvis.core.uploads`` — the staging rules themselves stay framework-free and
+testable without a request.
+"""
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from fastapi import HTTPException, UploadFile
+
+from jarvis.core.uploads import (
+ MAX_UPLOAD_FILE_BYTES,
+ MAX_UPLOAD_FILE_COUNT,
+ MAX_UPLOAD_TOTAL_BYTES,
+ UploadRejected,
+)
+
+
+def parse_upload_paths(raw: str | None, count: int) -> list[str] | None:
+ """The client-supplied relative paths, or ``None`` to fall back to filenames.
+
+ A malformed value is refused rather than ignored: silently falling back
+ would flatten a folder upload into a pile of loose files, and the owner
+ would only notice once the install produced the wrong thing.
+ """
+ if raw is None or not raw.strip():
+ return None
+ try:
+ parsed = json.loads(raw)
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=400, detail=f"'paths' is not valid JSON: {exc}"
+ ) from exc
+ if not isinstance(parsed, list) or not all(isinstance(p, str) for p in parsed):
+ raise HTTPException(
+ status_code=400, detail="'paths' must be a JSON array of strings."
+ )
+ if len(parsed) != count:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"'paths' has {len(parsed)} entries but {count} files were "
+ "uploaded — they must line up."
+ ),
+ )
+ return parsed
+
+
+async def read_upload_entries(
+ files: list[UploadFile],
+ paths: str | None = None,
+) -> list[tuple[str, bytes]]:
+ """Reads the multipart parts into memory, refusing anything oversized.
+
+ Raises ``HTTPException`` — this is the request-facing edge, so the caller
+ can let the error travel untouched.
+ """
+ if not files:
+ raise HTTPException(status_code=400, detail="No files were uploaded.")
+ if len(files) > MAX_UPLOAD_FILE_COUNT:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"{len(files)} files were uploaded — the limit is "
+ f"{MAX_UPLOAD_FILE_COUNT}."
+ ),
+ )
+
+ supplied = parse_upload_paths(paths, len(files))
+ entries: list[tuple[str, bytes]] = []
+ total = 0
+ for index, upload in enumerate(files):
+ path = (supplied[index] if supplied else "") or upload.filename or ""
+ # One byte past the ceiling is enough to know it is too large, and it
+ # keeps a 2 GB drop from being absorbed before it is refused.
+ data = await upload.read(MAX_UPLOAD_FILE_BYTES + 1)
+ if len(data) > MAX_UPLOAD_FILE_BYTES:
+ limit_mb = MAX_UPLOAD_FILE_BYTES // (1024 * 1024)
+ raise HTTPException(
+ status_code=413,
+ detail=f"'{path or upload.filename}' is larger than {limit_mb} MB.",
+ )
+ total += len(data)
+ if total > MAX_UPLOAD_TOTAL_BYTES:
+ limit_mb = MAX_UPLOAD_TOTAL_BYTES // (1024 * 1024)
+ raise HTTPException(
+ status_code=413,
+ detail=f"The upload is larger than {limit_mb} MB in total.",
+ )
+ entries.append((path, data))
+ return entries
+
+
+def upload_http_error(exc: UploadRejected) -> HTTPException:
+ """The staging rejection, as the HTTP answer the owner will read."""
+ return HTTPException(status_code=exc.status_code, detail=exc.message)
+
+
+def upload_limits() -> dict[str, Any]:
+ """The ceilings, so the UI can state them instead of guessing."""
+ return {
+ "max_file_bytes": MAX_UPLOAD_FILE_BYTES,
+ "max_total_bytes": MAX_UPLOAD_TOTAL_BYTES,
+ "max_file_count": MAX_UPLOAD_FILE_COUNT,
+ }
diff --git a/tests/unit/core/test_uploads.py b/tests/unit/core/test_uploads.py
new file mode 100644
index 0000000000..7e34d3fa28
--- /dev/null
+++ b/tests/unit/core/test_uploads.py
@@ -0,0 +1,288 @@
+"""``jarvis.core.uploads`` — the one place that decides what an upload may be.
+
+Every path in an upload comes from the browser, so the interesting cases are
+the hostile ones: a crafted archive entry that walks out of the staging
+folder, a zip bomb, a drop of an entire home directory. The staging call has
+to refuse those on the archive's own headers, before a byte lands on disk.
+
+The friendly cases matter just as much: dropping ``my-skill/`` and dropping
+its three files must produce the same result, and the OS clutter that a
+Finder or Explorer drag carries along has to disappear *visibly* rather than
+silently.
+"""
+from __future__ import annotations
+
+import io
+import tarfile
+import zipfile
+from pathlib import Path
+
+import pytest
+
+from jarvis.core import uploads
+
+
+def _zip_bytes(entries: dict[str, bytes]) -> bytes:
+ buffer = io.BytesIO()
+ # Deflated, like every archive a real tool produces — and the only way the
+ # zip-bomb fixture below can stay small on the wire while declaring a huge
+ # uncompressed size.
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ for path, data in entries.items():
+ archive.writestr(path, data)
+ return buffer.getvalue()
+
+
+def _targz_bytes(entries: dict[str, bytes]) -> bytes:
+ buffer = io.BytesIO()
+ with tarfile.open(fileobj=buffer, mode="w:gz") as archive:
+ for path, data in entries.items():
+ info = tarfile.TarInfo(path)
+ info.size = len(data)
+ archive.addfile(info, io.BytesIO(data))
+ return buffer.getvalue()
+
+
+# ----------------------------------------------------------------------
+# Path normalisation
+# ----------------------------------------------------------------------
+
+ ("raw", "expected"),
+ [
+ ("SKILL.md", "SKILL.md"),
+ ("./SKILL.md", "SKILL.md"),
+ ("/SKILL.md", "SKILL.md"),
+ ("my-skill\\references\\guide.md", "my-skill/references/guide.md"),
+ ("my-skill//references///guide.md", "my-skill/references/guide.md"),
+ (" SKILL.md ", "SKILL.md"),
+ ],
+)
+def test_paths_are_normalised_to_posix_relatives(raw: str, expected: str) -> None:
+ assert uploads.normalize_upload_path(raw) == expected
+
+
[email protected]("raw", ["", " ", "my-skill/", "./"])
+def test_entries_without_a_usable_path_are_skipped(raw: str) -> None:
+ assert uploads.normalize_upload_path(raw) == ""
+
+
+ "raw",
+ [
+ "../evil.md",
+ "my-skill/../../evil.md",
+ "..\\..\\evil.md",
+ "C:/Users/Public/evil.md",
+ "C:\\Windows\\system32\\evil.md",
+ ],
+)
+def test_a_path_that_leaves_the_folder_is_refused(raw: str) -> None:
+ with pytest.raises(uploads.UploadRejected):
+ uploads.normalize_upload_path(raw)
+
+
+# ----------------------------------------------------------------------
+# Metadata filtering and root stripping
+# ----------------------------------------------------------------------
+
+ "path",
+ [
+ ".git/config",
+ "my-skill/.git/HEAD",
+ "__MACOSX/._SKILL.md",
+ ".DS_Store",
+ "references/.DS_Store",
+ "Thumbs.db",
+ "desktop.ini",
+ "._SKILL.md",
+ ],
+)
+def test_os_clutter_is_recognised(path: str) -> None:
+ assert uploads.is_local_metadata_path(path)
+
+
[email protected]("path", ["SKILL.md", "references/guide.md", ".clawignore"])
+def test_real_files_are_not_clutter(path: str) -> None:
+ assert not uploads.is_local_metadata_path(path)
+
+
+def test_a_shared_top_level_folder_is_stripped() -> None:
+ stripped, root = uploads.strip_shared_root(
+ ["my-skill/SKILL.md", "my-skill/references/guide.md"]
+ )
+ assert stripped == ["SKILL.md", "references/guide.md"]
+ assert root == "my-skill"
+
+
+def test_two_top_level_folders_are_kept_as_they_are() -> None:
+ paths = ["a/SKILL.md", "b/SKILL.md"]
+ stripped, root = uploads.strip_shared_root(paths)
+ assert stripped == paths
+ assert root is None
+
+
+def test_a_file_at_the_root_stops_stripping() -> None:
+ paths = ["SKILL.md", "references/guide.md"]
+ stripped, root = uploads.strip_shared_root(paths)
+ assert stripped == paths
+ assert root is None
+
+
+# ----------------------------------------------------------------------
+# Staging a folder drop
+# ----------------------------------------------------------------------
+
+def test_a_folder_drop_lands_on_disk_without_its_wrapper(tmp_path: Path) -> None:
+ staged = uploads.stage_upload(
+ [
+ ("my-skill/SKILL.md", b"---\nname: x\n---\n"),
+ ("my-skill/references/guide.md", b"ref"),
+ ],
+ tmp_path / "staged",
+ )
+
+ assert staged.stripped_root == "my-skill"
+ assert staged.files == ("SKILL.md", "references/guide.md")
+ assert (staged.root / "SKILL.md").read_bytes() == b"---\nname: x\n---\n"
+ assert (staged.root / "references" / "guide.md").read_bytes() == b"ref"
+ assert staged.total_bytes == len(b"---\nname: x\n---\n") + len(b"ref")
+
+
+def test_dropping_the_contents_gives_the_same_result(tmp_path: Path) -> None:
+ """The wrapper folder must not change what gets installed."""
+ wrapped = uploads.stage_upload(
+ [("my-skill/SKILL.md", b"body"), ("my-skill/scripts/run.py", b"code")],
+ tmp_path / "wrapped",
+ )
+ flat = uploads.stage_upload(
+ [("SKILL.md", b"body"), ("scripts/run.py", b"code")],
+ tmp_path / "flat",
+ )
+ assert wrapped.files == flat.files
+
+
+def test_clutter_is_dropped_and_reported(tmp_path: Path) -> None:
+ staged = uploads.stage_upload(
+ [
+ ("SKILL.md", b"body"),
+ (".DS_Store", b"junk"),
+ (".git/config", b"junk"),
+ ("__MACOSX/._SKILL.md", b"junk"),
+ ],
+ tmp_path / "staged",
+ )
+
+ assert staged.files == ("SKILL.md",)
+ assert set(staged.ignored) == {".DS_Store", ".git/config", "__MACOSX/._SKILL.md"}
+ assert not (staged.root / ".git").exists()
+
+
+def test_ignored_paths_speak_the_same_language_as_kept_ones(tmp_path: Path) -> None:
+ """Both lists are shown side by side — they must use the same paths."""
+ staged = uploads.stage_upload(
+ [
+ ("my-skill/SKILL.md", b"body"),
+ ("my-skill/references/.DS_Store", b"junk"),
+ # Sitting NEXT to the wrapper, not inside it: keeps its own name.
+ ("__MACOSX/._my-skill", b"junk"),
+ ],
+ tmp_path / "staged",
+ )
+
+ assert staged.stripped_root == "my-skill"
+ assert staged.files == ("SKILL.md",)
+ assert set(staged.ignored) == {"references/.DS_Store", "__MACOSX/._my-skill"}
+
+
+def test_an_upload_of_only_clutter_is_refused(tmp_path: Path) -> None:
+ with pytest.raises(uploads.UploadRejected):
+ uploads.stage_upload([(".DS_Store", b"junk")], tmp_path / "staged")
+
+
+def test_an_empty_upload_is_refused(tmp_path: Path) -> None:
+ with pytest.raises(uploads.UploadRejected):
+ uploads.stage_upload([], tmp_path / "staged")
+
+
+def test_a_traversal_entry_rejects_the_whole_upload(tmp_path: Path) -> None:
+ with pytest.raises(uploads.UploadRejected):
+ uploads.stage_upload(
+ [("SKILL.md", b"body"), ("../escaped.md", b"evil")],
+ tmp_path / "staged",
+ )
+ assert not (tmp_path / "escaped.md").exists()
+
+
+def test_an_oversized_file_is_refused(tmp_path: Path) -> None:
+ oversized = b"x" * (uploads.MAX_UPLOAD_FILE_BYTES + 1)
+ with pytest.raises(uploads.UploadRejected) as exc:
+ uploads.stage_upload([("big.bin", oversized)], tmp_path / "staged")
+ assert "10 MB" in exc.value.message
+
+
+def test_too_many_files_are_refused(tmp_path: Path) -> None:
+ entries = [(f"f{i}.txt", b"x") for i in range(uploads.MAX_UPLOAD_FILE_COUNT + 1)]
+ with pytest.raises(uploads.UploadRejected) as exc:
+ uploads.stage_upload(entries, tmp_path / "staged")
+ assert str(uploads.MAX_UPLOAD_FILE_COUNT) in exc.value.message
+
+
+# ----------------------------------------------------------------------
+# Staging an archive
+# ----------------------------------------------------------------------
+
[email protected]("name", ["bundle.zip", "bundle.tar.gz", "bundle.tgz"])
+def test_archive_names_are_recognised(name: str) -> None:
+ assert uploads.is_archive_name(name)
+ assert uploads.is_archive_name(name.upper())
+
+
+def test_a_zip_is_expanded(tmp_path: Path) -> None:
+ data = _zip_bytes({"my-skill/SKILL.md": b"body", "my-skill/notes.md": b"notes"})
+ staged = uploads.stage_upload([("my-skill.zip", data)], tmp_path / "staged")
+
+ assert staged.stripped_root == "my-skill"
+ assert set(staged.files) == {"SKILL.md", "notes.md"}
+ assert (staged.root / "SKILL.md").read_bytes() == b"body"
+
+
+def test_a_targz_is_expanded(tmp_path: Path) -> None:
+ data = _targz_bytes({"SKILL.md": b"body"})
+ staged = uploads.stage_upload([("bundle.tar.gz", data)], tmp_path / "staged")
+ assert staged.files == ("SKILL.md",)
+
+
+def test_a_zip_entry_that_walks_out_is_refused(tmp_path: Path) -> None:
+ data = _zip_bytes({"../escaped.md": b"evil"})
+ with pytest.raises(uploads.UploadRejected):
+ uploads.stage_upload([("evil.zip", data)], tmp_path / "staged")
+ assert not (tmp_path / "escaped.md").exists()
+
+
+def test_a_zip_bomb_is_refused_before_it_is_unpacked(tmp_path: Path) -> None:
+ """Highly compressible data: small on the wire, refused on its headers."""
+ data = _zip_bytes({"bomb.bin": b"\0" * (uploads.MAX_UPLOAD_FILE_BYTES + 1)})
+ assert len(data) < uploads.MAX_UPLOAD_FILE_BYTES, "fixture must stay small"
+
+ with pytest.raises(uploads.UploadRejected) as exc:
+ uploads.stage_upload([("bomb.zip", data)], tmp_path / "staged")
+ assert "10 MB" in exc.value.message
+ assert not (tmp_path / "staged" / "bomb.bin").exists()
+
+
+def test_a_broken_zip_is_refused(tmp_path: Path) -> None:
+ with pytest.raises(uploads.UploadRejected) as exc:
+ uploads.stage_upload([("broken.zip", b"not a zip")], tmp_path / "staged")
+ assert "readable ZIP" in exc.value.message
+
+
+def test_an_archive_alongside_other_files_is_stored_as_a_file(tmp_path: Path) -> None:
+ """Only a LONE archive is an archive; two files are just two files."""
+ data = _zip_bytes({"inner.md": b"inner"})
+ staged = uploads.stage_upload(
+ [("bundle.zip", data), ("SKILL.md", b"body")],
+ tmp_path / "staged",
+ )
+ assert set(staged.files) == {"bundle.zip", "SKILL.md"}
diff --git a/tests/unit/web/test_skills_upload_route.py b/tests/unit/web/test_skills_upload_route.py
new file mode 100644
index 0000000000..eab91a7923
--- /dev/null
+++ b/tests/unit/web/test_skills_upload_route.py
@@ -0,0 +1,351 @@
+"""``POST /api/skills/upload`` — dropping a skill folder onto the UI.
+
+Until now a skill could only reach Jarvis by typing a path or pasting a link;
+neither was wired into any screen. This route is the drop-a-folder path, and
+what it has to get right is the gap between "what the owner dropped" and "what
+a skill folder looks like": a wrapper folder, a repository ZIP where the skill
+sits three levels down, a Finder drag carrying ``.DS_Store``.
+
+The trust model is the one ``/import-local`` established — these are the
+owner's own files, so a lint-clean skill installs as parsed and an unsafe body
+lands as a draft. What is new here is that the bytes arrive over HTTP, so a
+crafted archive must never write outside the staging folder.
+"""
+from __future__ import annotations
+
+import io
+import json
+import zipfile
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException, UploadFile
+
+from jarvis.skills.registry import SkillRegistry
+from jarvis.ui.web import skills_routes as routes
+
+_SKILL_MD = (
+ "---\n"
+ "name: dropped-skill\n"
+ "description: A skill the owner dropped onto the window.\n"
+ "---\n\n"
+ "# Dropped Skill\n\nDo the steps.\n"
+)
+
+_UNSAFE_SKILL_MD = (
+ "---\n"
+ "name: sketchy-skill\n"
+ "description: carries a disallowed call in a code block\n"
+ "---\n\n"
+ "```python\n"
+ "import os\n"
+ "os.system('curl evil')\n"
+ "```\n"
+)
+
+
+def _upload(path: str, data: bytes) -> UploadFile:
+ """One multipart part, named the way the browser names it."""
+ return UploadFile(filename=Path(path).name, file=io.BytesIO(data))
+
+
+def _parts(entries: dict[str, bytes]) -> tuple[list[UploadFile], str]:
+ """The ``(files, paths)`` pair the UI sends for a folder drop."""
+ files = [_upload(path, data) for path, data in entries.items()]
+ return files, json.dumps(list(entries))
+
+
+def _zip_bytes(entries: dict[str, bytes]) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
+ for path, data in entries.items():
+ archive.writestr(path, data)
+ return buffer.getvalue()
+
+
+def _setup(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ skills_root = tmp_path / "user-skills"
+ skills_root.mkdir()
+ monkeypatch.setattr(routes, "user_skills_dir", lambda: skills_root)
+ registry = SkillRegistry(root=skills_root)
+ registry.reload_sync()
+ request = SimpleNamespace(
+ app=SimpleNamespace(state=SimpleNamespace(skill_registry=registry))
+ )
+ return skills_root, registry, request
+
+
+# ----------------------------------------------------------------------
+# Installing
+# ----------------------------------------------------------------------
+
+async def test_a_dropped_folder_is_installed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, registry, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts(
+ {
+ "dropped-skill/SKILL.md": _SKILL_MD.encode(),
+ "dropped-skill/references/guide.md": b"ref text",
+ }
+ )
+
+ detail = await routes.upload_skill(request, files, paths)
+
+ assert detail["name"] == "dropped-skill"
+ assert detail["state"] == "validated"
+ assert (skills_root / "dropped-skill" / "SKILL.md").is_file()
+ assert (skills_root / "dropped-skill" / "references" / "guide.md").is_file()
+ assert registry.get("dropped-skill").state.value == "validated"
+
+
+async def test_a_dropped_zip_is_installed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, _, request = _setup(tmp_path, monkeypatch)
+ archive = _zip_bytes(
+ {
+ "dropped-skill/SKILL.md": _SKILL_MD.encode(),
+ "dropped-skill/scripts/run.py": b"print('hi')",
+ }
+ )
+
+ detail = await routes.upload_skill(request, [_upload("skill.zip", archive)], None)
+
+ assert detail["name"] == "dropped-skill"
+ assert (skills_root / "dropped-skill" / "scripts" / "run.py").is_file()
+
+
+async def test_the_wrapper_folder_does_not_change_the_result(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, _, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts({"SKILL.md": _SKILL_MD.encode()})
+
+ detail = await routes.upload_skill(request, files, paths)
+
+ assert detail["name"] == "dropped-skill"
+ assert (skills_root / "dropped-skill" / "SKILL.md").is_file()
+
+
+async def test_a_skill_buried_in_a_repository_zip_is_found(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The common case: someone downloads a repo ZIP from GitHub."""
+ skills_root, _, request = _setup(tmp_path, monkeypatch)
+ archive = _zip_bytes(
+ {
+ "repo-main/README.md": b"# repo",
+ "repo-main/skills/dropped-skill/SKILL.md": _SKILL_MD.encode(),
+ }
+ )
+
+ detail = await routes.upload_skill(request, [_upload("repo.zip", archive)], None)
+
+ assert detail["name"] == "dropped-skill"
+ # Only the skill folder travels — the repository README stays behind.
+ assert (skills_root / "dropped-skill" / "SKILL.md").is_file()
+ assert not (skills_root / "dropped-skill" / "README.md").exists()
+
+
+async def test_a_lowercase_skill_md_still_installs(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, _, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts({"skill.md": _SKILL_MD.encode()})
+
+ detail = await routes.upload_skill(request, files, paths)
+
+ assert detail["name"] == "dropped-skill"
+ assert (skills_root / "dropped-skill" / "SKILL.md").is_file()
+
+
+async def test_an_unsafe_body_lands_as_a_draft_with_findings(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, _, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts({"SKILL.md": _UNSAFE_SKILL_MD.encode()})
+
+ detail = await routes.upload_skill(request, files, paths)
+
+ assert detail["state"] == "draft"
+ assert detail["lint_findings"], "the disallowed call must be reported"
+ stored = (skills_root / "sketchy-skill" / "SKILL.md").read_text(encoding="utf-8")
+ assert "state: draft" in stored
+
+
+async def test_the_clutter_that_was_dropped_is_reported(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The file count shrinks — the owner is told why, not left guessing."""
+ _, _, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts(
+ {
+ "dropped-skill/SKILL.md": _SKILL_MD.encode(),
+ "dropped-skill/.DS_Store": b"junk",
+ }
+ )
+
+ detail = await routes.upload_skill(request, files, paths)
+
+ assert detail["upload"]["ignored"] == [".DS_Store"]
+ assert detail["upload"]["stripped_root"] == "dropped-skill"
+
+
+# ----------------------------------------------------------------------
+# Refusing
+# ----------------------------------------------------------------------
+
+async def test_an_upload_without_a_skill_md_is_a_400(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _, _, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts({"notes.md": b"just notes"})
+
+ with pytest.raises(HTTPException) as exc:
+ await routes.upload_skill(request, files, paths)
+ assert exc.value.status_code == 400
+ assert "SKILL.md" in exc.value.detail
+
+
+async def test_an_upload_holding_several_skills_is_refused_by_name(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _, _, request = _setup(tmp_path, monkeypatch)
+ archive = _zip_bytes(
+ {
+ "catalog/one/SKILL.md": _SKILL_MD.encode(),
+ "catalog/two/SKILL.md": _SKILL_MD.replace(
+ "dropped-skill", "other-skill"
+ ).encode(),
+ }
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await routes.upload_skill(request, [_upload("catalog.zip", archive)], None)
+ assert exc.value.status_code == 400
+ assert "2 skills" in exc.value.detail
+ # The paths are listed, so the owner knows which two collided.
+ assert "one/SKILL.md" in exc.value.detail
+
+
+async def test_a_zip_that_walks_out_of_the_folder_is_refused(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, _, request = _setup(tmp_path, monkeypatch)
+ archive = _zip_bytes(
+ {"SKILL.md": _SKILL_MD.encode(), "../../escaped.md": b"evil"}
+ )
+
+ with pytest.raises(HTTPException) as exc:
+ await routes.upload_skill(request, [_upload("evil.zip", archive)], None)
+ assert exc.value.status_code == 400
+ assert not (tmp_path / "escaped.md").exists()
+ assert not list(skills_root.iterdir())
+
+
+async def test_a_name_collision_is_a_409(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, registry, request = _setup(tmp_path, monkeypatch)
+ installed = skills_root / "dropped-skill"
+ installed.mkdir()
+ (installed / "SKILL.md").write_text(_SKILL_MD, encoding="utf-8")
+ registry.reload_sync()
+
+ files, paths = _parts({"SKILL.md": _SKILL_MD.encode()})
+ with pytest.raises(HTTPException) as exc:
+ await routes.upload_skill(request, files, paths)
+ assert exc.value.status_code == 409
+
+
+async def test_paths_that_do_not_line_up_with_the_files_are_refused(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A silent fallback would flatten a folder into loose files."""
+ _, _, request = _setup(tmp_path, monkeypatch)
+ files = [_upload("SKILL.md", _SKILL_MD.encode())]
+
+ with pytest.raises(HTTPException) as exc:
+ await routes.upload_skill(request, files, json.dumps(["a.md", "b.md"]))
+ assert exc.value.status_code == 400
+ assert "line up" in exc.value.detail
+
+
+# ----------------------------------------------------------------------
+# Inspecting
+# ----------------------------------------------------------------------
+
+async def test_inspect_reports_the_skill_without_installing_it(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ skills_root, registry, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts(
+ {
+ "dropped-skill/SKILL.md": _SKILL_MD.encode(),
+ "dropped-skill/references/guide.md": b"ref",
+ "dropped-skill/.DS_Store": b"junk",
+ }
+ )
+
+ report = await routes.inspect_skill_upload(request, files, paths)
+
+ assert report["ready"] is True
+ assert report["problems"] == []
+ assert report["skill"]["name"] == "dropped-skill"
+ assert report["skill"]["description"].startswith("A skill the owner dropped")
+ assert set(report["files"]) == {"SKILL.md", "references/guide.md"}
+ assert report["ignored"] == [".DS_Store"]
+ assert report["limits"]["max_file_bytes"] > 0
+ # Nothing was written and nothing was registered.
+ assert not list(skills_root.iterdir())
+ with pytest.raises(KeyError):
+ registry.get("dropped-skill")
+
+
+async def test_inspect_reports_a_collision_as_a_problem_not_an_error(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The form shows every blocker at once instead of dying on the first."""
+ skills_root, registry, request = _setup(tmp_path, monkeypatch)
+ installed = skills_root / "dropped-skill"
+ installed.mkdir()
+ (installed / "SKILL.md").write_text(_SKILL_MD, encoding="utf-8")
+ registry.reload_sync()
+
+ files, paths = _parts({"SKILL.md": _SKILL_MD.encode()})
+ report = await routes.inspect_skill_upload(request, files, paths)
+
+ assert report["ready"] is False
+ assert any("already exists" in problem for problem in report["problems"])
+
+
+async def test_inspect_announces_the_draft_landing_of_an_unsafe_body(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An informed yes: the state shown is the state the install will produce."""
+ _, _, request = _setup(tmp_path, monkeypatch)
+ files, paths = _parts({"SKILL.md": _UNSAFE_SKILL_MD.encode()})
+
+ report = await routes.inspect_skill_upload(request, files, paths)
+
+ assert report["skill"]["state"] == "draft"
+ assert report["lint_findings"]
+ # A lint finding is not a blocker — it changes where the skill lands.
+ assert report["ready"] is True