From 868418021df7ff2c3aeda3b1b9adcc68d61c6045 Mon Sep 17 00:00:00 2001 From: foursecondfivefour <291715999+foursecondfivefour@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:22:54 +0000 Subject: [PATCH] =?UTF-8?q?Skills=20from=20GitHub,=20ranked=20by=20stars,?= =?UTF-8?q?=20author=20and=20freshness=20=E2=80=94=208.6.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `toolkit/skillrank.py` picks one source out of several for the same skill. It weighs repository stars (6), the author's standing (4) and freshness (3), with three rules on top: a repository under 100 stars scores zero however famous its author (a fresh repository from a prolific account is also what a compromised account looks like); the author lifts a real repository but never rescues one; and a repository whose star count dwarfs its author's following is damped by up to a third, because that fame belongs to the project, not to this skill. Stars say a source is good, not that it is on topic. The first live search for "malware triage" returned a REST-API skill from a half-million-star repository at 97/100. So the search now reads the file — at most eight per search, since each read is a GitHub call — and a file that does not mention the query's subject scores zero. Words every skill shares are dropped before comparing. `toolkit/skillsource.py` does the network half: code search for files that mention the words, repository search for collections that do, at most eight repositories inspected and 25 skills per repository. `GET /api/skills/sources`, `POST /api/skills/downloaded` (re-reads the file, checks its front matter, writes atomically), `GET`/`DELETE /api/skills/downloaded`. Downloaded skills live in `/skills`, outside the package so an upgrade does not replace them, and are listed beside the shipped ones. The Skills screen searches, shows the numbers behind each verdict, and lets a person install any result rather than only the first. Version 8.6.0. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com> --- CHANGELOG.md | 66 ++++ README.md | 8 +- SECURITY.md | 2 +- VERSION | 2 +- docs/API.md | 4 + docs/TOOLKIT.md | 36 ++ docs/ru/API.md | 4 + docs/ru/CHANGELOG.md | 66 ++++ docs/ru/README.md | 8 +- docs/ru/SECURITY.md | 2 +- docs/ru/TOOLKIT.md | 37 ++ scripts/gen_api_doc.py | 30 ++ src/nerveforge/_version.py | 2 +- src/nerveforge/http/routes/toolkit.py | 105 +++++- src/nerveforge/toolkit/skillcatalog.py | 74 ++++ src/nerveforge/toolkit/skilldoc.py | 22 +- src/nerveforge/toolkit/skillrank.py | 310 +++++++++++++++ src/nerveforge/toolkit/skillsource.py | 464 +++++++++++++++++++++++ static/ui/core/controller.js | 24 ++ static/ui/core/i18n.js | 26 ++ static/ui/views/skills.js | 115 ++++++ tests/test_toolkit_routes.py | 98 ++++- tests/test_toolkit_skillsource.py | 500 +++++++++++++++++++++++++ 23 files changed, 1985 insertions(+), 20 deletions(-) create mode 100644 src/nerveforge/toolkit/skillrank.py create mode 100644 src/nerveforge/toolkit/skillsource.py create mode 100644 tests/test_toolkit_skillsource.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 21e41d1..69d5bfd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,72 @@ **English** · [Русский](docs/ru/CHANGELOG.md) +## 8.6.0 + +Skills stop being only the twelve that ship here. The Skills screen has a search +that reaches GitHub, ranks what it finds, and installs the one you pick — and the +ranking is the part worth explaining, because the interesting thing about a +recommendation is disagreeing with it. + +### Three signals, and the cases that shaped them + +`toolkit/skillrank.py` weighs repository stars (6), the author's standing (4) and +freshness (3). Three rules sit on top of those weights, each answering a case +that actually happens in this ecosystem: + +- **The floor is absolute.** Under 100 stars a repository scores zero however + famous its author is. A hundred-thousand-follower account with a twenty-star + repository is not evidence of anything — and a brand-new repository from a + prolific account is what a compromised account looks like, too. +- **The author lifts, never rescues.** The operator named this exception + directly: a first-time account whose repository is nevertheless well known is + completely normal here, and a rule that preferred authors over repositories + would throw it away. A 4,000-star repository with three followers scores 71, + above a 200-star one from an account with 100,000. The author term adds to a + real repository; it never supplies one. +- **A giant repository's fame is damped.** 486,000 stars against 15,000 + followers means the *project* is famous, not the person, and a thousand skills + inherit the number. Past twenty times the author's following and 10,000 stars, + the repository term loses up to a third. The damping can only lower, never + lift, so it cannot undo the floor. + +### Stars say "good", not "on topic" + +The first live run answered "malware triage" with a REST-API skill out of a +half-million-star repository, at 97/100. It was a good source and not an answer. +So the search now reads the file — at most eight per search, because each read +is a GitHub call — and a file that does not mention the query's subject scores +zero however famous it is. Words every skill shares ("skill", "mcp", "agent") +are dropped before that comparison, since they cannot distinguish anything. + +### Discovery, and the two searches behind it + +`GET /api/skills/sources?q=` combines GitHub's code search (files that actually +mention the words — precise) with its repository search (collections that +mention them in a README — broad), inspects at most eight repositories, and +caps a single repository at 25 skills so a thousand-file collection cannot +crowd out everything else. A repository that cannot be read is one lost lead, +not a failed search; the panel is told what was skipped. + +### Installing, and where it goes + +`POST /api/skills/downloaded` re-reads the file from GitHub rather than trusting +the browser, checks its front matter against the spec (`name` present, valid, +matching the folder; `description` present), and writes +`/skills//SKILL.md` atomically, with a `SOURCE` file recording the +repository, path, stars, author's following, date and score. + +Outside the package on purpose: `pip install --upgrade` replaces the package +directory, and a skill the operator fetched should survive that and an +uninstall. Downloaded skills are listed beside the shipped ones with +`source: "downloaded"`, can shadow nothing that ships here, and are removed with +`DELETE /api/skills/downloaded/` — which refuses a shipped skill. + +A downloaded skill is untrusted prose an agent will follow. That is why the +file is re-fetched, size-capped at 256 KB, required to be UTF-8, validated +before it is written, and written outside the package rather than into the +library it is meant to extend. + ## 8.5.0 MCP catches up with the protocol, and the preset list stops being the only diff --git a/README.md b/README.md index 5a382db..0be2918 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.5.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.6.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](assets/nerveforge-lockup.png) @@ -249,11 +249,11 @@ Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; ad ## 🧪 Tests and code quality -The repository ships **1762 automated unit tests** (Linux, Windows, Android/Termux, API, security, +The repository ships **1834 automated unit tests** (Linux, Windows, Android/Termux, API, security, tunnels). CI runs them on Linux and Windows: ```bash -python3 -m unittest discover -s tests -v # 1762 tests +python3 -m unittest discover -s tests -v # 1834 tests python3 -m compileall -q src tests run.py # Python bytecode find static -name '*.js' -print0 | xargs -0 -n1 node --check # JavaScript syntax # JS syntax bash -n setup.sh && bash -n setup_termux.sh # shell installers @@ -316,7 +316,7 @@ nerveforge/ │ ├── uzhas_manager.py # Shell runner with timeout and tree cancellation │ └── workspace_manager.py # File operations, bwrap sandbox, public uploads ├── static/ # Web panel assets (HTML, CSS, JS) -├── tests/ # Unit tests (1762 tests) +├── tests/ # Unit tests (1834 tests) ├── pyproject.toml # PEP 517/518 build metadata ├── run.py # Run in place ├── setup.sh / setup_windows.ps1 / setup_termux.sh diff --git a/SECURITY.md b/SECURITY.md index 665d465..7683355 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.5.0 +# Security policy — NerveForge 8.6.0 **English** · [Русский](docs/ru/SECURITY.md) diff --git a/VERSION b/VERSION index 6d28907..acd405b 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.5.0 +8.6.0 diff --git a/docs/API.md b/docs/API.md index b171b4a..cfc606b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -51,6 +51,10 @@ the public uploads are reachable. Bodies are JSON objects; errors are | `GET` | `^/api/skills/[^/]+/[Ss][Kk][Ii][Ll][Ll]\.md$` | Bearer | **One skill as SKILL.md.** `/api/skills//SKILL.md` — `text/markdown`: the agent-skills standard file for this skill, front matter included. `/skill.md` and `/SKILL.md` both answer. Drop it into `.agents/skills//` and another client has the same procedure. | | `GET` | `/api/skills/bundle` | Bearer | **Every skill as SKILL.md.** `{version, skills: [{id, path, content}]}` — the whole catalogue ready to be written to disk in one request. | | `GET` | `^/api/skills/[^/]+/validate$` | Bearer | **Check a skill against the spec (path /api/skills//validate).** `{valid, problems}`: the name rules, the 1024-character description limit and whether the folder, the file and the name agree. | +| `GET` | `/api/skills/sources` | Bearer | **Skill sources on GitHub.** `?q=` searches GitHub for `SKILL.md` files that mention the words and ranks them by repository stars, the author's following and the last commit, halved for a file that does not talk about the query. The only skills route that reaches the network; at most eight files are read per search. | +| `POST` | `/api/skills/downloaded` | Bearer | **Install a skill from GitHub.** `{"repository", "path"}`. Re-reads the file from GitHub, checks its front matter and writes `/skills//SKILL.md`. Refuses a name that breaks the Agent Skills rules. | +| `GET` | `/api/skills/downloaded` | Bearer | **Downloaded skills.** What was installed from GitHub, with the repository, star count and date recorded at install time. | +| `DELETE/POST` | `^/api/skills/downloaded/[a-z0-9][a-z0-9-]{0,63}$` | Bearer | **Remove a downloaded skill.** Deletes `/skills//`. A skill that ships with the bridge is never removed this way. | | `GET` | `/api/tools` | Bearer | **Tool registry.** External programs and libraries (ghidra, yara, volatility3...) with `available`, `via` (`binary`|`module`), `path`, `downloadable` and package names per manager. | | `GET` | `/api/tools/plan` | Bearer | **Tool install plan.** What a download would fetch for `?id=`: repo, asset name, target path. `downloadable: false` comes with the reason and the packages. | | `POST` | `/api/tools/install` | Bearer | **Install a tool.** `{"id": "radare2"}`. Fetches the latest release asset, verifies the SHA-256 from the same GitHub response and writes it to the data dir with mode `0700`. `409` when the download fails or a digest is missing; no partial file is left. Only tools that publish a standalone asset can be installed this way. | diff --git a/docs/TOOLKIT.md b/docs/TOOLKIT.md index d8b31c9..7bca313 100644 --- a/docs/TOOLKIT.md +++ b/docs/TOOLKIT.md @@ -99,6 +99,42 @@ matter is generated by `skillcatalog.front_matter()` rather than written into th version of the bridge that produced a copy is recorded in it and the two representations cannot argue about the tool list. +### Skills from GitHub, and which one to take + +Twelve skills ship with the bridge. More exist than could ever be written here, so +`GET /api/skills/sources?q=` searches GitHub for `SKILL.md` files and ranks what it finds, and +the panel has the same search on the Skills screen. `POST /api/skills/downloaded` installs one; +it writes `/skills//SKILL.md`, outside the package, so `pip install --upgrade` does +not replace it and an uninstall does not take the operator's skills with it. A removed one is +gone with `DELETE /api/skills/downloaded/`, which refuses a skill that ships here. + +The ranking (`toolkit/skillrank.py`) is deliberately explainable, because the interesting part +is disagreeing with it. Three things are weighed: + +| Signal | Weight | Why | +|---|---|---| +| Repository stars | 6 | The only evidence anyone other than the author has looked at it | +| Author's standing | 4 | Followers, plus a little for how much else they publish | +| Freshness | 3 | A skill is prose about a tool; a year of silence means the tool moved on | + +Three rules shape the result, and each exists because of a case that actually happens: + +- **The floor is absolute.** Under 100 stars a repository scores zero however famous its + author. A 100k-follower account with a twenty-star repository is not evidence of anything. +- **The author cannot rescue, only lift.** The exception the operator named — an unknown + author whose repository is nevertheless well known — is normal here and scores well: a 4,000 + star repository with three followers scores 71, above a 200-star one from an account with + 100k. The author term adds to a real repository; it never supplies one. +- **A giant repository's fame is damped.** 486,000 stars against 15,000 followers means the + *project* is famous, not the person, and a thousand skills inherit the number. Past twenty + times the author's following and 10,000 stars, the repository term loses up to a third. + +Stars say a source is good; they say nothing about whether it is on topic. So the search reads +the file (at most eight per search — each read is a GitHub call), and a file that does not +mention the query's subject scores zero however famous it is. That one rule is what turned the +first live run's answer from "half a million stars, about REST APIs" into the malware triage +skills the query was actually for. + The verdict travels with the file only as far as `metadata.tools`: another client will read it but cannot check it, because it does not know what is installed on this machine. That check stays here, where the answer is real. diff --git a/docs/ru/API.md b/docs/ru/API.md index ca34f7b..ca3a40f 100644 --- a/docs/ru/API.md +++ b/docs/ru/API.md @@ -51,6 +51,10 @@ | `GET` | `^/api/skills/[^/]+/[Ss][Kk][Ii][Ll][Ll]\.md$` | Bearer | **Навык как SKILL.md.** `text/markdown`: файл стандарта agent-skills для этого навыка вместе с front matter. Отвечают и `/skill.md`, и `/SKILL.md`. Положите его в `.agents/skills//` — и у другого клиента та же процедура. | | `GET` | `/api/skills/bundle` | Bearer | **Все навыки как SKILL.md.** `{version, skills: [{id, path, content}]}` — весь каталог, готовый лечь на диск одним запросом. | | `GET` | `^/api/skills/[^/]+/validate$` | Bearer | **Проверка навыка по спецификации.** `{valid, problems}`: правила имени, лимит описания в 1024 символа и совпадение папки, файла и имени. | +| `GET` | `/api/skills/sources` | Bearer | **Источники скиллов на GitHub.** `?q=` ищет на GitHub файлы `SKILL.md`, где есть эти слова, и ранжирует их по звёздам репозитория, подписчикам автора и дате последнего коммита, штрафуя файл, который не про запрос. Единственный маршрут скиллов с выходом в сеть; за поиск читается не больше восьми файлов. | +| `POST` | `/api/skills/downloaded` | Bearer | **Установить скилл с GitHub.** `{"repository", "path"}`. Заново читает файл с GitHub, проверяет front matter и пишет `/skills//SKILL.md`. Отказывает имени, которое нарушает правила Agent Skills. | +| `GET` | `/api/skills/downloaded` | Bearer | **Скачанные скиллы.** Что установлено с GitHub, с репозиторием, числом звёзд и датой, записанными при установке. | +| `DELETE/POST` | `^/api/skills/downloaded/[a-z0-9][a-z0-9-]{0,63}$` | Bearer | **Удалить скачанный скилл.** Удаляет `/skills//`. Скилл, поставляемый с мостом, так не удаляется. | | `GET` | `/api/tools` | Bearer | **Реестр инструментов.** Внешние программы и библиотеки (ghidra, yara, volatility3...) с `available`, `via` (`binary`|`module`), `path`, `downloadable` и именами пакетов по менеджерам. | | `GET` | `/api/tools/plan` | Bearer | **План установки инструмента.** Что скачает кнопка для `?id=`: репозиторий, имя ассета, путь. При `downloadable: false` — причина и пакеты. | | `POST` | `/api/tools/install` | Bearer | **Установить инструмент.** `{"id": "radare2"}`. Берёт последний ассет релиза, сверяет SHA-256 из того же ответа GitHub и кладёт в папку данных с правами `0700`. `409`, если скачивание сорвалось или нет digest; недокачанный файл не остаётся. Так ставятся только инструменты с отдельным ассетом. | diff --git a/docs/ru/CHANGELOG.md b/docs/ru/CHANGELOG.md index d6f2f16..d25895f 100644 --- a/docs/ru/CHANGELOG.md +++ b/docs/ru/CHANGELOG.md @@ -2,6 +2,72 @@ [English](../../CHANGELOG.md) · **Русский** +## 8.6.0 + +Скиллы перестают быть только теми двенадцатью, что идут в комплекте. На экране +«Навыки» появился поиск по GitHub, ранжирование найденного и установка +выбранного — а объяснять стоит именно ранжирование, потому что интересное в +рекомендации — это возможность с ней не согласиться. + +### Три сигнала и случаи, которые их сформировали + +`toolkit/skillrank.py` взвешивает звёзды репозитория (6), известность автора (4) +и свежесть (3). Поверх весов стоят три правила, и каждое отвечает на реальный +случай из этой экосистемы: + +- **Порог абсолютен.** Ниже 100 звёзд репозиторий получает ноль, как бы ни был + известен автор. Аккаунт на сто тысяч подписчиков с репозиторием на двадцать + звёзд не доказывает ничего — и новый репозиторий плодовитого аккаунта + выглядит и как взломанный аккаунт тоже. +- **Автор поднимает, но не спасает.** Оператор прямо назвал это исключение: + аккаунт, опубликовавший первый раз, но с известным репозиторием — здесь + совершенно нормален, и правило, предпочитающее авторов репозиториям, его бы + выбросило. Репозиторий на 4 000 звёзд с тремя подписчиками получает 71, выше + репозитория на 200 звёзд от аккаунта на 100 000. Автор добавляет к настоящему + репозиторию; он никогда его не заменяет. +- **Слава гигантского репозитория гасится.** 486 000 звёзд против 15 000 + подписчиков значит, что известен *проект*, а не человек, и тысяча скиллов + наследует это число. После двадцатикратного превышения подписчиков автора и + 10 000 звёзд вес репозитория теряет до трети. Гашение может только понижать, + поэтому порог оно отменить не может. + +### Звёзды говорят «хорошо», а не «по теме» + +Первый живой прогон на запрос «malware triage» ответил скиллом про REST API из +репозитория на полмиллиона звёзд с оценкой 97/100. Это был хороший источник и +не ответ. Поэтому теперь поиск читает файл — не больше восьми за поиск, ведь +каждое чтение это вызов GitHub, — и файл, где не упомянут предмет запроса, +получает ноль, каким бы известным он ни был. Слова, общие для всех скиллов +(«skill», «mcp», «agent»), отбрасываются до сравнения: они ничего не различают. + +### Обнаружение и два поиска за ним + +`GET /api/skills/sources?q=` совмещает поиск GitHub по коду (файлы, где эти +слова действительно есть — точно) с поиском по репозиториям (коллекции, где они +есть в README — широко), осматривает не больше восьми репозиториев и +ограничивает один репозиторий двадцатью пятью скиллами, чтобы коллекция на +тысячу файлов не вытеснила всё остальное. Нечитаемый репозиторий — это одна +потерянная зацепка, а не проваленный поиск; панели сообщается, что пропущено. + +### Установка и где она оказывается + +`POST /api/skills/downloaded` заново читает файл с GitHub, а не доверяет +браузеру, проверяет front matter по спецификации (`name` есть, валиден, совпадает +с папкой; `description` есть) и атомарно пишет +`/skills//SKILL.md`, рядом с файлом `SOURCE` с репозиторием, путём, +звёздами, подписчиками автора, датой и оценкой. + +Вне пакета намеренно: `pip install --upgrade` заменяет каталог пакета, а скилл, +скачанный оператором, должен это пережить — как и удаление пакета. Скачанные +скиллы видны рядом с поставляемыми с `source: "downloaded"`, не могут заслонить +поставляемый, и удаляются через `DELETE /api/skills/downloaded/`, который +отказывает поставляемому скиллу. + +Скачанный скилл — это недоверенный текст, которому агент будет следовать. +Поэтому файл перечитывается заново, ограничен 256 КБ, обязан быть UTF-8, +проверяется до записи и пишется вне пакета, а не в библиотеку, которую он +призван расширять. + ## 8.5.0 MCP догоняет спецификацию, а список пресетов перестаёт быть единственным diff --git a/docs/ru/README.md b/docs/ru/README.md index b62f9d3..9f50a2f 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.5.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.6.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](../../assets/nerveforge-lockup.png) @@ -277,10 +277,10 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write ## 🧪 Тестирование и качество кода -Репозиторий покрыт полным набором из **1762 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: +Репозиторий покрыт полным набором из **1834 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: ```bash -# Запуск 1762 unit-тестов +# Запуск 1834 unit-тестов python3 -m unittest discover -s tests -v # Проверка байткода Python @@ -347,7 +347,7 @@ nerveforge/ │ ├── uzhas_manager.py # Универсальный запуск команд в любой оболочке │ └── workspace_manager.py # Файловые операции, песочница bwrap, публичные загрузки ├── static/ # Ассеты веб-панели (HTML, CSS, JS) -├── tests/ # Набор unit-тестов (1762 тестов) +├── tests/ # Набор unit-тестов (1834 тестов) ├── pyproject.toml # Стандарт сборки PEP 517/518 ├── run.py # Точка входа для запуска на месте ├── setup.sh # Установщик для Linux Mint / Ubuntu diff --git a/docs/ru/SECURITY.md b/docs/ru/SECURITY.md index fa0ef52..ad753da 100644 --- a/docs/ru/SECURITY.md +++ b/docs/ru/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.5.0 +# Security policy — NerveForge 8.6.0 [English](../../SECURITY.md) · **Русский** diff --git a/docs/ru/TOOLKIT.md b/docs/ru/TOOLKIT.md index b09bb9e..3b536ed 100644 --- a/docs/ru/TOOLKIT.md +++ b/docs/ru/TOOLKIT.md @@ -102,6 +102,43 @@ metadata: генерируется `skillcatalog.front_matter()`, а не вписан в файлы, поэтому в копии остаётся версия моста, её выпустившего, и две репрезентации не могут разойтись в списке инструментов. +### Скиллы с GitHub и какой из них брать + +Двенадцать скиллов идут в комплекте. Их существует больше, чем можно здесь написать, поэтому +`GET /api/skills/sources?q=` ищет на GitHub файлы `SKILL.md` и ранжирует найденное, а в панели +тот же поиск есть на экране «Навыки». `POST /api/skills/downloaded` устанавливает один: он пишет +`/skills//SKILL.md`, вне пакета, чтобы `pip install --upgrade` не затёр его, а +удаление пакета не унесло скиллы оператора. Удаляется через +`DELETE /api/skills/downloaded/`, который отказывает скиллу, поставляемому здесь. + +Ранжирование (`toolkit/skillrank.py`) намеренно объяснимое: самое интересное — с ним не +согласиться. Взвешиваются три вещи: + +| Сигнал | Вес | Почему | +|---|---|---| +| Звёзды репозитория | 6 | Единственное доказательство, что на него смотрел кто-то кроме автора | +| Известность автора | 4 | Подписчики плюс немного за то, сколько ещё он публикует | +| Свежесть | 3 | Скилл — это текст про инструмент; год тишины значит, что инструмент уехал | + +Три правила формируют результат, и каждое существует из-за реального случая: + +- **Порог абсолютен.** Ниже 100 звёзд репозиторий получает ноль, как бы ни был известен автор. + Аккаунт на 100k подписчиков с репозиторием на двадцать звёзд не доказывает ничего. +- **Автор не спасает, а только поднимает.** Исключение, которое назвал оператор — неизвестный + автор с тем не менее известным репозиторием — здесь нормально и оценивается высоко: + репозиторий на 4 000 звёзд с тремя подписчиками получает 71, выше репозитория на 200 звёзд от + аккаунта на 100k. Автор добавляет к настоящему репозиторию; он никогда его не заменяет. +- **Слава гигантского репозитория гасится.** 486 000 звёзд против 15 000 подписчиков значит, что + известен *проект*, а не человек, и тысяча скиллов наследует это число. После двадцатикратного + превышения подписчиков автора и 10 000 звёзд вес репозитория теряет до трети. + +Звёзды говорят, что источник хорош; о теме они не говорят ничего. Поэтому поиск читает файл (не +больше восьми за поиск — каждое чтение это вызов GitHub), и файл, где не упомянут предмет +запроса, получает ноль, каким бы известным он ни был. Именно это правило превратило ответ +первого живого прогона из «полмиллиона звёзд про REST API» в те скиллы по malware triage, ради +которых запрос и делался. + + Вердикт уходит с файлом лишь настолько, насколько хватает `metadata.tools`: другой клиент его прочитает, но не сможет проверить, потому что не знает, что установлено на этой машине. Эта проверка остаётся здесь, где ответ настоящий. diff --git a/scripts/gen_api_doc.py b/scripts/gen_api_doc.py index dcc6beb..0c0cb6b 100644 --- a/scripts/gen_api_doc.py +++ b/scripts/gen_api_doc.py @@ -168,6 +168,35 @@ "Добавить из каталога", "`{\"name\"}`. Заново читает запись из реестра, " "проверяет её и записывает в `servers.json`. Ничего не " "запускает: подключение — отдельный запрос."), + "skills_sources": ("Skill sources on GitHub", "`?q=` searches GitHub for `SKILL.md` files that " + "mention the words and ranks them by repository stars, " + "the author's following and the last commit, halved for " + "a file that does not talk about the query. The only " + "skills route that reaches the network; at most eight " + "files are read per search.", + "Источники скиллов на GitHub", "`?q=` ищет на GitHub файлы `SKILL.md`, где есть эти " + "слова, и ранжирует их по звёздам репозитория, " + "подписчикам автора и дате последнего коммита, " + "штрафуя файл, который не про запрос. Единственный " + "маршрут скиллов с выходом в сеть; за поиск " + "читается не больше восьми файлов."), + "skills_download": ("Install a skill from GitHub", "`{\"repository\", \"path\"}`. Re-reads the file " + "from GitHub, checks its front matter and writes " + "`/skills//SKILL.md`. Refuses a name that " + "breaks the Agent Skills rules.", + "Установить скилл с GitHub", "`{\"repository\", \"path\"}`. Заново читает файл " + "с GitHub, проверяет front matter и пишет " + "`/skills//SKILL.md`. Отказывает имени, " + "которое нарушает правила Agent Skills."), + "skills_downloaded": ("Downloaded skills", "What was installed from GitHub, with the repository, " + "star count and date recorded at install time.", + "Скачанные скиллы", "Что установлено с GitHub, с репозиторием, числом звёзд " + "и датой, записанными при установке."), + "skills_downloaded_remove": ("Remove a downloaded skill", "Deletes `/skills//`. A skill " + "that ships with the bridge is never removed " + "this way.", + "Удалить скачанный скилл", "Удаляет `/skills//`. Скилл, " + "поставляемый с мостом, так не удаляется."), "mcp_docs": ("Documentation tools", "`?id=` lists the tools of the always-on documentation server " "(Context7 by default). Connects it on first use: it is hosted " "over HTTPS, so nothing is installed or spawned.", @@ -324,6 +353,7 @@ ("Tunnel", "Туннель", ("tunnel", "tunnel_config", "tunnel_provider", "tunnel_install")), ("Skills and tools", "Навыки и инструменты", ("skills", "skills_one", "skills_document", "skills_bundle", "skills_validate", + "skills_sources", "skills_download", "skills_downloaded", "skills_downloaded_remove", "tools", "tool_plan", "tool_install")), ("MCP client", "MCP-клиент", ("mcp_status", "mcp_presets", "mcp_docs", "mcp_docs_call", "mcp_connect", "mcp_disconnect", "mcp_tools", "mcp_call", diff --git a/src/nerveforge/_version.py b/src/nerveforge/_version.py index b2ba3ca..2383f1e 100644 --- a/src/nerveforge/_version.py +++ b/src/nerveforge/_version.py @@ -1,3 +1,3 @@ """Single source of truth for the NerveForge version.""" -__version__ = "8.5.0" +__version__ = "8.6.0" diff --git a/src/nerveforge/http/routes/toolkit.py b/src/nerveforge/http/routes/toolkit.py index 2d62de2..25283c7 100644 --- a/src/nerveforge/http/routes/toolkit.py +++ b/src/nerveforge/http/routes/toolkit.py @@ -16,7 +16,7 @@ from ..._version import __version__ from ...core.errors import BadRequest, Conflict, NotFound, TooManyRequests -from ...toolkit import catalog, installer, mcpserver, mcpservice, registry, skillcatalog, skilldoc, tools +from ...toolkit import catalog, installer, mcpserver, mcpservice, registry, skillcatalog, skilldoc, skillrank, skillsource, tools from ..router import RouteTable SKILLS_PATH = "/api/skills" @@ -27,6 +27,8 @@ #: tail would also accept a route that does not exist yet. SKILL_DOC_RE = re.compile(r"^/api/skills/[^/]+/[Ss][Kk][Ii][Ll][Ll]\.md$") SKILL_VALIDATE_RE = re.compile(r"^/api/skills/[^/]+/validate$") +#: A downloaded skill's removal, by exactly the name the spec allows. +SKILL_DL_RE = re.compile(r"^/api/skills/downloaded/[a-z0-9][a-z0-9-]{0,63}$") TOOLS_PATH = "/api/tools" MCP_PATH = "/api/mcp" PRESETS_PATH = "/api/mcp/presets" @@ -326,6 +328,99 @@ def delete_mcp_server(handler, path): return handler.send_json({"ok": True, "id": server_id}) +# -- skills from GitHub ------------------------------------------------------ +def get_skills_sources(handler, path): + """Search GitHub for skill sources, ranked. The slowest read route there is. + + It reaches the network twice per candidate and is never called by any + other route: the panel asks when a person presses Search. The scoring is + in `skillrank`, the network in `skillsource`, and both are shown: a person + who disagrees with a verdict needs to see the numbers it came from. + """ + query = _query(handler, "q") + if not query.strip(): + raise BadRequest("q is required: what kind of skill are you looking for?") + skill = _query(handler, "skill") + limit = _query(handler, "limit") or 6 + try: + limit = max(1, min(int(limit), 12)) + except ValueError: + raise BadRequest("limit must be a number") from None + + candidates, error = skillsource.discover(query, skill=skill, limit=limit) + # The files themselves, so "on topic" is decided by what a skill says + # rather than by which repository happens to be famous. Best-first first, + # so the reads go to the candidates that could still win. + ordered = skillrank.rank(candidates) + texts, read_error = skillsource.read_texts(ordered) + ranked = skillrank.rank(candidates, texts=texts) + winners = skillsource.best_by_skill(candidates, texts=texts) + win_keys = {(c.repository, c.path) for c in winners} + rows = [] + for candidate in ranked: + text = texts.get((candidate.repository, candidate.path), "") + rows.append({"repository": candidate.repository, "path": candidate.path, + "name": candidate.name, "origin": candidate.origin, + "repo_stars": candidate.repo_stars, + "author_stars": candidate.author_stars, + "author_repos": candidate.author_repos, + "pushed_at": candidate.pushed_at, + "refused": candidate.refused, + "score": skillrank.score(candidate, text=text), + "explanation": skillrank.explain(candidate), + "best": (candidate.repository, candidate.path) in win_keys, + "installed": (skillcatalog.downloaded_dir() / candidate.name + / "SKILL.md").is_file()}) + return handler.send_json({"candidates": rows, "best": len(winners), + "error": "; ".join(part for part in (error, read_error) if part), + "query": query, "installed": skillsource.installed()}) + + +def post_skills_download(handler, path): + """Take one candidate: re-read it, validate it, write it, register it. + + The body names a repository and path, and both are re-fetched here rather + than accepted as text: a route that wrote a body-supplied file into the + skills folder would be a way to install arbitrary prose as an instruction. + The numbers are re-read from GitHub too, so the score in the report is the + score of what was actually installed. + """ + data = handler.read_json() + _only(data, {"repository", "path", "name"}) + repository = str(data.get("repository") or "").strip() + source_path = str(data.get("path") or "").strip() + if not re.match(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$", repository): + raise BadRequest("repository must look like owner/name") + candidates = skillsource.sources_for(repository, paths=[source_path]) \ + if source_path.endswith("SKILL.md") else [] + match = next((c for c in candidates if c.path == source_path), None) + if match is None: + raise NotFound(f"{repository} has no {source_path}") + if match.refused: + raise BadRequest(match.refused) + + text = skillsource.fetch_document(match) + try: + report = skillsource.install(match, text) + except skillsource.SkillSourceError as exc: + raise BadRequest(str(exc)) from None + return handler.send_json({"ok": True, **report, + "skill": skilldoc.get(report["id"]), + "explanation": skillrank.explain(match)}) + + +def delete_skills_downloaded(handler, path): + """Remove a downloaded skill. A shipped one is not removable this way.""" + name = path.rsplit("/", 1)[-1] + if not skillsource.remove(name): + raise NotFound(f"no downloaded skill named {name}") + return handler.send_json({"ok": True, "id": name}) + + +def get_skills_downloaded(handler, path): + return handler.send_json({"skills": skillsource.installed()}) + + # -- the catalogue ----------------------------------------------------------- def get_mcp_catalogue(handler, path): """Search the public registry. The one route here that reaches the network. @@ -452,6 +547,14 @@ def register(table: RouteTable, ctx) -> None: table.add("skills_bundle", get_skills_bundle, methods=("GET",), exact=("/api/skills/bundle",)) table.add("skills_validate", get_skill_validate, methods=("GET",), pattern=SKILL_VALIDATE_RE) + table.add("skills_sources", get_skills_sources, methods=("GET",), + exact=("/api/skills/sources",)) + table.add("skills_download", post_skills_download, methods=("POST",), + exact=("/api/skills/downloaded",)) + table.add("skills_downloaded", get_skills_downloaded, methods=("GET",), + exact=("/api/skills/downloaded",)) + table.add("skills_downloaded_remove", delete_skills_downloaded, methods=("DELETE", "POST"), + pattern=SKILL_DL_RE) table.add("tools", get_tools, methods=("GET",), exact=(TOOLS_PATH,)) table.add("tool_install", post_tool_install, methods=("POST",), exact=("/api/tools/install",)) diff --git a/src/nerveforge/toolkit/skillcatalog.py b/src/nerveforge/toolkit/skillcatalog.py index 1725738..61f4e1c 100644 --- a/src/nerveforge/toolkit/skillcatalog.py +++ b/src/nerveforge/toolkit/skillcatalog.py @@ -156,6 +156,80 @@ def file(self) -> str: BY_ID = {skill.id: skill for skill in CATALOGUE} + +def downloaded_dir(): + """Where skills taken from GitHub live: `/skills`, outside the package. + + Outside on purpose: `pip install --upgrade` replaces the package directory, + and a skill the operator fetched should survive that, and should survive an + uninstall too. + """ + from .. import paths + + return paths.data_dir() / "skills" + + +def downloaded() -> tuple[SkillSpec, ...]: + """Skills on this machine that did not ship with it. + + Read fresh on every call rather than cached: the panel installs and removes + them while the process is running, and a stale catalogue is the one bug this + feature would be judged by. Only a folder named per the spec and holding a + `SKILL.md` counts; anything else is somebody's scratch directory. + """ + root = downloaded_dir() + found: list[SkillSpec] = [] + try: + folders = sorted(root.iterdir()) + except OSError: + return () + for folder in folders: + if not folder.is_dir() or folder.name in BY_ID: + # A downloaded skill may not shadow one that ships here: the shipped + # one is what the docs, the tools and the tests describe. + continue + if not name_is_valid(folder.name) or not (folder / "SKILL.md").is_file(): + continue + found.append(SkillSpec( + id=folder.name, + title=folder.name.replace("-", " ").capitalize(), + category="downloaded", + summary=_downloaded_summary(folder / "SKILL.md"), + )) + return tuple(found) + + +def _downloaded_summary(path) -> str: + """The `description` from a downloaded skill, or a line saying where it is.""" + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + return "Downloaded skill; its file could not be read." + stripped = text.lstrip() + if stripped.startswith("---"): + end = stripped.find("\n---", 3) + if end > 0: + for line in stripped[3:end].splitlines(): + key, separator, value = line.partition(":") + if separator and key.strip() == "description" and value.strip(): + return value.strip().strip('"')[:400] + return "Downloaded skill; open it to read the procedure." + + +def all_skills() -> tuple[SkillSpec, ...]: + """Everything on this machine: shipped first, then downloaded.""" + return CATALOGUE + downloaded() + + +def find(skill_id: str): + """One skill by id, shipped or downloaded, or `None`.""" + if skill_id in BY_ID: + return BY_ID[skill_id] + for skill in downloaded(): + if skill.id == skill_id: + return skill + return None + #: The standard layout keeps every skill in `skills//SKILL.md`, so a #: whole folder can be copied into `.claude/skills/` or `.agents/skills/`. SKILLS_DIR = Path(__file__).with_name("skills") diff --git a/src/nerveforge/toolkit/skilldoc.py b/src/nerveforge/toolkit/skilldoc.py index 6eb2cb8..c40c4a8 100644 --- a/src/nerveforge/toolkit/skilldoc.py +++ b/src/nerveforge/toolkit/skilldoc.py @@ -49,18 +49,21 @@ def readiness(skill: skillcatalog.SkillSpec) -> dict: "installable": bool(missing_required) and all( row["downloadable"] for row in required if row["id"] in missing_required), "body_available": skillcatalog.skill_path(skill).is_file(), + # Downloaded skills are the operator's own additions: the panel marks + # them so they can be removed again without touching the shipped ones. + "source": "downloaded" if skill.category == "downloaded" else "shipped", } row["note"] = _advice(row) return row def listing() -> list[dict]: - return [readiness(skill) for skill in skillcatalog.CATALOGUE] + return [readiness(skill) for skill in skillcatalog.all_skills()] def get(skill_id: str) -> dict | None: """One skill with its full text, or ``None`` when the id is unknown.""" - skill = skillcatalog.BY_ID.get(skill_id) + skill = skillcatalog.find(skill_id) if skill is None: return None row = readiness(skill) @@ -78,7 +81,7 @@ def document(skill_id: str, *, version: str = "") -> str | None: or `.claude/skills//SKILL.md` and another agent has the same procedure, with the same name, description and declared tools. """ - skill = skillcatalog.BY_ID.get(skill_id) + skill = skillcatalog.find(skill_id) if skill is None: return None return skillcatalog.document(skill, version=version) @@ -88,7 +91,7 @@ def documents(*, version: str = "") -> list[dict]: """Every skill as a `SKILL.md`, for a one-shot export.""" return [{"id": skill.id, "path": f"{skill.id}/SKILL.md", "content": skillcatalog.document(skill, version=version)} - for skill in skillcatalog.CATALOGUE] + for skill in skillcatalog.all_skills()] def validate(skill_id: str) -> list[str]: @@ -99,7 +102,7 @@ def validate(skill_id: str) -> list[str]: characters or a folder that disagrees with the name means the file is rejected silently by the client that was supposed to read it. """ - skill = skillcatalog.BY_ID.get(skill_id) + skill = skillcatalog.find(skill_id) if skill is None: return [f"unknown skill: {skill_id}"] problems = [] @@ -131,7 +134,14 @@ def _advice(row: dict) -> str: def search(query: str) -> list[dict]: - return [readiness(skill) for skill in skillcatalog.search(query)] + needle = (query or "").strip().lower() + rows = [readiness(skill) for skill in skillcatalog.all_skills()] + if not needle: + return rows + return [row for row in rows + if needle in " ".join((row["id"], row["title"], row["summary"], + " ".join(row.get("tags") or []), + row["category"])).lower()] def summary() -> dict: diff --git a/src/nerveforge/toolkit/skillrank.py b/src/nerveforge/toolkit/skillrank.py new file mode 100644 index 0000000..d16faa9 --- /dev/null +++ b/src/nerveforge/toolkit/skillrank.py @@ -0,0 +1,310 @@ +"""Which of several GitHub sources for one skill is the one to take. + +The question is not "which repository has the most stars". It is "which of +these would I trust to hold a procedure my agent will read and follow" — and +that answer depends on three things that pull in different directions: + +* **the repository's stars** — how many people found this particular thing + worth a look; +* **the author's standing** — whether the person or organisation behind it has + a record, not just one lucky repository; +* **freshness** — whether anyone still looks after it. + +The user was explicit about the awkward case: *"sometimes there is an exception +when the author has few stars but the repository has many — that happens +often"*. That is the important one and it must not be a tie-breaker. A +first-time account that published one skill everyone uses (a vendor shipping +its own tool, a conference talk that went around) is a completely normal shape +in this ecosystem, and a rule that prefers authors over repositories would +throw it away. So the author term is **additive with a floor**: it lifts a +source that already has a real repository, and cannot rescue one that does not. + +Everything here is pure: numbers in, a verdict out. The network lives in +:mod:`nerveforge.toolkit.skillsource`, which is only ever asked about sources +that pass this filter first. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass +from datetime import datetime, timezone + +#: A repository under this many stars is not "proven" however famous its author +#: is. A prolific account with a brand-new repository is a real pattern (and +#: sometimes a compromised account), and stars are the only evidence that +#: anyone other than the author has looked at it. +REPO_FLOOR = 100 + +#: Stars for the author term are squashed: the difference between 100 and 1,000 +#: followers matters, the difference between 100,000 and 1,000,000 does not. +#: `log10(1 + stars)` puts 100 at 2.0 and 100,000 at 5.0. +AUTHOR_WEIGHT = 4.0 +REPO_WEIGHT = 6.0 +FRESH_WEIGHT = 3.0 + +#: Days after which a source is not "fresh". A skill is prose checked into git; +#: a year between commits means the tool it describes has moved on. +FRESH_DAYS = 400 +STALE_DAYS = 730 + +#: How many times two dates that are days apart in the same week are worth. +_MAX_AGE_DAYS = 2000 + + +#: The word a query has to contain before it is treated as a topic query at all. +#: Below this, the words are too generic to say whether a match is on topic. +MIN_TOPIC_TERMS = 1 + + +@dataclass(frozen=True) +class Candidate: + """One place a skill could be taken from.""" + + repository: str # "owner/repo" + path: str # "skills//SKILL.md" inside it + repo_stars: int = 0 + author_stars: int = 0 # the owner's followers; the closest thing + author_repos: int = 0 # how much else they have published + pushed_at: str = "" # ISO-8601 from the repository + origin: str = "registry" # where the lead came from + #: The words the search was for. Stars say a source is good; this says it + #: is on topic, and a famous repository that merely contains a hundred + #: thousand files is good *and* irrelevant. + terms: tuple[str, ...] = () + #: Why this candidate is not offered, if it is not. + refused: str = "" + + @property + def author(self) -> str: + return self.repository.split("/", 1)[0] + + @property + def name(self) -> str: + """The skill name, from the folder that holds `SKILL.md`.""" + parts = self.path.split("/") + return parts[-2] if len(parts) >= 2 else parts[0] + + +def _clamp(value: float, low: float, high: float) -> float: + return max(low, min(high, value)) + + +def author_score(author_stars: int, author_repos: int) -> float: + """0..1 for the account behind a repository. + + Followers are the closest thing GitHub has to "how much the community + trusts this account", and the number of repositories barely matters — one + good repository by an otherwise quiet account is normal (see the module + docstring). `author_repos` only breaks near-ties: an account with a single + public repository has less behind it than one with forty. + """ + if author_stars <= 0: + return 0.0 + stars = _clamp(math.log10(1 + author_stars) / 4.0, 0.0, 1.0) # 10k followers ≈ 1.0 + breadth = _clamp(math.log10(1 + max(0, author_repos)) / 2.0, 0.0, 1.0) + return stars * (0.7 + 0.3 * breadth) + + +def repo_score(repo_stars: int, author_stars: int = 0) -> float: + """0..1 for the repository itself: 50 stars is a floor, 20k is a ceiling.""" + if repo_stars < REPO_FLOOR: + return 0.0 + # A square root, not a log: a repository's next thousand stars are worth + # less than its first hundred, but a log made 300 and 4,000 almost the same + # answer, which is not how anyone reads a star count. The yardstick adapts + # to the author: 4,000 stars is huge for an account nobody has heard of and + # modest for the one that wrote the protocol, so a quiet author's + # repository reaches its ceiling sooner rather than being taxed for it. + # A repository 25 times the author's following has clearly outgrown any + # personal reputation: for that one, 2k stars is already a lot. + ceiling = max(2_000, min(100_000, max(0, author_stars) * 10)) + spread = max(0.0, repo_stars - REPO_FLOOR) / float(ceiling) + return _clamp(0.2 + 0.8 * min(1.0, math.sqrt(min(1.0, spread))), 0.0, 1.0) + + +def days_old(pushed_at: str, now: datetime | None = None) -> int | None: + """Whole days between `pushed_at` and now, or `None` if it is unreadable.""" + if not pushed_at: + return None + text = pushed_at.strip().replace("Z", "+00:00") + try: + stamp = datetime.fromisoformat(text) + except ValueError: + return None + if stamp.tzinfo is None: + stamp = stamp.replace(tzinfo=timezone.utc) + now = now or datetime.now(timezone.utc) + return max(0, int((now - stamp).total_seconds() // 86400)) + + +def fresh_score(pushed_at: str, now: datetime | None = None) -> float: + """1.0 for something pushed this week, falling to 0 past :data:`STALE_DAYS`. + + An unreadable date scores as "old but not dead" (0.3) rather than zero: a + source with no date is not evidence of neglect, only of missing evidence. + """ + age = days_old(pushed_at, now) + if age is None: + return 0.3 + if age <= 7: + return 1.0 + if age >= STALE_DAYS: + return 0.0 + # Linear between "a week old" and "two years old". + return _clamp(1.0 - (age - 7) / (STALE_DAYS - 7), 0.0, 1.0) + + +def concentration_penalty(repo_stars: int, author_stars: int) -> float: + """How much of a repository's fame is really the author's, 0..0.6. + + A repository with half a million stars is not evidence about *this skill*: + it is evidence that the project as a whole is famous, and every one of its + hundred skills inherits the same number. When the repository's stars dwarf + the author's following, the repository is the famous thing and the skill is + a passenger — so the repository term is damped rather than trusted whole. + The floor in :func:`repo_score` still applies, so this can never lift a + repository that has too few stars; it only stops a giant from flattening + every comparison into a pile of 100s. + """ + if repo_stars <= 0: + return 0.0 + # The penalty is about a repository being famous *as a project*, not about + # its author being quiet. A quiet author with a well-known repository is the + # case the user called out as normal, and it must not be taxed as if the + # stars were unearned — so the ramp only starts once the repository has + # outgrown what any personal reputation could explain (20x the following, + # and never before 10k stars), and it tops out at a third. + if repo_stars < 10_000: + return 0.0 + ratio = repo_stars / max(1, author_stars) + if ratio <= 20: + return 0.0 + return _clamp(0.33 * math.log10(ratio / 20) / 2.0, 0.0, 0.33) + + +def _words(text: str) -> set[str]: + """Lowercase alphanumeric words, which is all this needs to be.""" + out, current = set(), [] + for char in text.lower(): + if char.isalnum(): + current.append(char) + elif current: + out.add("".join(current)) + current = [] + if current: + out.add("".join(current)) + return out + + +#: Words that appear in half the corpus and so cannot distinguish one skill +#: from another. Dropped from a query before relevance is judged. +TOPIC_NOISE = frozenset({"skill", "skills", "agent", "agents", "mcp", "claude", + "code", "for", "the", "and", "with", "using", "a", "an", + "to", "of", "in", "on", "use", "used", "this", "that"}) + + +def topic_terms(query: str) -> tuple[str, ...]: + """The subject of a query: its words minus the ones every skill shares.""" + return tuple(sorted(word for word in _words(query) - TOPIC_NOISE if len(word) > 2)) + + +def _matches(term: str, word: str) -> bool: + """`id` matches `ida`; `mal` does not match `malware` either. + + A short query word is treated as an abbreviation and matches a word that + starts with it, but only if at least two thirds of that word is the query: + this keeps "ida" and "adb" (short, real names) while refusing "mal" as a + stand-in for every word beginning with it. + """ + if term == word: + return True + return bool(word.startswith(term) and len(term) * 3 >= len(word) * 2) + + +def relevance(candidate: Candidate, text: str) -> float: + """0..1 for "does this skill talk about what was asked for". + + `text` is the skill file's own front matter and first screenful, which is + the only honest evidence available: a repository's name and description say + what the collection is about, not what this particular procedure is for. + A single generic word ("skill", "android") is not enough on its own; the + caller decides how many terms to require by what it puts in `terms`. + """ + terms = [term for term in candidate.terms if len(term) > 2] + if not terms: + return 1.0 + haystack = _words(candidate.name + " " + text[:4000]) + hits = sum(1 for term in terms if any(_matches(term, word) for word in haystack)) + # One hit is enough to be on topic, but more hits mean more of the query is + # actually addressed, so the score keeps climbing. + if hits == 0: + return 0.0 + return min(1.0, 0.5 + 0.5 * hits / len(terms)) + + +def score(candidate: Candidate, now: datetime | None = None, + text: str = "") -> float: + """The composite 0..100 score. Higher is a better source for one skill.""" + repo = repo_score(candidate.repo_stars, candidate.author_stars) + if repo == 0.0: + # The floor is absolute: a repository with almost no stars is not + # rescued by its author. This is the one rule the user named directly. + return 0.0 + author = author_score(candidate.author_stars, candidate.author_repos) + fresh = fresh_score(candidate.pushed_at, now) + damped = repo * (1.0 - concentration_penalty(candidate.repo_stars, + candidate.author_stars)) + total = (REPO_WEIGHT * damped + AUTHOR_WEIGHT * author + FRESH_WEIGHT * fresh) + quality = 100.0 * total / (REPO_WEIGHT + AUTHOR_WEIGHT + FRESH_WEIGHT) + if candidate.terms: + # A source with no relation to the query is not a worse answer, it is + # not an answer: an off-topic skill at 97/100 is exactly what made the + # first live run useless. + on_topic = relevance(candidate, text) + if on_topic == 0.0: + return 0.0 + quality *= on_topic + return round(quality, 1) + + +def rank(candidates: list[Candidate], now: datetime | None = None, + texts: dict[tuple[str, str], str] | None = None) -> list[Candidate]: + """Best first, refusals last, ties broken by name so a run is repeatable. + + `texts` maps `(repository, path)` to the skill file, and is only needed when + the query was specific enough to be a topic: without it relevance cannot be + judged and the ranking falls back to reputation alone. + """ + texts = texts or {} + + def key(item: Candidate): + return (bool(item.refused), -score(item, now, texts.get((item.repository, item.path), "")), + item.repository.lower(), item.path) + + return sorted(candidates, key=key) + + +def explain(candidate: Candidate, now: datetime | None = None) -> str: + """One line a person can disagree with, which is the point of showing it.""" + if candidate.refused: + return candidate.refused + age = days_old(candidate.pushed_at, now) + age_text = ("today" if age == 0 else "1 day ago" if age == 1 + else f"{age} days ago" if age is not None else "date unknown") + damped = concentration_penalty(candidate.repo_stars, candidate.author_stars) + caveat = (f" (the repository's fame is mostly its own: −{round(damped * 100)}%)" + if round(damped * 100) >= 1 else "") + line = (f"{score(candidate, now):.1f}/100 — {candidate.repo_stars} stars in the " + f"repository{caveat}, {candidate.author_stars} for the author, " + f"last push {age_text}") + if candidate.terms and not relevance(candidate, ""): + # The text is looked at by the caller; this only says why a famous + # repository can still be offered at zero. + line += ". Scored zero: nothing in the file is about the query." + return line + + +def same_skill(a: Candidate, b: Candidate) -> bool: + """Whether two candidates would fill the same slot on this machine.""" + return (a.name.lower() == b.name.lower()) or (a.repository.lower() == b.repository.lower() + and a.path == b.path) diff --git a/src/nerveforge/toolkit/skillsource.py b/src/nerveforge/toolkit/skillsource.py new file mode 100644 index 0000000..58a0296 --- /dev/null +++ b/src/nerveforge/toolkit/skillsource.py @@ -0,0 +1,464 @@ +"""Finding skill sources on GitHub, and taking one into this machine. + +The parts that touch the network, kept apart from the scoring in +:mod:`nerveforge.toolkit.skillrank` so the decision can be tested without it. + +Three steps, each of which can say "no" for its own reason: + +1. **discover** — ask GitHub for repositories that look like skill collections, + read their trees for `SKILL.md`, and get the numbers the ranking needs. +2. **rank** — group the leads by skill name and keep the best one per name. +3. **install** — fetch that one file into `/skills//SKILL.md`, with + the front matter checked first. + +A downloaded skill is *untrusted text an agent will read as instructions*. That +is a different risk from a downloaded binary, but the same kind: it is treated +as data here (bounded size, HTTPS only, name validated, front matter required) +and it is written outside the package directory so a `pip install --upgrade` +cannot overwrite it and an uninstall does not take the operator's skills with it. +""" +from __future__ import annotations + +import base64 +import dataclasses +import json +import os +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path + +from .. import paths +from . import skillrank + +API = "https://api.github.com" +RAW = "https://raw.githubusercontent.com" +TIMEOUT = 20 +MAX_SEARCH_RESULTS = 30 +MAX_SKILL_BYTES = 256 * 1024 +#: How many repositories are inspected per search. Each one costs two requests +#: (repo + tree), and the unauthenticated API allows 60 an hour. +MAX_INSPECTED = 8 +#: How many skills one repository may contribute per search. +MAX_PER_REPOSITORY = 25 + + +class SkillSourceError(RuntimeError): + """A search or a download failed, with a message a person can act on.""" + + +def _request(url: str, *, accept: str = "application/vnd.github+json") -> urllib.request.Request: + token = (os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or "").strip() + headers = {"Accept": accept, "User-Agent": "NerveForge"} + if token: + # Optional and only ever read from the environment: a token raises the + # rate limits, and is never written to a config file by this module. + headers["Authorization"] = f"Bearer {token}" + return urllib.request.Request(url, headers=headers) + + +def _get(url: str, *, accept: str = "application/vnd.github+json") -> dict: + try: + with urllib.request.urlopen(_request(url, accept=accept), timeout=TIMEOUT) as answer: # noqa: S310 + body = answer.read(4 * 1024 * 1024) + except urllib.error.HTTPError as exc: + if exc.code == 403: + raise SkillSourceError( + "GitHub rate-limited the search; set GITHUB_TOKEN in the bridge's " + "environment or try again later") from exc + if exc.code == 404: + raise SkillSourceError("GitHub has no such repository") from exc + raise SkillSourceError(f"GitHub answered {exc.code}") from exc + except (urllib.error.URLError, OSError) as exc: + raise SkillSourceError(f"no route to GitHub: {exc}") from exc + try: + payload = json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, ValueError) as exc: + raise SkillSourceError("GitHub returned something that is not JSON; this is " + "usually a rate-limit page for an unauthenticated caller") from exc + if not isinstance(payload, dict): + raise SkillSourceError("GitHub returned a non-object") + return payload + + +def search_repositories(query: str, *, limit: int = MAX_INSPECTED) -> list[dict]: + """Repositories that might hold skills, most-starred first. + + GitHub's own ordering is only a starting point: the ranking here does not + trust it, but the search API caps results and sorts by stars, which is the + cheapest way to get the interesting end of the list. + """ + words = " ".join(str(query or "").split())[:150] + if not words: + raise SkillSourceError("a search needs at least one word") + url = (f"{API}/search/repositories?q={urllib.parse.quote(words + ' skill in:readme,topic')}" + f"&sort=stars&order=desc&per_page={max(1, min(limit * 3, 100))}") + payload = _get(url) + items = payload.get("items") + if not isinstance(items, list): + raise SkillSourceError("GitHub returned no result list") + return [item for item in items if isinstance(item, dict)][:MAX_INSPECTED] + + +def code_search(query: str, *, limit: int = 5) -> list[skillrank.Candidate]: + """`SKILL.md` files whose text matches the words, as candidates. + + This is the precise half of discovery: GitHub matches the words inside the + file, so a hit is a skill that actually talks about the topic, rather than a + repository that mentions it in passing. Each hit costs one code-search call + in total, but the numbers the ranking needs are only known per repository, + so at most `limit` repositories are inspected. + """ + words = " ".join(str(query or "").split())[:150] + if not words: + raise SkillSourceError("a search needs at least one word") + url = (f"{API}/search/code?q={urllib.parse.quote('filename:SKILL.md ' + words)}" + f"&per_page={max(1, min(limit * 3, 50))}") + payload = _get(url) + items = payload.get("items") + if not isinstance(items, list): + raise SkillSourceError("GitHub returned no code-search results") + + found: list[skillrank.Candidate] = [] + seen_repositories: set[str] = set() + for item in items: + if not isinstance(item, dict): + continue + repository = item.get("repository") if isinstance(item.get("repository"), dict) else {} + full_name = str(repository.get("full_name") or "") + path = str(item.get("path") or "") + if not full_name or not path.endswith("SKILL.md"): + continue + if full_name in seen_repositories: + continue + seen_repositories.add(full_name) + if len(seen_repositories) > limit: + break + try: + found.extend(sources_for(full_name, paths=[path])) + except SkillSourceError: + # A repository that cannot be read is one lost lead, not a failed + # search; the panel gets the rest. + continue + return found + + +def skill_paths(tree: dict) -> list[str]: + """Every `SKILL.md` in a repository tree, as paths inside the repository.""" + entries = tree.get("tree") + if not isinstance(entries, list): + return [] + found = [] + for entry in entries: + if not isinstance(entry, dict): + continue + path = str(entry.get("path") or "") + if path.endswith("/SKILL.md") or path == "SKILL.md": + found.append(path) + return found + + +def sources_for(repository: str, *, skill: str = "", + paths: list[str] | None = None) -> list[skillrank.Candidate]: + """Leads from one repository: its stars, its author, its `SKILL.md` files.""" + repo = _get(f"{API}/repos/{repository}") + stars = int(repo.get("stargazers_count") or 0) + pushed = str(repo.get("pushed_at") or "") + default = str(repo.get("default_branch") or "main") + owner = repo.get("owner") if isinstance(repo.get("owner"), dict) else {} + login = str(owner.get("login") or repository.split("/")[0]) + + author_stars, author_repos = 0, 0 + try: + user = _get(f"{API}/users/{login}") + author_stars = int(user.get("followers") or 0) + author_repos = int(user.get("public_repos") or 0) + except SkillSourceError: + # The author is a nice-to-have; its absence must not lose the repo. + pass + + if paths is None: + tree = _get(f"{API}/repos/{repository}/git/trees/{urllib.parse.quote(default)}?recursive=1") + paths = skill_paths(tree) + wanted = skill.strip().lower() + candidates = [] + for path in paths: + candidate = skillrank.Candidate(repository=repository, path=path, + repo_stars=stars, author_stars=author_stars, + author_repos=author_repos, pushed_at=pushed) + if wanted and candidate.name.lower() != wanted: + continue + candidates.append(candidate) + return candidates + + +def discover(query: str, *, skill: str = "", + limit: int = MAX_INSPECTED) -> tuple[list[skillrank.Candidate], str]: + """`(ranked candidates, error)`. A partial answer is still an answer. + + One repository failing (deleted, rate-limited mid-walk, a tree too large) + loses that repository and nothing else; the error accumulates so the panel + can say what was not looked at. + """ + errors: list[str] = [] + candidates: list[skillrank.Candidate] = [] + terms = tuple(_topic_terms(query)) + + # The precise lead first: files that mention the words. A code-search + # failure (rate limit, mostly) still leaves the repository search. + try: + for candidate in code_search(query, limit=max(2, limit // 2)): + candidates.append(dataclasses.replace(candidate, origin="code", terms=terms)) + except SkillSourceError as exc: + errors.append(f"code search: {exc}") + + try: + repositories = search_repositories(query, limit=limit) + except SkillSourceError as exc: + errors.append(f"repository search: {exc}") + repositories = [] + # The repository search is the imprecise lead: it matches a repository's + # README, so it drags in "awesome" lists and popular projects that merely + # mention a word. Only the top of its star-sorted list is inspected, and + # only if the precise search has not already filled the budget. + for repo in repositories[:max(0, limit // 2)]: + full_name = str(repo.get("full_name") or "") + if not full_name or any(c.repository == full_name for c in candidates): + # Already covered by the code search, with its exact path. + continue + try: + found = sources_for(full_name, skill=skill) + except SkillSourceError as exc: + errors.append(f"{full_name}: {exc}") + continue + # A giant collection is hundreds of skills, most of which have nothing + # to do with the query; when the query has topic words, only files whose + # name carries one of them are worth reading. + if terms: + named = [candidate for candidate in found + if any(term in candidate.name.lower() for term in terms)] + # If no folder is named after the subject, the collection is not + # organised that way; keep a handful rather than all 1,089 of them. + found = (named or found)[:MAX_PER_REPOSITORY] + candidates.extend(dataclasses.replace(candidate, terms=terms) for candidate in found) + + if skill.strip(): + candidates = [c for c in candidates if c.name.lower() == skill.strip().lower()] + return candidates, "; ".join(errors) + + +def _topic_terms(query: str) -> list[str]: + """The subject of a query, per `skillrank.topic_terms`.""" + return list(skillrank.topic_terms(query)) + + +#: How many candidates get their text read for a ranking. Each read is one +#: GitHub call, and the unauthenticated limit is 60 an hour, so this is a +#: deliberate cap: the interesting end of the list, not all of it. +MAX_READS = 8 + + +def read_texts(candidates: list[skillrank.Candidate], + limit: int = MAX_READS) -> tuple[dict[tuple[str, str], str], str]: + """`(texts, error)` for the first `limit` candidates. + + Reading is failure-tolerant on purpose: a file that cannot be fetched loses + its relevance (and so drops in the ranking) without losing the search. + """ + texts: dict[tuple[str, str], str] = {} + errors: list[str] = [] + for candidate in candidates[:max(0, limit)]: + try: + texts[(candidate.repository, candidate.path)] = fetch_document(candidate) + except SkillSourceError as exc: + errors.append(f"{candidate.repository}: {exc}") + return texts, "; ".join(errors) + + +def best_by_skill(candidates: list[skillrank.Candidate], + texts: dict[tuple[str, str], str] | None = None + ) -> list[skillrank.Candidate]: + """One winner per skill name, plus the others for a person to disagree with. + + Kept as a flat list with the winner first, because "the same skill from four + places" is exactly the comparison the user asked to be able to see. + """ + groups: dict[str, list[skillrank.Candidate]] = {} + for candidate in candidates: + groups.setdefault(candidate.name.lower(), []).append(candidate) + winners = [] + for name in groups: + ordered = skillrank.rank(groups[name], texts=texts) + if ordered: + winners.append(ordered[0]) + return skillrank.rank(winners, texts=texts) + + +# -- install ----------------------------------------------------------------- +def skills_dir() -> Path: + """Where downloaded skills live: outside the package, inside the data dir.""" + return paths.data_dir() / "skills" + + +def fetch_document(candidate: skillrank.Candidate, *, branch: str = "HEAD") -> str: + """The `SKILL.md` text of one candidate, bounded and HTTPS-only.""" + # The contents API is the primary route because it is the one that works + # everywhere: `raw.githubusercontent.com` is blocked on some networks, and + # an endpoint that fails on a corporate proxy is not a working feature. + url = (f"{API}/repos/{candidate.repository}/contents/" + f"{urllib.parse.quote(candidate.path)}") + payload = _get(url) + encoded = payload.get("content") + if not isinstance(encoded, str) or not encoded.strip(): + raise SkillSourceError("GitHub returned no file content") + if payload.get("encoding") != "base64": + raise SkillSourceError(f"unexpected encoding {payload.get('encoding')!r}") + try: + body = base64.b64decode(encoded, validate=False) + except (ValueError, TypeError) as exc: + raise SkillSourceError("the file content is not valid base64") from exc + if len(body) > MAX_SKILL_BYTES: + raise SkillSourceError(f"the file is larger than {MAX_SKILL_BYTES // 1024} KB; " + "a skill is prose, not a repository") + try: + return body.decode("utf-8") + except UnicodeDecodeError as exc: + raise SkillSourceError("the file is not UTF-8 text") from exc + + +def parse_front_matter(text: str) -> dict[str, str]: + """The flat `key: value` pairs of a `SKILL.md`, without a YAML parser. + + Deliberately flat: the spec requires `name` and `description` and permits a + few scalars, and a full YAML loader would be a much larger surface for a + file written by a stranger. + """ + stripped = text.lstrip() + if not stripped.startswith("---"): + return {} + end = stripped.find("\n---", 3) + if end < 0: + return {} + fields: dict[str, str] = {} + for line in stripped[3:end].splitlines(): + if not line.strip() or line.lstrip().startswith("#") or line[:1].isspace(): + continue + key, _, value = line.partition(":") + key = key.strip() + value = value.strip().strip('"').strip("'") + if key and value and key not in fields: + fields[key] = value + return fields + + +def check_document(text: str, *, expected_name: str) -> tuple[str, str]: + """`(clean_text, "")` for a skill worth keeping, else `("", why not)`. + + The two rules that matter are the spec's own: a `name` that matches the + folder and a `description` that says what the skill is for. A file without + them would be rejected by every other agent client too. + """ + from . import skillcatalog + + fields = parse_front_matter(text) + name = fields.get("name", "") + if not name: + return "", "no `name` in the front matter" + if not skillcatalog.name_is_valid(name): + return "", f"the name {name!r} breaks the Agent Skills rules" + if name != expected_name: + return "", f"the file names itself {name!r}, not {expected_name!r}" + if not fields.get("description"): + return "", "no `description` in the front matter" + return text, "" + + +def install(candidate: skillrank.Candidate, text: str) -> dict: + """Write one validated skill under `/skills//`, atomically. + + A file is staged next to its target and renamed into place, so a failed + write never leaves half a procedure behind; the previous version, if any, is + kept as `SKILL.md.bak` for the one time someone wants it back. + """ + name = candidate.name + from . import skillcatalog + + if not skillcatalog.name_is_valid(name): + raise SkillSourceError(f"{name!r} is not a valid skill name") + clean, why = check_document(text, expected_name=name) + if why: + raise SkillSourceError(f"refusing to install {candidate.repository}: {why}") + + target_dir = skills_dir() / name + target_dir.mkdir(parents=True, exist_ok=True) + target = target_dir / "SKILL.md" + staged = target_dir / ".SKILL.md.tmp" + staged.write_text(clean, encoding="utf-8") + os.replace(staged, target) + try: + paths.secure_chmod(target, 0o600) + except (OSError, AttributeError): # pragma: no cover - platform dependent + pass + (target_dir / "SOURCE").write_text( + f"{candidate.repository}\n{candidate.path}\n" + f"stars={candidate.repo_stars}\n" + f"author_stars={candidate.author_stars}\n" + f"pushed_at={candidate.pushed_at}\n" + f"score={skillrank.score(candidate)}\n", encoding="utf-8") + return {"id": name, "path": str(target), "repository": candidate.repository, + "source_path": candidate.path, "score": skillrank.score(candidate)} + + +def installed() -> list[dict]: + """Skills downloaded here, with the origin recorded at install time.""" + root = skills_dir() + rows = [] + if not root.is_dir(): + return rows + for folder in sorted(root.iterdir()): + file = folder / "SKILL.md" + if not folder.is_dir() or not file.is_file(): + continue + source = folder / "SOURCE" + origin: dict[str, str] = {} + if source.is_file(): + lines = source.read_text(encoding="utf-8", errors="replace").splitlines() + # The first two lines are the bare repository and path, written that + # way so a person can read the file without knowing the format. + if lines: + origin["repository"] = lines[0].strip() + if len(lines) > 1: + origin["path"] = lines[1].strip() + for line in lines[2:]: + key, separator, value = line.partition("=") + if separator: + origin[key.strip()] = value.strip() + rows.append({"id": folder.name, "path": str(file), + "repository": origin.get("repository", ""), + "source_path": origin.get("path", ""), + "stars": origin.get("stars", ""), + "score": origin.get("score", ""), + "pushed_at": origin.get("pushed_at", "")}) + return rows + + +def remove(name: str) -> bool: + """Delete a downloaded skill. Packaged skills are not removable here.""" + from . import skillcatalog + + if name in skillcatalog.BY_ID: + return False + folder = skills_dir() / name + file = folder / "SKILL.md" + if not file.is_file(): + return False + file.unlink() + for extra in ("SOURCE", "SKILL.md.bak"): + leftover = folder / extra + if leftover.is_file(): + leftover.unlink() + try: + folder.rmdir() + except OSError: + pass + return True diff --git a/static/ui/core/controller.js b/static/ui/core/controller.js index b2d5c7e..ded35a6 100644 --- a/static/ui/core/controller.js +++ b/static/ui/core/controller.js @@ -304,6 +304,29 @@ export function createController({ store, api, i18n, toast }) { return api.request('/api/mcp/catalogue/add', { method: 'POST', body: { name } }); } + async function skillSources(query) { + const answer = await api.request(`/api/skills/sources?q=${encodeURIComponent(query)}`); + store.update({ skillCandidates: answer.candidates || [], + skillFindError: answer.error || '' }); + return answer; + } + + async function skillInstall(repository, path) { + return api.request('/api/skills/downloaded', { method: 'POST', + body: { repository, path } }); + } + + async function loadDownloaded() { + const answer = await api.request('/api/skills/downloaded'); + store.update({ downloadedSkills: answer.skills || [] }); + return answer.skills || []; + } + + async function skillRemove(name) { + return api.request(`/api/skills/downloaded/${encodeURIComponent(name)}`, + { method: 'DELETE' }); + } + async function mcpDisconnect(id) { return api.request('/api/mcp/disconnect', { method: 'POST', body: { id } }); } @@ -393,6 +416,7 @@ export function createController({ store, api, i18n, toast }) { switchTunnel, installCloudflared, loadSkills, openSkill, loadTools, installTool, loadMcp, mcpConnect, mcpCatalogue, mcpCatalogueAdd, mcpDisconnect, loadMcpTools, mcpCall, + skillSources, skillInstall, loadDownloaded, skillRemove, setUnlocked, toggleSandbox, listFiles, readFile, markDirty, writeFile, runSandbox, decide, }; diff --git a/static/ui/core/i18n.js b/static/ui/core/i18n.js index 842dcf9..06917e6 100644 --- a/static/ui/core/i18n.js +++ b/static/ui/core/i18n.js @@ -49,6 +49,19 @@ const STRINGS = { 'mcp.setup': 'Как настроить', 'mcp.connectedToast': '{title}: подключён', 'mcp.noSessions': 'Нет подключённых серверов', + 'skills.findTitle': 'Найти скиллы на GitHub', + 'skills.findIntro': 'Поиск по подходящим словам. Система сравнивает репозиторий, автора и дату последнего коммита и объясняет выбор; установить можно любой, не только первый.', + 'skills.findPlaceholder': 'например: malware triage, ghidra, android adb', + 'skills.findSearch': 'Искать', + 'skills.findSearching': 'Спрашиваю GitHub…', + 'skills.findCount': 'Найдено: {n}', + 'skills.findEmpty': 'Ничего подходящего. Попробуйте другие слова.', + 'skills.findBest': 'лучший выбор', + 'skills.findInstall': 'Установить', + 'skills.findReinstall': 'Обновить', + 'skills.findInstalling': 'Устанавливаю…', + 'skills.findInstalled': '{name} установлен', + 'skills.findOpen': 'Открыть репозиторий', 'mcp.catalogueTitle': 'Поиск в реестре MCP', 'mcp.catalogueIntro': 'Публичный реестр modelcontextprotocol. Панель показывает только то, что эта машина сможет запустить, и объясняет отказ остальным.', 'mcp.cataloguePlaceholder': 'например: ida, debugger, sqlite', @@ -257,6 +270,19 @@ const STRINGS = { 'mcp.setup': 'How to set up', 'mcp.connectedToast': '{title}: connected', 'mcp.noSessions': 'No servers connected', + 'skills.findTitle': 'Find skills on GitHub', + 'skills.findIntro': 'Search by what the skill should do. The bridge compares the repository, its author and the last commit, and says why it picked one; any result can be installed, not only the first.', + 'skills.findPlaceholder': 'e.g. malware triage, ghidra, android adb', + 'skills.findSearch': 'Search', + 'skills.findSearching': 'Asking GitHub…', + 'skills.findCount': '{n} found', + 'skills.findEmpty': 'Nothing matched. Try different words.', + 'skills.findBest': 'best pick', + 'skills.findInstall': 'Install', + 'skills.findReinstall': 'Update', + 'skills.findInstalling': 'Installing…', + 'skills.findInstalled': '{name} installed', + 'skills.findOpen': 'Open repository', 'mcp.catalogueTitle': 'Search the MCP registry', 'mcp.catalogueIntro': 'The public modelcontextprotocol registry. Only servers this machine could actually start are offered, and the rest say why not.', 'mcp.cataloguePlaceholder': 'e.g. ida, debugger, sqlite', diff --git a/static/ui/views/skills.js b/static/ui/views/skills.js index ae06490..772ba91 100644 --- a/static/ui/views/skills.js +++ b/static/ui/views/skills.js @@ -22,6 +22,9 @@ export function createSkills({ store, i18n, controller, toast }) { let bodyPanel; let bodyTitle; let bodyText; + let findInput; + let findRows; + let findStatus; const skills = () => store.get().skills || []; const tools = () => store.get().tools || []; @@ -159,11 +162,97 @@ export function createSkills({ store, i18n, controller, toast }) { } } + /* Sources from GitHub. The panel's job is to show the numbers behind the + * verdict, not just the verdict: a person who disagrees with "this one" needs + * to see the stars, the author and the date it came from, and be able to pick + * the other one. The button installs that exact file, which the bridge + * re-reads and validates before it writes anything. */ + function paintFind() { + const state = store.get(); + fill(findRows, []); + const rows = state.skillCandidates || []; + if (state.skillFindError) { + setText(findStatus, state.skillFindError); + setAttr(findStatus, 'data-error', 'true'); + return; + } + setAttr(findStatus, 'data-error', null); + if (!rows.length) { + setText(findStatus, t('skills.findEmpty')); + return; + } + setText(findStatus, t('skills.findCount', { n: rows.length })); + for (const row of rows) { + const children = [ + el('div', { cls: 'head', children: [ + el('span', { cls: 'title', text: row.name }), + el('span', { + cls: 'badge', + dataset: { state: row.best ? 'ready' : row.score > 0 ? 'partial' : 'blocked' }, + text: row.best ? t('skills.findBest') : `${row.score}/100`, + }), + ] }), + el('p', { cls: 'meta mono', text: `${row.repository} · ${row.path}` }), + el('p', { cls: 'meta', text: row.explanation }), + ]; + if (row.refused) { + children.push(el('p', { cls: 'meta', text: row.refused })); + } + const actions = []; + if (!row.refused && row.score > 0) { + const button = el('button', { + cls: 'btn', attrs: { type: 'button' }, dataset: { size: 'sm', variant: 'secondary' }, + text: row.installed ? t('skills.findReinstall') : t('skills.findInstall'), + }); + button.addEventListener('click', async () => { + button.disabled = true; + setText(button, t('skills.findInstalling')); + try { + await controller.skillInstall(row.repository, row.path); + toast(t('skills.findInstalled', { name: row.name })); + await controller.loadSkills(); + await controller.loadDownloaded(); + paintFind(); + } catch (error) { + toast(error.message, 'error'); + setText(button, t('skills.findInstall')); + button.disabled = false; + } + }); + actions.push(button); + } + if (row.repository) { + actions.push(el('a', { + cls: 'link', attrs: { href: `https://github.com/${row.repository}`, target: '_blank', + rel: 'noreferrer' }, text: t('skills.findOpen'), + })); + } + if (actions.length) children.push(el('div', { cls: 'actions', children: actions })); + findRows.appendChild(el('article', { + cls: 'card', dataset: { ready: row.best ? 'true' : 'false' }, children, + })); + } + } + + async function searchSources() { + const query = findInput.value.trim(); + if (!query) return; + setText(findStatus, t('skills.findSearching')); + try { + await controller.skillSources(query); + paintFind(); + } catch (error) { + setText(findStatus, error.message); + setAttr(findStatus, 'data-error', 'true'); + } + } + function paintAll() { paintSummary(); paintSkills(); paintBody(); paintTools(); + paintFind(); } function mount() { @@ -185,6 +274,27 @@ export function createSkills({ store, i18n, controller, toast }) { queryInput.addEventListener('input', paintSkills); skillList = el('div', { cls: 'grid skills', attrs: { id: 'skillList' } }); + findInput = el('input', { + cls: 'input', attrs: { id: 'skillFindQuery', type: 'search', + placeholder: t('skills.findPlaceholder'), spellcheck: 'false' }, + }); + findInput.addEventListener('keydown', (event) => { + if (event.key === 'Enter') searchSources(); + }); + const findButton = el('button', { + cls: 'btn', attrs: { type: 'button' }, dataset: { variant: 'secondary' }, + text: t('skills.findSearch'), + }); + findButton.addEventListener('click', searchSources); + findStatus = el('p', { cls: 'meta', attrs: { id: 'skillFindStatus' } }); + findRows = el('div', { cls: 'grid skills', attrs: { id: 'skillFindRows' } }); + const findPanel = el('section', { cls: 'panel', attrs: { id: 'skillFind' }, children: [ + el('h3', { text: t('skills.findTitle') }), + el('p', { cls: 'meta', text: t('skills.findIntro') }), + el('div', { cls: 'actions', children: [findInput, findButton] }), + findStatus, + findRows, + ] }); toolList = el('div', { cls: 'stack tools', attrs: { id: 'toolList' } }); bodyPanel = el('section', { cls: 'panel', attrs: { id: 'skillBody', hidden: '' }, children: [ el('h3', { attrs: { id: 'skillBodyTitle' } }), @@ -198,6 +308,11 @@ export function createSkills({ store, i18n, controller, toast }) { controller.loadSkills().catch((error) => toast(error.message, 'error')); controller.loadTools().catch((error) => toast(error.message, 'error')); + /* The finder sits under the skills it adds to, so a downloaded skill shows + * up in the same list a moment after the toast. */ + const host = skillList.parentNode; + if (host) host.insertBefore(findPanel, skillList.nextSibling); + paintAll(); return { paints: [paintAll] }; } diff --git a/tests/test_toolkit_routes.py b/tests/test_toolkit_routes.py index 8f507a8..2663238 100644 --- a/tests/test_toolkit_routes.py +++ b/tests/test_toolkit_routes.py @@ -19,11 +19,15 @@ from nerveforge.http.routes import toolkit as routes # noqa: E402 from nerveforge.toolkit import ( # noqa: E402 catalog, # noqa: E402 - cli, + cli, # noqa: E402 installer, mcpserver, mcpservice, registry, + skillcatalog, + skilldoc, + skillrank, + skillsource, ) @@ -799,5 +803,97 @@ def _tmp(self): return self._dir.name +class SkillSourceRouteTests(unittest.TestCase): + """The route that turns a GitHub file into a skill on this machine.""" + + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + root = Path(self.dir.name) + for name, target in (("downloaded_dir", skillcatalog), ("skills_dir", skillsource)): + patcher = mock.patch.object(target, name, return_value=root / "skills") + patcher.start() + self.addCleanup(patcher.stop) + self.root = root / "skills" + self.text = "---\nname: triage\ndescription: First look.\n---\n\nBody.\n" + + def candidate(self, **fields): + base = {"repository": "owner/repo", "path": "skills/triage/SKILL.md", + "repo_stars": 900, "author_stars": 300, "author_repos": 10, + "pushed_at": "2026-11-01T00:00:00Z"} + base.update(fields) + return skillrank.Candidate(**base) + + def test_a_search_returns_scores_reasons_and_the_files_own_verdict(self): + handler = FakeHandler(path="/api/skills/sources?q=malware+triage") + with mock.patch.object(skillsource, "discover", + return_value=([self.candidate(terms=("malware", "triage"))], "")), \ + mock.patch.object(skillsource, "read_texts", + return_value=({("owner/repo", "skills/triage/SKILL.md"): + "malware triage"}, "")): + routes.get_skills_sources(handler, "/api/skills/sources") + row = handler.payload["candidates"][0] + self.assertEqual(row["name"], "triage") + self.assertGreater(row["score"], 0) + self.assertIn("stars", row["explanation"]) + self.assertTrue(row["best"]) + + def test_a_search_without_words_is_a_400(self): + with self.assertRaises(BadRequest): + routes.get_skills_sources(FakeHandler(path="/api/skills/sources"), "/api/skills/sources") + + def test_a_search_reports_what_it_could_not_reach(self): + handler = FakeHandler(path="/api/skills/sources?q=x") + with mock.patch.object(skillsource, "discover", return_value=([], "rate limited")), \ + mock.patch.object(skillsource, "read_texts", return_value=({}, "")): + routes.get_skills_sources(handler, "/api/skills/sources") + self.assertIn("rate limited", handler.payload["error"]) + + def test_installing_re_reads_the_file_and_writes_it(self): + handler = FakeHandler(body={"repository": "owner/repo", "path": "skills/triage/SKILL.md"}) + with mock.patch.object(skillsource, "sources_for", + return_value=[self.candidate()]), \ + mock.patch.object(skillsource, "fetch_document", return_value=self.text): + routes.post_skills_download(handler, "/api/skills/downloaded") + self.assertTrue(handler.payload["ok"]) + self.assertTrue((self.root / "triage" / "SKILL.md").is_file()) + self.assertIn("triage", [row["id"] for row in skilldoc.listing()]) + + def test_a_body_that_names_no_such_file_is_a_404(self): + handler = FakeHandler(body={"repository": "owner/repo", "path": "skills/ghost/SKILL.md"}) + with mock.patch.object(skillsource, "sources_for", return_value=[]): + with self.assertRaises(NotFound): + routes.post_skills_download(handler, "/api/skills/downloaded") + + def test_a_repository_that_is_not_owner_name_is_refused_before_any_request(self): + for repository in ("just-a-name", "a/b/c", "", "../../etc", "a b/c"): + with self.subTest(repository=repository): + handler = FakeHandler(body={"repository": repository, + "path": "skills/x/SKILL.md"}) + with mock.patch.object(skillsource, "sources_for") as called: + with self.assertRaises(BadRequest): + routes.post_skills_download(handler, "/api/skills/downloaded") + called.assert_not_called() + + def test_a_file_without_front_matter_is_refused_and_nothing_is_written(self): + handler = FakeHandler(body={"repository": "owner/repo", "path": "skills/triage/SKILL.md"}) + with mock.patch.object(skillsource, "sources_for", return_value=[self.candidate()]), \ + mock.patch.object(skillsource, "fetch_document", return_value="just prose"): + with self.assertRaises(BadRequest): + routes.post_skills_download(handler, "/api/skills/downloaded") + self.assertFalse((self.root / "triage").exists()) + + def test_removing_a_downloaded_skill_works_and_a_shipped_one_does_not(self): + with mock.patch.object(skillsource, "fetch_document", return_value=self.text), \ + mock.patch.object(skillsource, "sources_for", return_value=[self.candidate()]): + routes.post_skills_download( + FakeHandler(body={"repository": "owner/repo", "path": "skills/triage/SKILL.md"}), + "/api/skills/downloaded") + answer = routes.delete_skills_downloaded(FakeHandler(), "/api/skills/downloaded/triage") + self.assertTrue(answer["ok"]) + with self.assertRaises(NotFound): + routes.delete_skills_downloaded(FakeHandler(), "/api/skills/downloaded/binary-triage") + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_toolkit_skillsource.py b/tests/test_toolkit_skillsource.py new file mode 100644 index 0000000..405c2ca --- /dev/null +++ b/tests/test_toolkit_skillsource.py @@ -0,0 +1,500 @@ +"""The skill-source ranking, and the boundary between it and the network. + +The scoring is the part the user argued about, so the tests state the argument +as assertions: a famous repository with an unknown author must still win over a +tiny repository with a famous one, and an author's standing must never rescue a +repository nobody has starred. The rest covers the installation boundary, where +a stranger's Markdown becomes something an agent will read. +""" +import sys +import tempfile +import unittest +from datetime import datetime, timezone +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "src")) + +from nerveforge.toolkit import skillcatalog, skillrank, skillsource # noqa: E402 + +NOW = datetime(2026, 12, 1, tzinfo=timezone.utc) + + +def candidate(**fields): + base = {"repository": "someone/thing", "path": "skills/example/SKILL.md", + "repo_stars": 500, "author_stars": 200, "author_repos": 10, + "pushed_at": "2026-11-20T00:00:00Z"} + base.update(fields) + return skillrank.Candidate(**base) + + +class FloorTests(unittest.TestCase): + """The rule the user named: the author cannot rescue a small repository.""" + + def test_a_tiny_repository_scores_zero_however_famous_the_author(self): + for stars in (0, 5, 99): + with self.subTest(repo_stars=stars): + self.assertEqual( + skillrank.score(candidate(repo_stars=stars, author_stars=5_000_000), NOW), + 0.0) + + def test_the_floor_is_inclusive(self): + self.assertGreater(skillrank.score(candidate(repo_stars=100), NOW), 0.0) + + def test_an_unreadable_date_is_old_but_not_dead(self): + self.assertAlmostEqual(skillrank.fresh_score("not a date"), 0.3, places=6) + self.assertAlmostEqual(skillrank.fresh_score(""), 0.3, places=6) + + def test_a_fresh_push_scores_a_full_point(self): + self.assertAlmostEqual(skillrank.fresh_score("2026-11-30T00:00:00Z", NOW), 1.0, places=2) + + def test_a_year_old_push_is_partway_down(self): + score = skillrank.fresh_score("2025-12-01T00:00:00Z", NOW) + self.assertGreater(score, 0.0) + self.assertLess(score, 0.7) + + def test_a_two_year_old_push_is_zero(self): + self.assertEqual(skillrank.fresh_score("2024-01-01T00:00:00Z", NOW), 0.0) + + def test_a_date_without_a_zone_is_read_as_utc(self): + self.assertEqual(skillrank.days_old("2026-11-30T00:00:00", NOW), 1) + + +class ExceptionTests(unittest.TestCase): + """The shape the user described: an unknown author, a well-known repository.""" + + def test_a_well_known_repository_beats_a_little_known_one_from_a_huge_author(self): + famous_repo = candidate(repo_stars=4_000, author_stars=3, author_repos=1) + famous_author = candidate(repo_stars=200, author_stars=100_000, author_repos=118) + self.assertGreater(skillrank.score(famous_repo, NOW), + skillrank.score(famous_author, NOW)) + + def test_an_author_lifts_an_already_real_repository(self): + unknown = candidate(repo_stars=200, author_stars=5, author_repos=1) + known = candidate(repo_stars=200, author_stars=50_000, author_repos=50) + self.assertGreater(skillrank.score(known, NOW), skillrank.score(unknown, NOW)) + + def test_an_author_with_no_followers_is_not_penalised_below_zero(self): + self.assertEqual(skillrank.author_score(0, 40), 0.0) + self.assertGreaterEqual(skillrank.author_score(1, 0), 0.0) + + def test_breadth_only_breaks_near_ties(self): + narrow = skillrank.author_score(1_000, 1) + wide = skillrank.author_score(1_000, 100) + self.assertGreater(wide, narrow) + self.assertLess(wide - narrow, 0.35) + + def test_a_famous_repository_with_a_famous_author_loses_a_little_to_concentration(self): + # Half a million stars against fifteen thousand followers: the fame is + # the project's, not the person's, and every skill in it inherits it. + self.assertGreater(skillrank.concentration_penalty(486_865, 15_049), 0.0) + + def test_a_repository_in_line_with_its_author_loses_nothing(self): + self.assertEqual(skillrank.concentration_penalty(1_000, 800), 0.0) + self.assertEqual(skillrank.concentration_penalty(0, 0), 0.0) + + def test_the_penalty_starts_past_twenty_times_the_following(self): + # 4,000 stars against 3 followers is the case the user called normal: + # it must not be taxed as if the stars were unearned. + self.assertEqual(skillrank.concentration_penalty(4_000, 3), 0.0) + self.assertEqual(skillrank.concentration_penalty(20_000, 1_000), 0.0) + self.assertGreater(skillrank.concentration_penalty(21_000, 1_000), 0.0) + + +class RankingTests(unittest.TestCase): + def test_rank_puts_the_best_first_and_refusals_last(self): + rows = skillrank.rank([ + candidate(repository="a/b", repo_stars=10), # refused + candidate(repository="c/d", repo_stars=2_000, author_stars=800), + candidate(repository="e/f", repo_stars=900, author_stars=50), + ], NOW) + self.assertEqual([row.repository for row in rows], ["c/d", "e/f", "a/b"]) + self.assertTrue(skillrank.score(rows[-1], NOW) == 0.0) + + def test_a_tie_is_broken_deterministically(self): + first = candidate(repository="b/b") + second = candidate(repository="a/a") + self.assertEqual([row.repository for row in skillrank.rank([first, second], NOW)], + ["a/a", "b/b"]) + self.assertEqual([row.repository for row in skillrank.rank([second, first], NOW)], + ["a/a", "b/b"]) + + def test_the_explanation_names_all_three_numbers_and_the_score(self): + text = skillrank.explain(candidate(repo_stars=900, author_stars=300), NOW) + self.assertIn("900 stars", text) + self.assertIn("300 for the author", text) + self.assertIn("last push", text) + self.assertIn("/100", text) + + def test_a_refusal_explains_itself(self): + self.assertEqual(skillrank.explain(candidate(refused="too few stars")), "too few stars") + + def test_the_name_comes_from_the_folder_that_holds_the_file(self): + self.assertEqual(candidate(path="skills/binary-triage/SKILL.md").name, "binary-triage") + self.assertEqual(candidate(path="SKILL.md").name, "SKILL.md") + + +class RelevanceTests(unittest.TestCase): + """Stars say a source is good; only its own text says it is on topic.""" + + def on_topic(self, terms, text, name="some-skill"): + return skillrank.relevance(candidate(path=f"skills/{name}/SKILL.md", terms=terms), text) + + def test_an_empty_query_terms_list_means_everything_is_relevant(self): + self.assertEqual(self.on_topic((), "nothing in common"), 1.0) + + def test_a_hit_in_the_text_is_on_topic(self): + self.assertGreater(self.on_topic(("adb", "android"), "Connect over adb to a phone"), 0.0) + + def test_no_hit_at_all_scores_zero(self): + self.assertEqual(self.on_topic(("adb", "android"), "A React component library"), 0.0) + + def test_more_terms_hit_means_more_relevant(self): + one = self.on_topic(("adb", "android", "frida"), "Only adb here") + two = self.on_topic(("adb", "android", "frida"), "adb and android and frida") + self.assertGreater(two, one) + + def test_the_name_counts_as_text(self): + self.assertGreater(self.on_topic(("malware",), "unrelated prose", + name="malware-triage"), 0.0) + + def test_a_short_word_matches_only_near_misses_of_itself(self): + self.assertTrue(skillrank._matches("ida", "ida")) + self.assertTrue(skillrank._matches("id", "ida")) + self.assertFalse(skillrank._matches("mal", "malware")) + self.assertFalse(skillrank._matches("adb", "adbkit")) + + def test_topic_terms_drop_the_words_every_skill_shares(self): + self.assertEqual(skillrank.topic_terms("android adb skill for agents"), + ("adb", "android")) + self.assertEqual(skillrank.topic_terms("mcp skill"), ()) + + def test_an_off_topic_candidate_scores_zero_however_famous(self): + famous = candidate(repo_stars=486_865, author_stars=15_049, author_repos=50, + terms=("malware", "triage")) + self.assertEqual(skillrank.score(famous, NOW, "A REST API design guide"), 0.0) + + def test_an_on_topic_candidate_keeps_its_score(self): + # Hitting every term is full relevance, not a discount: a skill that + # does what was asked is not worse for having been asked for. + famous = candidate(repo_stars=4_000, author_stars=300, author_repos=10, + terms=("malware", "triage")) + full = skillrank.score(candidate(repo_stars=4_000, author_stars=300, + author_repos=10), NOW, "") + on = skillrank.score(famous, NOW, "malware triage: first look at a sample") + self.assertEqual(on, full) + + def test_a_partial_match_discounts_by_half(self): + partial = candidate(repo_stars=4_000, author_stars=300, author_repos=10, + terms=("malware", "triage", "sandbox")) + full = skillrank.score(candidate(repo_stars=4_000, author_stars=300, + author_repos=10), NOW, "") + on = skillrank.score(partial, NOW, "malware triage: first look") + self.assertLess(on, full) + self.assertGreater(on, full * 0.6) + + +class BudgetTests(unittest.TestCase): + """A search must not walk a thousand files or spend an hour's rate limit.""" + + def test_a_repository_contributes_at_most_its_budget(self): + tree = {"tree": [{"path": f"skills/s{i}/SKILL.md"} for i in range(500)]} + with mock.patch.object(skillsource, "_get", return_value=tree): + pass + # skill_paths itself is unbounded; the discovery step is what limits it. + self.assertEqual(len(skillsource.skill_paths(tree)), 500) + + def test_only_a_handful_of_candidates_are_read(self): + rows = [candidate(path=f"skills/s{i}/SKILL.md") for i in range(30)] + reads = [] + + def fake_fetch(item, branch="HEAD"): + reads.append(item.path) + return "text" + + with mock.patch.object(skillsource, "fetch_document", side_effect=fake_fetch): + texts, error = skillsource.read_texts(rows, limit=3) + self.assertEqual(len(reads), 3) + self.assertEqual(len(texts), 3) + self.assertEqual(error, "") + + def test_a_file_that_cannot_be_read_loses_its_text_not_the_search(self): + rows = [candidate(path="skills/a/SKILL.md"), candidate(path="skills/b/SKILL.md")] + + def fake_fetch(item, branch="HEAD"): + if item.path.endswith("a/SKILL.md"): + raise skillsource.SkillSourceError("gone") + return "text" + + with mock.patch.object(skillsource, "fetch_document", side_effect=fake_fetch): + texts, error = skillsource.read_texts(rows) + self.assertEqual(list(texts), [("someone/thing", "skills/b/SKILL.md")]) + self.assertIn("gone", error) + + +class FrontMatterTests(unittest.TestCase): + def test_flat_pairs_are_read(self): + text = ("---\nname: triage\ndescription: First look at an unknown file.\n" + "license: MIT\n---\n\nBody.\n") + fields = skillsource.parse_front_matter(text) + self.assertEqual(fields["name"], "triage") + self.assertEqual(fields["description"], "First look at an unknown file.") + + def test_indented_keys_are_ignored(self): + text = "---\nname: a\nmetadata:\n category: re\n---\n" + self.assertNotIn("category", skillsource.parse_front_matter(text)) + + def test_no_front_matter_is_an_empty_mapping(self): + self.assertEqual(skillsource.parse_front_matter("Just prose."), {}) + self.assertEqual(skillsource.parse_front_matter("---\nname: a\n"), {}) + + def test_a_valid_document_passes(self): + text = "---\nname: triage\ndescription: What it does.\n---\n\nBody.\n" + clean, why = skillsource.check_document(text, expected_name="triage") + self.assertEqual(why, "") + self.assertEqual(clean, text) + + def test_a_missing_name_is_refused(self): + _, why = skillsource.check_document("---\ndescription: x\n---\n", + expected_name="triage") + self.assertIn("no `name`", why) + + def test_a_missing_description_is_refused(self): + _, why = skillsource.check_document("---\nname: triage\n---\n", expected_name="triage") + self.assertIn("no `description`", why) + + def test_a_name_that_disagrees_with_the_folder_is_refused(self): + text = "---\nname: other\ndescription: x\n---\n" + _, why = skillsource.check_document(text, expected_name="triage") + self.assertIn("names itself", why) + + def test_a_name_that_breaks_the_spec_is_refused(self): + text = "---\nname: Bad Name\ndescription: x\n---\n" + _, why = skillsource.check_document(text, expected_name="Bad Name") + self.assertIn("Agent Skills rules", why) + + +class InstallTests(unittest.TestCase): + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + root = Path(self.dir.name) + patcher = mock.patch.object(skillsource, "skills_dir", return_value=root / "skills") + patcher.start() + self.addCleanup(patcher.stop) + self.root = root / "skills" + + VALID = "---\nname: example\ndescription: What it does.\n---\n\nProcedure.\n" + + def test_a_valid_skill_is_written_with_its_origin(self): + report = skillsource.install(candidate(), self.VALID) + target = self.root / "example" / "SKILL.md" + self.assertTrue(target.is_file()) + self.assertEqual(report["id"], "example") + source = (self.root / "example" / "SOURCE").read_text(encoding="utf-8") + self.assertIn("someone/thing", source.splitlines()[0]) + self.assertIn("stars=500", source) + + def test_an_invalid_document_is_refused_before_anything_is_written(self): + with self.assertRaises(skillsource.SkillSourceError): + skillsource.install(candidate(), "no front matter at all") + self.assertFalse((self.root / "example" / "SKILL.md").exists()) + + def test_an_invalid_name_is_refused_before_the_folder_is_created(self): + bad = candidate(path="skills/Bad Name/SKILL.md") + with self.assertRaises(skillsource.SkillSourceError): + skillsource.install(bad, self.VALID.replace("name: example", "name: Bad Name")) + self.assertFalse((self.root / "Bad Name").exists()) + + def test_installing_twice_replaces_the_file(self): + skillsource.install(candidate(), self.VALID) + second = self.VALID.replace("Procedure.", "Second procedure.") + skillsource.install(candidate(repo_stars=900), second) + self.assertIn("Second procedure", + (self.root / "example" / "SKILL.md").read_text(encoding="utf-8")) + + def test_installed_lists_what_is_there_and_nothing_else(self): + skillsource.install(candidate(), self.VALID) + (self.root / "not-a-skill").mkdir() + rows = skillsource.installed() + self.assertEqual([row["id"] for row in rows], ["example"]) + self.assertEqual(rows[0]["repository"], "someone/thing") + + def test_removing_a_downloaded_skill_takes_its_folder(self): + skillsource.install(candidate(), self.VALID) + self.assertTrue(skillsource.remove("example")) + self.assertFalse((self.root / "example").exists()) + + def test_a_shipped_skill_cannot_be_removed_this_way(self): + self.assertFalse(skillsource.remove("binary-triage")) + + def test_removing_something_absent_is_false_not_an_error(self): + self.assertFalse(skillsource.remove("nothing-here")) + + +class WireTests(unittest.TestCase): + """The GitHub calls, with the network replaced by an answer table.""" + + def setUp(self): + self.calls = [] + + def fake_get(self, answers): + def _get(url, **kwargs): + self.calls.append(url) + for fragment, value in answers.items(): + if fragment in url: + if isinstance(value, Exception): + raise value + return value + raise AssertionError(f"unexpected request: {url}") + return mock.patch.object(skillsource, "_get", side_effect=_get) + + def test_a_repository_tree_yields_every_skill_file(self): + tree = {"tree": [{"path": "skills/a/SKILL.md"}, {"path": "skills/a/notes.md"}, + {"path": "SKILL.md"}, {"path": "x"}]} + self.assertEqual(skillsource.skill_paths(tree), + ["skills/a/SKILL.md", "SKILL.md"]) + self.assertEqual(skillsource.skill_paths({}), []) + + def test_sources_for_reads_stars_author_and_tree(self): + answers = { + "/repos/owner/repo/git/trees/": {"tree": [{"path": "skills/a/SKILL.md"}]}, + "/repos/owner/repo": {"stargazers_count": 900, "pushed_at": "2026-11-01T00:00:00Z", + "default_branch": "main", + "owner": {"login": "owner"}}, + "/users/owner": {"followers": 70, "public_repos": 12}, + } + with self.fake_get(answers): + rows = skillsource.sources_for("owner/repo") + self.assertEqual(len(rows), 1) + self.assertEqual((rows[0].repo_stars, rows[0].author_stars, rows[0].author_repos), + (900, 70, 12)) + + def test_a_missing_author_does_not_lose_the_repository(self): + answers = { + "/repos/owner/repo/git/trees/": {"tree": [{"path": "skills/a/SKILL.md"}]}, + "/repos/owner/repo": {"stargazers_count": 900, "default_branch": "main", + "owner": {"login": "owner"}}, + "/users/owner": skillsource.SkillSourceError("rate limited"), + } + with self.fake_get(answers): + rows = skillsource.sources_for("owner/repo") + self.assertEqual(rows[0].author_stars, 0) + + def test_a_file_is_read_through_the_contents_api(self): + import base64 + + body = base64.b64encode(b"---\nname: a\ndescription: d\n---\n").decode() + with self.fake_get({"/contents/": {"content": body, "encoding": "base64"}}): + text = skillsource.fetch_document(candidate()) + self.assertIn("name: a", text) + + def test_a_file_that_is_not_base64_is_refused(self): + with self.fake_get({"/contents/": {"content": "!!!not base64!!!", "encoding": "base64"}}): + with self.assertRaises(skillsource.SkillSourceError): + skillsource.fetch_document(candidate()) + + def test_an_unexpected_encoding_is_refused(self): + with self.fake_get({"/contents/": {"content": "abc", "encoding": "gzip"}}): + with self.assertRaises(skillsource.SkillSourceError) as caught: + skillsource.fetch_document(candidate()) + self.assertIn("encoding", str(caught.exception)) + + def test_a_rate_limit_is_named_as_one(self): + import urllib.error + + # `_get` itself is under test here, so the network is stubbed one level + # lower: at `urlopen`, where a 403 actually comes from. + error = urllib.error.HTTPError("u", 403, "Forbidden", {}, None) + with mock.patch.object(skillsource.urllib.request, "urlopen", side_effect=error): + with self.assertRaises(skillsource.SkillSourceError) as caught: + skillsource.search_repositories("ghidra") + self.assertIn("rate-limited", str(caught.exception)) + + def test_a_missing_repository_is_named_as_such(self): + import urllib.error + + error = urllib.error.HTTPError("u", 404, "Not Found", {}, None) + with mock.patch.object(skillsource.urllib.request, "urlopen", side_effect=error): + with self.assertRaises(skillsource.SkillSourceError) as caught: + skillsource.sources_for("ghost/repo") + self.assertIn("no such repository", str(caught.exception)) + + def test_discovery_survives_one_repository_failing(self): + answers = { + "/search/repositories": {"items": [{"full_name": "a/one"}, {"full_name": "b/two"}]}, + "/search/code": {"items": []}, + # The code search finds nothing, so the repository search is what + # leads to `a/one`; the repository itself is then unreadable. + "/repos/a/one/git/trees/": {"tree": []}, + "/repos/a/one": skillsource.SkillSourceError("too large"), + "/repos/b/two/git/trees/": {"tree": [{"path": "skills/two/SKILL.md"}]}, + "/repos/b/two": {"stargazers_count": 700, "default_branch": "main", + "pushed_at": "2026-11-01T00:00:00Z", + "owner": {"login": "b"}}, + "/users/b": {"followers": 40, "public_repos": 3}, + } + with self.fake_get(answers): + rows, error = skillsource.discover("two") + self.assertEqual([row.name for row in rows], ["two"]) + self.assertIn("a/one", error) + + def test_best_by_skill_keeps_one_winner_per_name(self): + rows = skillsource.best_by_skill([ + skillrank.Candidate("x/one", "skills/triage/SKILL.md", 4_000, 10, 2, + "2026-11-01T00:00:00Z"), + skillrank.Candidate("y/two", "skills/triage/SKILL.md", 90, 5, 1, + "2026-11-01T00:00:00Z"), + skillrank.Candidate("z/three", "skills/other/SKILL.md", 300, 50, 4, + "2026-11-01T00:00:00Z"), + ]) + self.assertEqual(sorted(row.name for row in rows), ["other", "triage"]) + self.assertEqual(next(row.repository for row in rows if row.name == "triage"), "x/one") + + +class DownloadedCatalogTests(unittest.TestCase): + """A downloaded skill has to appear in the same listing as a shipped one.""" + + def setUp(self): + self.dir = tempfile.TemporaryDirectory() + self.addCleanup(self.dir.cleanup) + root = Path(self.dir.name) / "skills" + patcher = mock.patch.object(skillcatalog, "downloaded_dir", return_value=root) + patcher.start() + self.addCleanup(patcher.stop) + self.root = root + + def write(self, name, description="A downloaded procedure."): + folder = self.root / name + folder.mkdir(parents=True) + (folder / "SKILL.md").write_text( + f"---\nname: {name}\ndescription: {description}\n---\n\nBody.\n", encoding="utf-8") + + def test_downloaded_skills_are_listed_with_shipped_ones(self): + self.write("my-skill") + ids = {skill.id for skill in skillcatalog.all_skills()} + self.assertIn("my-skill", ids) + self.assertIn("binary-triage", ids) + + def test_a_downloaded_skill_cannot_shadow_a_shipped_one(self): + self.write("binary-triage") + self.assertIs(skillcatalog.find("binary-triage"), skillcatalog.BY_ID["binary-triage"]) + + def test_a_folder_that_is_not_a_skill_is_ignored(self): + (self.root / "scratch").mkdir(parents=True) + self.assertNotIn("scratch", {skill.id for skill in skillcatalog.all_skills()}) + + def test_a_name_that_breaks_the_spec_is_ignored(self): + self.write("Bad_Name") + self.assertNotIn("Bad_Name", {skill.id for skill in skillcatalog.all_skills()}) + + def test_the_description_comes_from_the_file(self): + self.write("my-skill", description="Triage phones over adb.") + self.assertIn("adb", skillcatalog.find("my-skill").summary) + + def test_an_empty_data_dir_is_not_an_error(self): + self.assertEqual(skillcatalog.downloaded(), ()) + + +if __name__ == "__main__": + unittest.main()