diff --git a/AGENTS.md b/AGENTS.md index 72cafe6..b6407e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,6 +132,12 @@ say what is missing instead. `GET /api/tools/plan?id=` says whether a one- exists; if it does, tell the user to press it (or run `python3 -m nerveforge.toolkit --install `), and do not try to install anything yourself. +Skills are standard `SKILL.md` files (`skills//SKILL.md`), so they also work outside this +bridge: `GET /api/skills//SKILL.md` returns the same file as `text/markdown` with generated +front matter, and `GET /api/skills/bundle` returns all of them for writing into +`.agents/skills/`. Do not hand the `body` field to another agent when the file is what it needs — +the file carries `name`, `description` and the tool list in the shape a client reads. + ### Step 6 — use an MCP server, if one is configured `GET /api/mcp` lists sessions and `GET /api/mcp/presets` names what blocks each bridge. Call a tool diff --git a/CHANGELOG.md b/CHANGELOG.md index 1351cb9..43a2e5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,63 @@ **English** · [Русский](docs/ru/CHANGELOG.md) +## 8.4.0 + +Skills become files somebody else can read. The twelve procedures were already +good advice and already carried a verdict computed from what this machine has +installed; they were written in a shape only this bridge understood. They now +follow the **Agent Skills** standard (`SKILL.md`), which Claude Code, Cursor, +Codex, Copilot and the rest of the agentskills.io clients load directly. + +### One file, two audiences + +The layout moved from `skills/.md` to `skills//SKILL.md`, and the front +matter is generated by `skillcatalog.front_matter()` instead of being written by +hand: `name` (which the spec requires to match the folder, lowercase, no double +hyphens), `description` (what it does and when to use it, capped at 1024 +characters), `license`, and everything the bridge needs under `metadata` — +category, tags, required and optional tools. A test checks the rules that a +client would otherwise enforce by silently refusing the file. + +Three routes make the export real rather than nominal: + +- `GET /api/skills//SKILL.md` answers `text/markdown`, front matter included, + ready to drop into `.agents/skills//`. `/skill.md` in lowercase answers the + same thing — an agent holding one spelling should not have to discover the other. +- `GET /api/skills/bundle` returns every skill as `{id, path, content}` plus the + version that produced them, so a dozen files can be written in one request. +- `GET /api/skills//validate` reports what would stop the file from loading: + the name rules, the description limit, and whether the folder, the file and the + name agree. + +`GET /api/skills/` still returns the procedure in `body`, but now without the +YAML block: the verdict and the tool list are already fields next to it, and two +copies of one fact are one copy too many. + +### What did not travel + +`metadata.tools` goes with the file, but the *check* of it cannot: another client +does not know what is installed on this machine. So the exported skill says what +it needs and the bridge says whether it is there — `ready`, `partial`, `blocked` — +and that split is documented instead of being left to be discovered. + +### Everything else + +- `firmware-iOT` is now `firmware-iot`. The standard permits lowercase letters, + digits and single hyphens; the old name would have been rejected by the clients + this release is for. The catalog id, the folder and the docs agree. +- `pyproject.toml` ships `toolkit/skills/*/SKILL.md` as package data, so an + installed bridge has the same procedures as a checkout instead of twelve + one-line summaries. Verified against a built wheel: 12 `SKILL.md` entries. +- The old flat layout is still read if it is found, so a tree that was installed + before this release keeps working. +- `/llms.txt` and `/api/agent-prompt` gained a `skills` section and the three new + routes: an agent should be told to read a procedure before improvising the + order of steps in a reversing job. +- Routes 63 → 66, tests 1680 → 1698. `Table.resolve` now prefers an exact path, then a + pattern, then a prefix: a prefix cannot say where a path ends, and this release is the first + to add routes underneath one. + ## 8.3.0 Context7, on by default. The bridge has spoken MCP in both directions since diff --git a/README.md b/README.md index 3e008be..1c4a975 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.3.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.4.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](assets/nerveforge-lockup.png) @@ -131,6 +131,11 @@ from what is actually installed, so an agent reading `read_skill` never starts a cannot finish. On a clean container three are ready, one is one button away and eight are blocked; that is the honest answer, not a bug. +Each skill is a standard `SKILL.md` under `skills//`, in the Agent Skills layout that Claude +Code, Cursor, Codex and Copilot read, so `GET /api/skills//SKILL.md` hands the same procedure +to another agent as a file it can drop into `.agents/skills/`. The verdict stays here, because +only this machine knows what is installed on it. + **Tools** (`GET /api/tools`). 24 entries across reverse engineering, debugging, mobile, forensics and networking, each with the GitHub release asset a download would use. The **install** button and the CLI follow the same rule as cloudflared: release asset only, SHA-256 from the same API @@ -227,6 +232,7 @@ Every protected call needs `Authorization: Bearer `. | `POST /api/public/scripts` | public | Create a new `.cs` file (legacy) in the workspace root | | `POST /api/public/assets` | public | Create a text file with an allowlisted extension | | `GET /api/skills`, `GET /api/skills/` | bearer | Skill catalogue with `ready`/`partial`/`blocked` and the body of one skill | +| `GET /api/skills//SKILL.md`, `/bundle` | bearer | Portable Agent Skills files, with generated front matter | | `GET /api/tools` | bearer | Tool catalogue: what is installed, what is missing, what can be downloaded | | `POST /api/tools/install` | bearer | `{"id": "jadx"}` — download, verify the SHA-256, unpack into the data dir; `201` | | `GET /api/mcp/presets` | bearer | Thirteen MCP bridges and what blocks each one | @@ -234,7 +240,7 @@ Every protected call needs `Authorization: Bearer `. | `POST /api/mcp/connect`, `/call`, `/disconnect` | bearer | Drive an MCP server; mutations need `allow_mutating` | | `GET /api/mcp/server/tools` | bearer | This bridge as an MCP server: nine tools, write and run annotated | -The reference lists all 63 routes; [docs/API.md](docs/API.md) is generated from the table, so it cannot drift. +The reference lists all 66 routes; [docs/API.md](docs/API.md) is generated from the table, so it cannot drift. Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; add your own with `NERVEFORGE_PUBLIC_UPLOAD_EXTRA`. Details: [docs/PUBLIC_UPLOAD.md](docs/PUBLIC_UPLOAD.md). @@ -243,11 +249,11 @@ Full allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; ad ## 🧪 Tests and code quality -The repository ships **1680 automated unit tests** (Linux, Windows, Android/Termux, API, security, +The repository ships **1698 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 # 1680 tests +python3 -m unittest discover -s tests -v # 1698 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 @@ -310,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 (1680 tests) +├── tests/ # Unit tests (1698 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 0ffbc09..514b2eb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.3.0 +# Security policy — NerveForge 8.4.0 **English** · [Русский](docs/ru/SECURITY.md) diff --git a/VERSION b/VERSION index 2bf50aa..a2f28f4 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -8.3.0 +8.4.0 diff --git a/docs/API.md b/docs/API.md index a7aa476..5cfba1d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -48,6 +48,9 @@ the public uploads are reachable. Bodies are JSON objects; errors are |---|---|---|---| | `GET` | `/api/skills` | Bearer | **Skills.** The skill catalogue with readiness computed from what is installed: `ready`, `partial` (a required tool is missing) or `blocked`. Each row names the missing tools, so an agent can see what this machine can actually do. | | `GET` | `/api/skills/*` | Bearer | **Read a skill.** One skill with its full procedure in `body`, plus `note`: advice built from the tool registry (what to install, or where to stop). | +| `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/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/REFACTORING_PLAN.md b/docs/REFACTORING_PLAN.md index 663d3ed..907263d 100644 --- a/docs/REFACTORING_PLAN.md +++ b/docs/REFACTORING_PLAN.md @@ -6,7 +6,7 @@ > version 7.0.7). The analysis covered `src/`, `static/`, `tests/`, the installers and the > documentation. Test suite at the time of analysis: **66/66 green**. > -> **Status: all eight stages are done. Nine releases later the project is at 8.3.0 with 1680 +> **Status: all eight stages are done. Nine releases later the project is at 8.3.0 with 1698 > tests.** The "before" numbers below are kept as the record of what motivated each stage; the > tables say what each stage started from, not what the suite contains today. > diff --git a/docs/TOOLKIT.md b/docs/TOOLKIT.md index 1b31896..49afe4d 100644 --- a/docs/TOOLKIT.md +++ b/docs/TOOLKIT.md @@ -9,7 +9,7 @@ Three ideas, deliberately separate: | Term | What it is | Where it lives | |---|---|---| -| **Skill** | A written procedure plus the tools it declares | `src/nerveforge/toolkit/skills/*.md` | +| **Skill** | A written procedure plus the tools it declares | `src/nerveforge/toolkit/skills//SKILL.md` | | **Tool** | An external program or Python module, with the release asset a download would use | `src/nerveforge/toolkit/tools.py` | | **MCP server** | Somebody else's tool server, spoken to over JSON-RPC | `src/nerveforge/toolkit/registry.py` | @@ -20,26 +20,30 @@ which tools it needs. Execution stays where it already was: the approval queue o ## Skills -A skill is a Markdown file whose name is the id (`binary-triage.md`). The catalogue -(`skillcatalog.CATALOGUE`) carries the metadata; the file carries the prose, and the two are checked -against each other by a test. The head of `binary-triage.md`: +A skill is a folder whose name is the id, holding a `SKILL.md` +(`skills/binary-triage/SKILL.md`) — the **Agent Skills** layout that Claude Code, Cursor, Codex, +Copilot and the other clients of [agentskills.io](https://agentskills.io) read. The catalogue +(`skillcatalog.CATALOGUE`) carries the tool list; the file carries the YAML front matter and the +prose, and tests check all three against each other. The head of `binary-triage/SKILL.md`: ``` --- -id: binary-triage -category: re -tools: [strings, objdump] -optional: [binwalk, yara, lief, capstone] +name: binary-triage +description: "First ten minutes with an unknown file: what it is, what it links, whether it is packed. Use when working on: reversing, triage, static." +license: MIT +metadata: + category: re + tags: reversing, triage, static + tools: strings, objdump + optional-tools: binwalk, yara, lief, capstone --- - -# Binary triage - -The first ten minutes decide whether the next two hours are wasted. ... ``` -The body is written for an agent, in the imperative, with the commands it would actually type. The -`tools` list is the contract: `GET /api/skills` resolves each name against what is installed here -and reports one of three states. +Two of those fields are the standard's: `name` must be the folder, lowercase, and `description` is +the only thing another agent reads before deciding to open the file. The rest live under +`metadata`, where the spec puts anything a client does not interpret — `category`, `tags`, and the +`tools` list that is this bridge's own contract: `GET /api/skills` resolves each name against what +is installed here and reports one of three states. | State | Meaning | What the agent should do | |---|---|---| @@ -64,7 +68,7 @@ Twelve ship: | `malware-static` | malware | strings | yara, binwalk, exiftool, ghidra | Indicators without executing anything | | `protocol-reversing` | protocol | tshark | scapy, strings | Reconstruct a wire format from a capture | | `android-apk` | mobile | jadx | apktool, adb, frida | Manifest, permissions, Java from an APK | -| `firmware-iOT` | forensics | binwalk | strings, ghidra, sleuthkit | Unpack an image, find the root filesystem | +| `firmware-iot` | forensics | binwalk | strings, ghidra, sleuthkit | Unpack an image, find the root filesystem | | `disk-forensics` | forensics | sleuthkit | plaso, exiftool | Partitions, deleted files, file carving | | `memory-forensics` | forensics | volatility3 | yara | Processes, connections, injected code from a dump | | `yara-authoring` | forensics | yara | strings | Turn indicators into a rule that can be run again | @@ -77,6 +81,28 @@ one can stand in for the other. Adding a skill is one file plus one entry in `skillcatalog.CATALOGUE`; a test checks that every declared tool exists in the catalogue and that every file is present and non-trivial. +### Taking a skill somewhere else + +The point of following the standard is that the file is not ours alone. A skill can be handed to +another agent as it stands: + +| Route | Answers | Use | +|---|---|---| +| `GET /api/skills/` | JSON with `body` (the procedure) and the verdict | This bridge's own screens | +| `GET /api/skills//SKILL.md` | `text/markdown`, a complete standard file | Drop into `.agents/skills//` | +| `GET /api/skills/bundle` | Every skill as `{path, content}`, plus the version | Install all of them at once | +| `GET /api/skills//validate` | `{valid, problems}` against the spec's rules | Before publishing one | + +`/skill.md` in lowercase answers the same thing as `/SKILL.md`; the name of the file is a +convention, and an agent holding one spelling should not have to discover the other. The front +matter is generated by `skillcatalog.front_matter()` rather than written into the files, so the +version of the bridge that produced a copy is recorded in it and the two representations cannot +argue about the tool list. + +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. + --- ## Tools diff --git a/docs/ru/AGENTS.md b/docs/ru/AGENTS.md index 33daab8..d70795c 100644 --- a/docs/ru/AGENTS.md +++ b/docs/ru/AGENTS.md @@ -145,6 +145,12 @@ curl -H "Authorization: Bearer " https:///api/tools кнопкой; если есть — попросите пользователя нажать её (или выполнить `python3 -m nerveforge.toolkit --install <инструмент>`) и не пытайтесь устанавливать сами. +Скиллы — это стандартные файлы `SKILL.md` (`skills//SKILL.md`), поэтому они работают +и вне этого моста: `GET /api/skills//SKILL.md` отдаёт тот же файл как `text/markdown` со +сгенерированным front matter, а `GET /api/skills/bundle` — все сразу, чтобы записать их в +`.agents/skills/`. Не передавайте другому агенту поле `body`, если ему нужен файл: имя, +описание и список инструментов в форме, которую клиент читает, есть только в файле. + ### Шаг 6: Вызвать MCP-инструмент, если сервер настроен `GET /api/mcp` перечисляет сессии, `GET /api/mcp/presets` называет, что мешает каждому мосту. diff --git a/docs/ru/API.md b/docs/ru/API.md index 3ab8a20..8c20568 100644 --- a/docs/ru/API.md +++ b/docs/ru/API.md @@ -48,6 +48,9 @@ |---|---|---|---| | `GET` | `/api/skills` | Bearer | **Навыки.** Каталог навыков с готовностью, посчитанной по установленному: `ready`, `partial` (нет обязательного инструмента) или `blocked`. В каждой строке перечислены недостающие инструменты — агент видит, что машина умеет на самом деле. | | `GET` | `/api/skills/*` | Bearer | **Читать навык.** Один навык с полной процедурой в `body` и `note` — советом, собранным по реестру инструментов (что доустановить или где остановиться). | +| `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/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 7707b5f..baf45b8 100644 --- a/docs/ru/CHANGELOG.md +++ b/docs/ru/CHANGELOG.md @@ -2,6 +2,62 @@ [English](../../CHANGELOG.md) · **Русский** +## 8.4.0 + +Скиллы становятся файлами, которые может прочитать кто-то ещё. Двенадцать процедур +уже были хорошим советом и уже несли вердикт, посчитанный по тому, что установлено +на этой машине; записаны они были в форме, которую понимал только этот мост. Теперь +они следуют стандарту **Agent Skills** (`SKILL.md`), который Claude Code, Cursor, +Codex, Copilot и остальные клиенты agentskills.io загружают напрямую. + +### Один файл, две аудитории + +Раскладка переехала из `skills/.md` в `skills//SKILL.md`, а front matter +генерируется `skillcatalog.front_matter()`, а не пишется руками: `name` (спецификация +требует совпадения с папкой, нижнего регистра и без двойных дефисов), `description` +(что делает и когда применять, не длиннее 1024 символов), `license` и всё нужное +мосту — в `metadata`: категория, теги, обязательные и необязательные инструменты. +Тест проверяет именно те правила, которые клиент иначе применил бы молчаливым +отказом загрузить файл. + +Экспорт делают настоящим, а не номинальным, три маршрута: + +- `GET /api/skills//SKILL.md` отвечает `text/markdown` с front matter, файл + готов лечь в `.agents/skills//`. `/skill.md` в нижнем регистре отвечает тем + же: агент, держащий одно написание, не должен выяснять, что есть и другое. +- `GET /api/skills/bundle` отдаёт все скиллы как `{id, path, content}` и версию, + их выпустившую, — дюжину файлов можно записать одним запросом. +- `GET /api/skills//validate` сообщает, что помешает файлу загрузиться: правила + имени, лимит описания и совпадение папки, файла и имени. + +`GET /api/skills/` по-прежнему отдаёт процедуру в `body`, но уже без YAML-блока: +вердикт и список инструментов и так лежат рядом полями, а две копии одного факта — +это на одну копию больше, чем нужно. + +### Что не переезжает + +`metadata.tools` уходит вместе с файлом, а *проверка* этого списка — нет: другой +клиент не знает, что установлено на этой машине. Поэтому выгруженный скилл говорит, +что ему нужно, а мост говорит, есть ли это, — `ready`, `partial`, `blocked`, — и это +разделение задокументировано, а не оставлено на выяснение. + +### Всё остальное + +- `firmware-iOT` теперь `firmware-iot`. Стандарт разрешает строчные буквы, цифры и + одиночные дефисы; старое имя клиенты, для которых этот релиз делался, отвергли бы. + Id каталога, папка и документация совпадают. +- `pyproject.toml` поставляет `toolkit/skills/*/SKILL.md` как данные пакета, поэтому + установленный мост имеет те же процедуры, что и репозиторий, а не двенадцать + однострочных сводок. Проверено на собранном колесе: 12 записей `SKILL.md`. +- Старая плоская раскладка всё ещё читается, если найдена: дерево, установленное до + этого релиза, продолжает работать. +- В `/llms.txt` и `/api/agent-prompt` появились раздел про скиллы и три новых + маршрута: агенту стоит сказать «прочитай процедуру», прежде чем импровизировать + порядок шагов в реверсе. +- Маршрутов 63 → 66, тестов 1680 → 1698. `Table.resolve` теперь предпочитает точный + путь, затем паттерн, затем префикс: префикс не может сказать, где путь кончается, а этот + релиз — первый, который добавил маршруты под существующий префикс. + ## 8.3.0 Context7, включённый по умолчанию. С 8.2.0 мост говорит по MCP в обе стороны, и diff --git a/docs/ru/README.md b/docs/ru/README.md index 080e205..365af5a 100644 --- a/docs/ru/README.md +++ b/docs/ru/README.md @@ -1,4 +1,4 @@ -# NerveForge 8.3.0 ⚡ Arena.ai ↔ PC & Android Bridge +# NerveForge 8.4.0 ⚡ Arena.ai ↔ PC & Android Bridge ![NerveForge — Build boldly. Ship cleverly.](../../assets/nerveforge-lockup.png) @@ -120,6 +120,11 @@ python3 -m nerveforge.tunnel.cli --install-cloudflared чистом контейнере три готовы, один лечится одним нажатием и восемь заблокированы; это честный ответ, а не ошибка. +Каждый скилл — это стандартный `SKILL.md` в `skills//`, в раскладке Agent Skills, которую +читают Claude Code, Cursor, Codex и Copilot, поэтому `GET /api/skills//SKILL.md` отдаёт ту же +процедуру другому агенту файлом, который можно положить в `.agents/skills/`. Вердикт остаётся +здесь, потому что только эта машина знает, что на ней установлено. + **Инструменты** (`GET /api/tools`). 24 записи по реверсу, отладке, мобильным платформам, форензике и сети, у каждой — релизный ассет, который понадобится при скачивании. Кнопка **установить** и CLI идут по тому же правилу, что cloudflared: только ассет релиза, @@ -255,6 +260,7 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write | Метод / Эндпоинт | Заголовки | Описание | | :--- | :--- | :--- | | `GET /api/skills`, `GET /api/skills/` | `Bearer ` | Каталог скиллов со статусом `ready`/`partial`/`blocked` и тело одного скилла | +| `GET /api/skills//SKILL.md`, `/bundle` | `Bearer ` | Переносимые файлы Agent Skills со сгенерированным front matter | | `GET /api/tools` | `Bearer ` | Каталог инструментов: что установлено, чего нет, что можно скачать | | `POST /api/tools/install` | `Bearer ` | `{"id": "jadx"}` — скачать, сверить SHA-256, распаковать в data dir; `201` | | `GET /api/tools/plan?id=` | `Bearer ` | Что именно будет скачано и откуда | @@ -263,7 +269,7 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write | `POST /api/mcp/connect`, `/call`, `/disconnect` | `Bearer ` | Работа с MCP-сервером; изменения требуют `allow_mutating` | | `GET /api/mcp/server/tools` | `Bearer ` | Этот мост как MCP-сервер: девять инструментов, запись и запуск помечены | -Справочник покрывает все 63 маршрута; [docs/API.md](../../docs/API.md) генерируется из таблицы, поэтому разойтись с кодом не может. +Справочник покрывает все 66 маршрутов; [docs/API.md](../../docs/API.md) генерируется из таблицы, поэтому разойтись с кодом не может. Полный allowlist: `GET /api/quick` → `capabilities.public_upload.extensions`; свои расширения — `NERVEFORGE_PUBLIC_UPLOAD_EXTRA`. Подробнее: [docs/PUBLIC_UPLOAD.md](../../docs/PUBLIC_UPLOAD.md). @@ -271,10 +277,10 @@ python3 -m nerveforge.toolkit --serve --allow-write # плюс workspace_write ## 🧪 Тестирование и качество кода -Репозиторий покрыт полным набором из **1680 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: +Репозиторий покрыт полным набором из **1698 автоматических unit-тестов** (Linux, Windows, Android/Termux, API, безопасность, туннели). CI запускает их на Linux и Windows: ```bash -# Запуск 1680 unit-тестов +# Запуск 1698 unit-тестов python3 -m unittest discover -s tests -v # Проверка байткода Python @@ -341,7 +347,7 @@ nerveforge/ │ ├── uzhas_manager.py # Универсальный запуск команд в любой оболочке │ └── workspace_manager.py # Файловые операции, песочница bwrap, публичные загрузки ├── static/ # Ассеты веб-панели (HTML, CSS, JS) -├── tests/ # Набор unit-тестов (1680 тестов) +├── tests/ # Набор unit-тестов (1698 тестов) ├── pyproject.toml # Стандарт сборки PEP 517/518 ├── run.py # Точка входа для запуска на месте ├── setup.sh # Установщик для Linux Mint / Ubuntu diff --git a/docs/ru/REFACTORING_PLAN.md b/docs/ru/REFACTORING_PLAN.md index dd00516..4355243 100644 --- a/docs/ru/REFACTORING_PLAN.md +++ b/docs/ru/REFACTORING_PLAN.md @@ -6,7 +6,7 @@ > (ветка `arena/36a4d756-nerveforge`, версия 7.0.7). Анализ покрывал `src/`, `static/`, `tests/`, > установщики и документацию. Тесты на момент анализа: **66/66 зелёные**. > -> **Статус: все восемь этапов выполнены. Девять релизов спустя проект на 8.3.0 с 1680 тестами.** +> **Статус: все восемь этапов выполнены. Девять релизов спустя проект на 8.3.0 с 1698 тестами.** > Числа «до» сохранены как запись о том, что мотивировало каждый этап. > > Более поздний проход замерил покрытие и дублирование и убрал то, что оставили сами этапы: мёртвые @@ -255,7 +255,7 @@ CSP плюс `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy`, `Cross- | Покрыто инструкций | 71% | 94% | | Непокрытых строк | 1048 | 217 | | Дублирующихся блоков длиннее 6 строк | 4 | 0 | -| Тестов | 301 | 1680 | +| Тестов | 301 | 1698 | Три самых слабых файла стояли на пути от запроса к оболочке — `approval.py` 25%, `configs.py` 23%, `workspace.py` 37%. Теперь 87%, 97% и 94%. Тесты очереди проверяют порядок (одновременно в работе только один запрос), отказ (ничего не запускается без подтверждения) и восстановление (упавшее исполнение освобождает активный слот, а не заклинивает очередь). diff --git a/docs/ru/SECURITY.md b/docs/ru/SECURITY.md index 6466cd7..2e33581 100644 --- a/docs/ru/SECURITY.md +++ b/docs/ru/SECURITY.md @@ -1,4 +1,4 @@ -# Security policy — NerveForge 8.3.0 +# Security policy — NerveForge 8.4.0 [English](../../SECURITY.md) · **Русский** diff --git a/docs/ru/TOOLKIT.md b/docs/ru/TOOLKIT.md index 95492f2..4749add 100644 --- a/docs/ru/TOOLKIT.md +++ b/docs/ru/TOOLKIT.md @@ -10,7 +10,7 @@ | Термин | Что это | Где лежит | |---|---|---| -| **Скилл** | Написанная процедура плюс объявленный список инструментов | `src/nerveforge/toolkit/skills/*.md` | +| **Скилл** | Написанная процедура плюс объявленный список инструментов | `src/nerveforge/toolkit/skills//SKILL.md` | | **Инструмент** | Внешняя программа или Python-модуль с именем релизного ассета | `src/nerveforge/toolkit/tools.py` | | **MCP-сервер** | Чужой сервер инструментов, с которым говорят по JSON-RPC | `src/nerveforge/toolkit/registry.py` | @@ -22,26 +22,31 @@ ## Скиллы -Скилл — это Markdown-файл, имя которого и есть id (`binary-triage.md`). Метаданные живут в -каталоге (`skillcatalog.CATALOGUE`), а файл — это текст, и тест сверяет одно с другим. Начало -`binary-triage.md`: +Скилл — это папка, имя которой и есть id, с файлом `SKILL.md` +(`skills/binary-triage/SKILL.md`) — раскладка стандарта **Agent Skills**, которую читают Claude +Code, Cursor, Codex, Copilot и другие клиенты [agentskills.io](https://agentskills.io). Список +инструментов живёт в каталоге (`skillcatalog.CATALOGUE`), а файл — это YAML в начале и текст +дальше, и тесты сверяют друг с другом всё три. Начало `binary-triage/SKILL.md`: ``` --- -id: binary-triage -category: re -tools: [strings, objdump] -optional: [binwalk, yara, lief, capstone] +name: binary-triage +description: "First ten minutes with an unknown file: what it is, what it links, whether it is packed. Use when working on: reversing, triage, static." +license: MIT +metadata: + category: re + tags: reversing, triage, static + tools: strings, objdump + optional-tools: binwalk, yara, lief, capstone --- - -# Binary triage - -The first ten minutes decide whether the next two hours are wasted. ... ``` -Тело написано для агента, в повелительном наклонении, с командами, которые он реально -набрал бы. Список `tools` — это контракт: `GET /api/skills` сверяет каждое имя с тем, -что установлено здесь, и сообщает одно из трёх состояний. +Два поля здесь из стандарта: `name` обязан совпадать с папкой и быть в нижнем регистре, а +`description` — единственное, что другой агент прочитает до того, как решит открыть файл. +Остальное лежит в `metadata`, куда спецификация кладёт всё, что клиент не интерпретирует: +`category`, `tags` и список `tools`, который является контрактом уже этого моста: +`GET /api/skills` сверяет каждое имя с тем, что установлено здесь, и сообщает одно из трёх +состояний. | Состояние | Значение | Что делать агенту | |---|---|---| @@ -66,7 +71,7 @@ The first ten minutes decide whether the next two hours are wasted. ... | `malware-static` | malware | strings | yara, binwalk, exiftool, ghidra | Индикаторы, ничего не запуская | | `protocol-reversing` | protocol | tshark | scapy, strings | Восстановить формат по перехваченному трафику | | `android-apk` | mobile | jadx | apktool, adb, frida | Манифест, разрешения, Java из APK | -| `firmware-iOT` | forensics | binwalk | strings, ghidra, sleuthkit | Распаковать образ, найти корневую ФС | +| `firmware-iot` | forensics | binwalk | strings, ghidra, sleuthkit | Распаковать образ, найти корневую ФС | | `disk-forensics` | forensics | sleuthkit | plaso, exiftool | Разделы, удалённые файлы, карвинг | | `memory-forensics` | forensics | volatility3 | yara | Процессы, соединения, внедрённый код из дампа | | `yara-authoring` | forensics | yara | strings | Превратить индикаторы в правило, которое можно прогнать снова | @@ -80,6 +85,27 @@ The first ten minutes decide whether the next two hours are wasted. ... проверяет, что каждый объявленный инструмент есть в каталоге, а каждый файл существует и не пуст. +### Как забрать скилл с собой + +Смысл следования стандарту в том, что файл принадлежит не только нам. Скилл можно отдать +другому агенту как есть: + +| Маршрут | Отдаёт | Для чего | +|---|---|---| +| `GET /api/skills/` | JSON с `body` (процедура) и вердиктом | Собственные экраны моста | +| `GET /api/skills//SKILL.md` | `text/markdown`, полный файл стандарта | Положить в `.agents/skills//` | +| `GET /api/skills/bundle` | Все скиллы как `{path, content}` и версию | Установить все сразу | +| `GET /api/skills//validate` | `{valid, problems}` по правилам спецификации | Перед публикацией | + +`/skill.md` в нижнем регистре отвечает тем же, что и `/SKILL.md`: имя файла — конвенция, и агент, +держащий одно написание, не должен выяснять, что существует ещё и другое. Front matter +генерируется `skillcatalog.front_matter()`, а не вписан в файлы, поэтому в копии остаётся версия +моста, её выпустившего, и две репрезентации не могут разойтись в списке инструментов. + +Вердикт уходит с файлом лишь настолько, насколько хватает `metadata.tools`: другой клиент его +прочитает, но не сможет проверить, потому что не знает, что установлено на этой машине. Эта +проверка остаётся здесь, где ответ настоящий. + --- ## Инструменты diff --git a/pyproject.toml b/pyproject.toml index 04fd6ae..8598c95 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,14 @@ nerveforge = "nerveforge.tunnel:main" [tool.setuptools.packages.find] where = ["src"] +# Skills are data, not code: `skills//SKILL.md` ships with the package so +# an installed bridge has the same procedures, and the same exportable files, +# as a repository checkout. Without this the catalogue would list twelve skills +# whose bodies degrade to one-line summaries. +[tool.setuptools.package-data] +nerveforge = ["toolkit/skills/*/SKILL.md", "toolkit/skills_flat/*.md", "toolkit/skills/*/*", + "toolkit/skills/*/*/*"] + [tool.setuptools.dynamic] version = {attr = "nerveforge._version.__version__"} diff --git a/scripts/gen_api_doc.py b/scripts/gen_api_doc.py index 7fdc26f..b13f945 100644 --- a/scripts/gen_api_doc.py +++ b/scripts/gen_api_doc.py @@ -101,6 +101,27 @@ "from the tool registry (what to install, or where to stop).", "Читать навык", "Один навык с полной процедурой в `body` и `note` — советом, собранным " "по реестру инструментов (что доустановить или где остановиться)."), + "skills_document": ("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.", + "Навык как SKILL.md", + "`text/markdown`: файл стандарта agent-skills для этого навыка вместе с front " + "matter. Отвечают и `/skill.md`, и `/SKILL.md`. Положите его в " + "`.agents/skills//` — и у другого клиента та же процедура."), + "skills_bundle": ("Every skill as SKILL.md", + "`{version, skills: [{id, path, content}]}` — the whole catalogue ready to be " + "written to disk in one request.", + "Все навыки как SKILL.md", + "`{version, skills: [{id, path, content}]}` — весь каталог, готовый лечь на диск " + "одним запросом."), + "skills_validate": ("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.", + "Проверка навыка по спецификации", + "`{valid, problems}`: правила имени, лимит описания в 1024 символа и совпадение " + "папки, файла и имени."), "tools": ("Tool registry", "External programs and libraries (ghidra, yara, volatility3...) with " "`available`, `via` (`binary`|`module`), `path`, `downloadable` and package " "names per manager.", @@ -287,7 +308,9 @@ ("State and limits", "Состояние и лимиты", ("quick", "limits_get", "limits_set", "state", "events", "requests", "system_report")), ("Tunnel", "Туннель", ("tunnel", "tunnel_config", "tunnel_provider", "tunnel_install")), - ("Skills and tools", "Навыки и инструменты", ("skills", "skills_one", "tools", "tool_plan", "tool_install")), + ("Skills and tools", "Навыки и инструменты", + ("skills", "skills_one", "skills_document", "skills_bundle", "skills_validate", + "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", "mcp_config_get", "mcp_config_set", "mcp_enable", "mcp_delete")), diff --git a/src/nerveforge/_version.py b/src/nerveforge/_version.py index 55b221f..c79beac 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.3.0" +__version__ = "8.4.0" diff --git a/src/nerveforge/http/router.py b/src/nerveforge/http/router.py index f4ed7dc..a544e32 100644 --- a/src/nerveforge/http/router.py +++ b/src/nerveforge/http/router.py @@ -37,14 +37,48 @@ def add(self, *args, **kwargs) -> Route: return route def resolve(self, path: str, method: str | None = None) -> Route | None: - path_match = None - for route in self.routes: - if not route.matches(path): + """The most specific route for this path, in three passes. + + Exact paths come before patterns, and patterns before prefixes, because + a prefix is the only rule that cannot say where a path ends: + `/api/skills/*` matches `/api/skills/bundle`. Registration order used to + decide that, which worked only for as long as nobody added a route + underneath an existing prefix — and then it failed silently, sending a + request for one resource to a handler for another. The passes keep the + old behaviour for everything that was unambiguous and give the specific + rule the right to exist. + """ + prefix_match = None + for group in (self._exact, self._pattern, self._prefix): + path_match = None + for route in group: + if not route.matches(path): + continue + if method is None or method in route.methods: + return route + path_match = path_match or route + if group is self._prefix: + prefix_match = path_match continue - if method is None or method in route.methods: - return route - path_match = path_match or route - return path_match + if path_match is not None: + # A pattern that matches the path but not the method still + # beats a prefix: the caller asked for this resource and used + # the wrong verb, which is a 405, not somebody else's handler. + return path_match + return prefix_match + + @property + def _exact(self) -> list[Route]: + return [route for route in self.routes if route.exact] + + @property + def _pattern(self) -> list[Route]: + return [route for route in self.routes if route.pattern] + + @property + def _prefix(self) -> list[Route]: + return [route for route in self.routes + if route.prefixes and not route.exact and not route.pattern] def names(self) -> list[str]: return [route.name for route in self.routes] diff --git a/src/nerveforge/http/routes/toolkit.py b/src/nerveforge/http/routes/toolkit.py index 3eaf70d..b80b6a9 100644 --- a/src/nerveforge/http/routes/toolkit.py +++ b/src/nerveforge/http/routes/toolkit.py @@ -12,12 +12,21 @@ """ from __future__ import annotations +import re + +from ..._version import __version__ from ...core.errors import BadRequest, Conflict, NotFound, TooManyRequests -from ...toolkit import installer, mcpserver, mcpservice, registry, skilldoc, tools +from ...toolkit import installer, mcpserver, mcpservice, registry, skillcatalog, skilldoc, tools from ..router import RouteTable SKILLS_PATH = "/api/skills" SKILL_PATH = "/api/skills/" + +#: `` only, and `/SKILL.md` in either case. Patterns rather than +#: prefixes: a skill id and a suffix have a shape, and a route that accepted any +#: 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$") TOOLS_PATH = "/api/tools" MCP_PATH = "/api/mcp" PRESETS_PATH = "/api/mcp/presets" @@ -50,6 +59,51 @@ def get_skill(handler, path): return handler.send_json(row) +def get_skill_document(handler, path): + """One skill as a portable `SKILL.md`. + + The bridge's own view of a skill (`body`) is the procedure alone, because + the verdict and the tool list sit next to it as fields. Another agent gets + no such fields, so this route returns the file that carries them in YAML — + the same bytes a repository checkout holds, which is what makes it + copyable into `.agents/skills/` without editing. + """ + skill_id = _skill_id(path, SKILL_PATH, "skill.md") + content = skilldoc.document(skill_id, version=__version__) + if content is None: + raise NotFound(f"unknown skill: {skill_id}") + return handler.send_bytes(content.encode("utf-8"), "text/markdown; charset=utf-8") + + +def get_skills_bundle(handler, path): + return handler.send_json({"version": __version__, "skills": skilldoc.documents(version=__version__)}) + + +def get_skill_validate(handler, path): + skill_id = _skill_id(path, SKILL_PATH, "validate") + if skill_id not in skillcatalog.BY_ID: + raise NotFound(f"unknown skill: {skill_id}") + problems = skilldoc.validate(skill_id) + return handler.send_json({"id": skill_id, "valid": not problems, "problems": problems}) + + +def _skill_id(path: str, prefix: str, suffix: str) -> str: + """The id between the prefix and the suffix, closing the skill's folder. + + `/api/skills//SKILL.md` and `/api/skills//skill.md` both answer: + the first is what the standard's own layout uses, and an agent that has + one of them in front of it should not have to discover that the other is + the accepted spelling. + """ + body = path.split("?", 1)[0] + if not body.startswith(prefix) or not body.lower().endswith("/" + suffix): + raise NotFound("skill not found") + rest = body[len(prefix): -len(suffix) - 1] + if not rest or "/" in rest: + raise NotFound("skill not found") + return rest + + def post_tool_install(handler, path): """Download one tool from its GitHub releases, verified, into the data dir. @@ -326,6 +380,10 @@ def _require_id(data: dict) -> str: def register(table: RouteTable, ctx) -> None: table.add("skills", get_skills, methods=("GET",), exact=(SKILLS_PATH,)) table.add("skills_one", get_skill, methods=("GET",), prefixes=(SKILL_PATH,)) + table.add("skills_document", get_skill_document, methods=("GET",), pattern=SKILL_DOC_RE) + 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("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/services/system.py b/src/nerveforge/services/system.py index abf98b0..8c9bb8c 100644 --- a/src/nerveforge/services/system.py +++ b/src/nerveforge/services/system.py @@ -69,6 +69,18 @@ no reason to skip it. Versions, defaults and deprecated calls drift between releases; the model's memory of them does not. Treat a signature you have not confirmed here as a guess, and say so if the lookup fails. + +9. **Skills: procedures with a verdict, and with a portable file:** + `GET /api/skills` lists the procedures this machine can actually run (reverse engineering, + forensics, mobile, protocol work), each as `ready`, `partial` or `blocked` based on the + tools installed here; `GET /api/skills/` returns the body together with that verdict, + so a skill whose tools are missing says so before you start it. + + The files follow the Agent Skills standard (`SKILL.md`), so the same text works in other + clients: `GET /api/skills//SKILL.md` answers `text/markdown` with generated front + matter, and `GET /api/skills/bundle` returns all of them as `{path, content}` for writing + into `.agents/skills/`. Read a skill before a reversing or forensics task instead of + improvising the order of steps. """ @@ -108,6 +120,10 @@ def get_agent_prompt() -> dict: "docs_tools": "GET /api/mcp/docs", "docs_lookup": "POST /api/mcp/docs/call", "docs_server": "context7", + "skills": "GET /api/skills", + "skill": "GET /api/skills/", + "skill_document": "GET /api/skills//SKILL.md", + "skills_bundle": "GET /api/skills/bundle", }, "full_access_phrase": "yesiknow", } diff --git a/src/nerveforge/toolkit/skillcatalog.py b/src/nerveforge/toolkit/skillcatalog.py index ddab5c3..1725738 100644 --- a/src/nerveforge/toolkit/skillcatalog.py +++ b/src/nerveforge/toolkit/skillcatalog.py @@ -9,6 +9,14 @@ Skills live as Markdown files next to this module. They are data: adding one is a file plus a row, with no code to touch. + +The files follow the **Agent Skills** layout (`SKILL.md`: YAML front matter +with `name`, `description` and `metadata`, then the prose), which Claude Code, +Cursor, Codex, Copilot and a dozen other agent clients already read. That is +deliberate: the same procedure that this bridge will not let an agent run past a +missing tool is also a skill somebody can drop into their own editor. The +front matter generated by `front_matter()` is the only place the two audiences +meet, so it is built from one function rather than written twice. """ from __future__ import annotations @@ -118,7 +126,7 @@ def file(self) -> str: tags=("yara", "detection"), ), SkillSpec( - id="firmware-iOT", + id="firmware-iot", title="Firmware and embedded images", category="forensics", summary="Find the filesystem inside a firmware blob, then the interesting binaries inside that.", @@ -147,20 +155,117 @@ def file(self) -> str: ) BY_ID = {skill.id: skill for skill in CATALOGUE} + +#: 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") +#: Where the files used to live, when they were one flat `.md` each. Kept as +#: a fallback so an installed tree that still has them keeps working. +LEGACY_SKILLS_DIR = Path(__file__).with_name("skills_flat") + + +def skill_path(skill: SkillSpec) -> Path: + """Where this skill's file is, in whichever of the two layouts exists.""" + standard = SKILLS_DIR / skill.id / "SKILL.md" + if standard.is_file(): + return standard + legacy = LEGACY_SKILLS_DIR / skill.file + if legacy.is_file(): + return legacy + return standard + + + +def skill_body(skill: SkillSpec) -> str: + """The prose of a skill without any front matter, or a plain refusal. + + The bridge's own screens show the procedure, not the metadata: the verdict + and the tool list are already computed fields next to it, and repeating them + in YAML would give an agent two versions of the same fact. + """ + raw = body(skill) + stripped = raw.lstrip() + if not stripped.startswith("---"): + return raw + parts = stripped.split("---", 2) + return parts[2].lstrip("\n") if len(parts) == 3 else raw def body(skill: SkillSpec) -> str: """The Markdown body of a skill, or a plain refusal when it is missing.""" - path = SKILLS_DIR / skill.file try: - return path.read_text(encoding="utf-8") + return skill_path(skill).read_text(encoding="utf-8") except OSError: # A skill without its text is still listed: hiding it would leave the # agent wondering why a name it was given does not resolve. return f"# {skill.title}\n\n{skill.summary}\n" +#: Letters, digits and single hyphens, per the Agent Skills spec. A name that +#: breaks this is a name some other agent will refuse to load. +_NAME_OK = "abcdefghijklmnopqrstuvwxyz0123456789-" + + +def name_is_valid(name: str) -> bool: + """The spec's `name` rule: 1-64 chars, lowercase, no double hyphens.""" + if not 1 <= len(name) <= 64 or name.strip("-") != name: + return False + if "--" in name: + return False + return all(char in _NAME_OK for char in name) + + +def description(skill: SkillSpec) -> str: + """The one sentence the spec puts in `description`, at most 1024 chars. + + It has to say *what* the skill does and *when* to use it, because that is + all another agent sees before deciding to open the file. + """ + text = f"{skill.summary} Use when working on: {', '.join(skill.tags)}." if skill.tags \ + else skill.summary + return text[:1024] + + +def front_matter(skill: SkillSpec, *, version: str = "") -> str: + """The YAML block of one `SKILL.md`, generated rather than hand-written. + + Required by the spec: `name` and `description`. `license` and `metadata` + are optional and kept because a copied skill should say what it is and + where it came from, with the Bridge's verdict still computable afterwards. + """ + lines = ["---", f"name: {skill.id}", f"description: {_yaml_text(description(skill))}", + "license: MIT", + "metadata:", + " category: " + skill.category, + " tags: " + ", ".join(skill.tags)] + if version: + lines.append(" version: " + version) + if skill.tools: + lines.append(" tools: " + ", ".join(skill.tools)) + if skill.optional_tools: + lines.append(" optional-tools: " + ", ".join(skill.optional_tools)) + lines.append("---") + return "\n".join(lines) + + +def document(skill: SkillSpec, *, body: str = "", version: str = "") -> str: + """A complete `SKILL.md`: the generated front matter plus the procedure. + + Called with a body for a file written now, and without one to describe what + this bridge holds — an installed tree and a repository checkout then produce + the same bytes, which is what makes the file copyable. + """ + prose = body if body else skill_body(skill) + return front_matter(skill, version=version) + "\n\n" + prose.strip() + "\n" + + +def _yaml_text(value: str) -> str: + """Quote a string that a YAML parser would otherwise mangle.""" + if not value or value[0] in "-?:,[]{}#&*!|>'\"%@`" or ": " in value or value != value.strip(): + return '"' + value.replace('"', '\\"') + '"' + return value + + def categories() -> dict[str, int]: counts: dict[str, int] = {} for skill in CATALOGUE: diff --git a/src/nerveforge/toolkit/skilldoc.py b/src/nerveforge/toolkit/skilldoc.py index 2011259..6eb2cb8 100644 --- a/src/nerveforge/toolkit/skilldoc.py +++ b/src/nerveforge/toolkit/skilldoc.py @@ -33,6 +33,9 @@ def readiness(skill: skillcatalog.SkillSpec) -> dict: state = "blocked" row = { "id": skill.id, + # The Agent Skills name, which the standard requires to match the + # folder and which other clients will look for. + "name": skill.id, "title": skill.title, "category": skill.category, "summary": skill.summary, @@ -45,7 +48,7 @@ def readiness(skill: skillcatalog.SkillSpec) -> dict: # saying so is the difference between a menu and a dead end. "installable": bool(missing_required) and all( row["downloadable"] for row in required if row["id"] in missing_required), - "body_available": (skillcatalog.SKILLS_DIR / skill.file).is_file(), + "body_available": skillcatalog.skill_path(skill).is_file(), } row["note"] = _advice(row) return row @@ -61,11 +64,57 @@ def get(skill_id: str) -> dict | None: if skill is None: return None row = readiness(skill) - row["body"] = skillcatalog.body(skill) + # The procedure, not the YAML: the verdict and the tool list are already + # fields here, and a second copy of them is a second thing to drift. + row["body"] = skillcatalog.skill_body(skill) row["note"] = _advice(row) return row +def document(skill_id: str, *, version: str = "") -> str | None: + """A complete `SKILL.md` for one skill, ready to be written to disk. + + This is the portable artefact: drop it into `.agents/skills//SKILL.md` + 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) + if skill is None: + return None + return skillcatalog.document(skill, version=version) + + +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] + + +def validate(skill_id: str) -> list[str]: + """What stops this skill from loading in another agent, if anything. + + The spec's rules are few and mechanical, which is exactly why they are + worth checking: a name with a capital letter, a description over 1024 + 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) + if skill is None: + return [f"unknown skill: {skill_id}"] + problems = [] + if not skillcatalog.name_is_valid(skill.id): + problems.append("name must be 1-64 lowercase letters, digits or single hyphens") + if len(skillcatalog.description(skill)) > 1024: + problems.append("description is longer than 1024 characters") + path = skillcatalog.skill_path(skill) + if not path.is_file(): + problems.append("no SKILL.md on disk") + elif path.parent.name != skill.id: + problems.append(f"folder {path.parent.name!r} does not match the name {skill.id!r}") + return problems + + def _advice(row: dict) -> str: """One sentence the agent can act on, in the skill's own terms.""" if row["state"] == "ready": diff --git a/src/nerveforge/toolkit/skills/android-apk/SKILL.md b/src/nerveforge/toolkit/skills/android-apk/SKILL.md new file mode 100644 index 0000000..47414e6 --- /dev/null +++ b/src/nerveforge/toolkit/skills/android-apk/SKILL.md @@ -0,0 +1,54 @@ +--- +name: android-apk +description: "Unpack an APK, read the manifest and smali, hook the parts that only work on a device. Use when working on: mobile, android, apk." +license: MIT +metadata: + category: mobile + tags: mobile, android, apk + tools: jadx + optional-tools: apktool, adb, frida +--- + +# Android APK analysis + +An APK is a zip with opinions. Rust, Kotlin, Flutter and React Native all ship +inside the same container and none of them look like Java. + +## Order of steps + +1. **Manifest first.** `aapt2 dump badging` or the `AndroidManifest.xml` in + jadx: package, version, permissions, exported components. The permissions + list is a summary of what the app is allowed to be. +2. **Native code check.** Any `lib/*/lib*.so` in the zip means the interesting + logic is probably not in the dex. Note the ABIs before going further. +3. **Dex level.** `jadx -d out app.apk`, then read from `MainActivity` inward, + and from the network layer outward. Signing, crypto and auth are usually + named honestly in third-party SDKs and dishonestly in first-party code. +4. **Resources and config.** `apktool d` when you need the real XML, the + `assets/` folder, or `google-services.json`. Flutter apps keep Dart in + `libapp.so`; React Native keeps JS in `index.android.bundle`, which is + readable after decompressing. +5. **Only then the device.** `adb shell` to install and run a build you are + authorised to test; `frida` to hook the function you identified statically. +6. **Record the trust boundary.** What is checked on the client and never on + the server is the finding, not a curiosity. + +## What people get wrong + +- Reading only the dex. Most modern apps do the real work in a `.so`. +- Confusing obfuscation with encryption. `a.b.c()` is obfuscation; a decrypted + string that turns back into readable text is not a secret, it is a delay. +- Running Frida on a phone that is not yours. Hooking a live app on a shared + device is somebody else's problem waiting to happen; use a test device. + +## Definition of done + +You can say where the app's decisions are made (client or server), what it +sends and to whom, and which piece of code enforces each rule — with a file and +line to point at. + +## With the tools here + +`jadx` for the dex, `apktool` for resources, `adb` for a device or emulator, +`frida` for hooks. For native libraries, `function-recovery` is the next skill, +not this one. diff --git a/src/nerveforge/toolkit/skills/binary-triage/SKILL.md b/src/nerveforge/toolkit/skills/binary-triage/SKILL.md new file mode 100644 index 0000000..f27e61d --- /dev/null +++ b/src/nerveforge/toolkit/skills/binary-triage/SKILL.md @@ -0,0 +1,52 @@ +--- +name: binary-triage +description: "First ten minutes with an unknown file: what it is, what it links, whether it is packed. Use when working on: reversing, triage, static." +license: MIT +metadata: + category: re + tags: reversing, triage, static + tools: strings, objdump + optional-tools: binwalk, yara, lief, capstone +--- + +# Binary triage + +The first ten minutes decide whether the next two hours are wasted. Do not open +a decompiler yet. + +## Order of steps + +1. **Hash it and stat it.** `sha256sum`, size, mtime. A file nobody hashed is a + file nobody can compare against a second copy. +2. **Identify, don't guess.** `file` for the container, then the header: + `xxd -l 64`. A `MZ` that says "data" is usually a packed or overlay file. +3. **Ask what it links.** `readelf -d` (ELF) or `objdump -p` (PE) for imports. + Few imports plus a large file is the classic packing signal; a single + `LoadLibrary`/`dlopen` import is the same signal. +4. **Sections.** `readelf -S` / `objdump -h`. Entropy per section above ~7.0, + or a section whose name is not a name, means unpacking comes first. +5. **Strings, but read them as evidence.** `strings -n 6` and look for: URLs, + file paths, registry keys, error messages, library versions. Compiler + messages tell you the toolchain; a version banner tells you the era. +6. **Only now** decide: static reversing, dynamic tracing, or unpacking. + +## What people get wrong + +- Running it "just to see". On a hostile sample that is the whole analysis, + decided by accident. A skill that says `malware-static` says it for a reason. +- Trusting `file`. It reads the magic, not the meaning; a `.dll` renamed to + `.so` is still a PE. +- Ignoring the build path. `/home/builder/src/foo` in a stripped binary names + the project and often the exact commit. + +## Definition of done + +You can state, in one paragraph: what the file is, what it was built with, +whether it is packed, and which of the next skills applies. If you cannot say +"packed" or "not packed" with a reason, you are not done. + +## With the tools here + +`strings` and `objdump` are enough for steps 1–4. `binwalk` finds embedded +members; `yara` turns your findings into a reusable rule; `lief` reads headers +from Python when you want a table rather than a wall of output. diff --git a/src/nerveforge/toolkit/skills/dependency-audit/SKILL.md b/src/nerveforge/toolkit/skills/dependency-audit/SKILL.md new file mode 100644 index 0000000..e3ac035 --- /dev/null +++ b/src/nerveforge/toolkit/skills/dependency-audit/SKILL.md @@ -0,0 +1,52 @@ +--- +name: dependency-audit +description: "What a project actually pulls in, which version has a known hole, and what a fix would break. Use when working on: supply-chain, audit, dependencies." +license: MIT +metadata: + category: dev + tags: supply-chain, audit, dependencies + optional-tools: nmap +--- + +# Dependency and supply-chain audit + +The question is not "is this package popular". It is "which of these things runs +in my build, at which version, and what would a compromise look like". + +## Order of steps + +1. **Build the real list.** The lockfile, not the manifest. `pip freeze`, + `npm ls --all`, `cargo tree`, `go list -m all`. Transitive dependencies are + most of the surface and none of the attention. +2. **Pin what you report.** Version, resolved URL, and the hash if the tool + records one. A finding without a version is not reproducible. +3. **Check for known holes against a source you name.** The advisory database + and its date; "probably fine" is not a result. +4. **Look at what changed recently.** A dependency that was stable for two + years and shipped three releases this month is a different risk from one + that has not moved — including the risk of an abandoned package being taken + over. +5. **Ask what it can reach.** A build-time dependency that runs arbitrary code + in CI is a different finding from a runtime library that parses your input. +6. **Write the fix with its blast radius.** Upgrade, replace, or pin-and-wait; + and what breaks if you do. + +## What people get wrong + +- Auditing only direct dependencies. +- Trusting a version range. `>=1.0` in a manifest resolves to whatever was + newest at build time, which is not the thing you tested. +- Ignoring the install scripts. `postinstall` and `build.rs` run before your + first line of code does. + +## Definition of done + +A table of dependencies with version and advisory status, the two or three that +actually matter ranked by reachability, and a concrete upgrade plan with what +it would break. + +## With the tools here + +No dedicated tool is required; the package managers do the listing. This skill +is the procedure. `nmap` is listed only because an audit sometimes ends with +"and what is actually exposed on the box that runs it". diff --git a/src/nerveforge/toolkit/skills/disk-forensics/SKILL.md b/src/nerveforge/toolkit/skills/disk-forensics/SKILL.md new file mode 100644 index 0000000..81d2cec --- /dev/null +++ b/src/nerveforge/toolkit/skills/disk-forensics/SKILL.md @@ -0,0 +1,54 @@ +--- +name: disk-forensics +description: "Read a disk image without changing it: partitions, timelines, deleted files. Use when working on: forensics, disk, timeline." +license: MIT +metadata: + category: forensics + tags: forensics, disk, timeline + tools: sleuthkit + optional-tools: plaso, exiftool +--- + +# Disk and filesystem forensics + +Read the disk, never mount it read-write. Every step below is designed so that +the original image is still the original image when you are done. + +## Order of steps + +1. **Hash, then work from the copy.** `sha256sum image.dd`. If the acquisition + log says otherwise, the log is your first finding. +2. **Partition layout.** `mmls image.dd` — partition table, offsets, sizes. + An unexpected partition is not "weird", it is the next thing to examine. +3. **Filesystem inventory.** `fls -r -p -o OFFSET image.dd` for a recursive + listing with full paths. Note that `fls` shows deleted entries with a `*`; + those are candidates, not results. +4. **Timeline.** `fls -m / -o OFFSET` piped into `mactime`, or `plaso` when + you want a body file across many artefacts. A timeline without a question is + a wall; start from the moment of interest and move outward. +5. **Extract specific files.** `icat -o OFFSET image.dd INODE > out.bin`, then + hash the extracted file and keep the inode in the report. +6. **Deleted data.** Only after the live filesystem is understood. Recovery is + `tsk_recover` into a fresh directory; unallocated space is a separate pass. +7. **Report with provenance.** Every claim needs image hash, offset, inode. + +## What people get wrong + +- Mounting loopback "just to look". Mount changes access times and gives every + other tool a chance to write. +- Treating `mactime` output as truth for MACB. The four timestamps have + different reliability per filesystem; say which one your conclusion rests on. +- Chasing deleted files before the live ones. Usually the answer is in files + that were never deleted. + +## Definition of done + +A list of files that matter with inode, offset and extracted hash, plus a +timeline slice that supports the narrative — and an original image whose hash +still matches the acquisition. + +## With the tools here + +The Sleuth Kit (`mmls`, `fls`, `icat`, `tsk_recover`) does the filesystem work. +`plaso` builds the super-timeline when there is more than one artefact source. +`exiftool` for the metadata of anything you extract. diff --git a/src/nerveforge/toolkit/skills/dynamic-tracing/SKILL.md b/src/nerveforge/toolkit/skills/dynamic-tracing/SKILL.md new file mode 100644 index 0000000..03a5e7f --- /dev/null +++ b/src/nerveforge/toolkit/skills/dynamic-tracing/SKILL.md @@ -0,0 +1,55 @@ +--- +name: dynamic-tracing +description: "Watch a program do the thing: breakpoints, syscall traces, and what to record while it runs. Use when working on: debugging, runtime." +license: MIT +metadata: + category: re + tags: debugging, runtime + tools: gdb + optional-tools: x64dbg, frida +--- + +# Dynamic tracing + +Static analysis tells you what the code can do. Running it tells you what it +does. The gap between the two is where most bugs and most secrets are. + +## Order of steps + +1. **Decide what you are looking for before you run anything.** One question, + written down: "which function decides the exit code", "where does this key + become that ciphertext". Tracing without a question produces a log nobody + reads. +2. **Set the smallest breakpoint that answers it.** A breakpoint on the + writer, the syscall or the comparison — not on `main` "to warm up". +3. **Record, don't watch.** Use a command list (`gdb -x`) or a script so the + run is repeatable and the output is a file. A session you cannot replay is + an anecdote. +4. **Move outward only when stuck.** If the breakpoint never fires, the branch + you assumed was taken is not taken — that is information, not failure. +5. **Capture the state at the boundary.** Registers, stack, and the memory the + pointer points at, saved at the moment of interest. Later questions should + be answerable from the dump. +6. **Re-read the disassembly with the trace in hand.** The dynamic run is how + you choose which static function matters. + +## What people get wrong + +- Single-stepping through library code. Step over, or set the breakpoint past + it; the standard library is not your target. +- Debugging a release build without symbols and calling the result noise. Build + with symbols when you can; when you cannot, breakpoint on imports instead. +- Forgetting that the trace changes the program. Anti-debug checks, timing + checks and race behaviour all notice a debugger. + +## Definition of done + +You can point at a specific address and say: this is where the value I care +about is computed, here is its input, here is its output. A saved log backs it. + +## With the tools here + +`gdb` on Linux, `x64dbg` on Windows. `frida` is the right tool when the target +is already running (or is a mobile app) and you want to hook a function rather +than stop the world. The x64dbg MCP servers expose breakpoints and memory to an +agent, so the loop above can run from the panel. diff --git a/src/nerveforge/toolkit/skills/firmware-iot/SKILL.md b/src/nerveforge/toolkit/skills/firmware-iot/SKILL.md new file mode 100644 index 0000000..32f4138 --- /dev/null +++ b/src/nerveforge/toolkit/skills/firmware-iot/SKILL.md @@ -0,0 +1,55 @@ +--- +name: firmware-iot +description: "Find the filesystem inside a firmware blob, then the interesting binaries inside that. Use when working on: firmware, iot, embedded." +license: MIT +metadata: + category: forensics + tags: firmware, iot, embedded + tools: binwalk + optional-tools: strings, ghidra, sleuthkit +--- + +# Firmware and embedded images + +A firmware blob is usually a bootloader, a compressed kernel, a filesystem, and +some vendor code, glued together without an index. You are rebuilding the index. + +## Order of steps + +1. **Identify the container.** `binwalk firmware.bin` for signatures: U-Boot, + squashfs, JFFS2, cramfs, LZMA, gzip. The header tells you where the pieces + start; it does not tell you where they end. +2. **Extract, then check the extraction.** `binwalk -e` writes a directory per + match. Open the largest result first — that is usually the filesystem. +3. **Filesystem first, binaries second.** Inside, `etc/init.d`, `etc/passwd`, + `etc/shadow`, dropbear keys, web roots. Vendors ship secrets in images far + more often than in apps. +4. **Architecture census.** `file` on every binary in `/bin` and `/usr/bin`. + MIPS, ARM little and big endian, and a stray x86 binary are all common; the + odd one out is often the newest code and the least tested. +5. **Find the update path.** How does the device accept firmware? Signed or + not, checksummed or not. This is where the interesting findings live. +6. **Hardcoded keys and backdoors** — search for private keys, hardcoded SSH + credentials, and debug endpoints switched on in the release build. +7. **Only then decompile** one or two binaries, starting with the web server or + the update daemon. + +## What people get wrong + +- Trusting `binwalk -e` output size. Extraction can fail quietly on truncated + images; compare offsets to the original blob. +- Assuming the root filesystem is the whole story. There is usually a second + partition — user data or a recovery image — with the older, weaker code. +- Running `emulation "to see the UI"` on your own network. A device that boots + under QEMU is a device making network calls; isolate it first. + +## Definition of done + +A list of the partitions and filesystems with offsets, the architecture map, +and the update mechanism's trust decision explained in one paragraph. + +## With the tools here + +`binwalk` for discovery and extraction, `strings` for fast sweeps, `ghidra` for +the binaries you chose to look at. `sleuthkit` when the extracted piece is a +real filesystem with deleted files in it. diff --git a/src/nerveforge/toolkit/skills/function-recovery/SKILL.md b/src/nerveforge/toolkit/skills/function-recovery/SKILL.md new file mode 100644 index 0000000..25b6e42 --- /dev/null +++ b/src/nerveforge/toolkit/skills/function-recovery/SKILL.md @@ -0,0 +1,56 @@ +--- +name: function-recovery +description: "Rebuild a function map from a stripped binary, then name things until the code reads. Use when working on: reversing, decompiler, symbols." +license: MIT +metadata: + category: re + tags: reversing, decompiler, symbols + tools: ghidra + optional-tools: radare2, ida, binaryninja, capstone +--- + +# Function and symbol recovery + +A stripped binary is not unreadable, it is unnamed. The work is to name things +until the code explains itself. + +## Order of steps + +1. **Let the decompiler do its pass first.** Import, run auto-analysis, and + only then look. Reading a half-analysed database is how people conclude the + binary is obfuscated when it was merely not analysed. +2. **Start from the edges, not the middle.** Imports tell you what the program + touches; strings tell you what it says. Find the functions that reference + them — those are the boundary with the outside world and always have a + meaning you can name. +3. **Name as you go, in the program's vocabulary.** `read_config`, + `verify_license`, `decrypt_blob`. A renamed function is a docstring that + compilers cannot strip. Resist `sub_401000 → do_stuff`. +4. **Type the data, not just the code.** A `char*` that is always 16 bytes long + is a hash. Re-type it and the surrounding code usually simplifies. +5. **Follow the call graph down.** From the entry points inward, breadth + first. Depth first on a large binary is how a day disappears into one + function's bit tricks. +6. **Write the map down.** Function, purpose, evidence. It is what a reviewer + reads and what you will need tomorrow. + +## What people get wrong + +- Starting at `main`. It is often the least interesting function: a dispatcher. +- Ignoring the C++ runtime. `std::string` and `std::vector` shapes repeat; + learn them once and hundreds of functions become readable. +- Renaming without evidence. A wrong name is worse than `sub_...`, because the + next person believes it. + +## Definition of done + +The three or four functions that carry the logic have names, types and a +one-line purpose each, and you can narrate the program's flow from entry to +output without opening the disassembly again. + +## With the tools here + +`ghidra` gives you the decompiler and the database. `radare2` is the terminal +route and scripts well when you want to batch-rename. The MCP bridges +(`ida-pro-mcp`, `GhidraMCP`) let an agent drive the same database directly — +see the MCP tab, and prefer them for the rename-heavy middle of the work. diff --git a/src/nerveforge/toolkit/skills/malware-static/SKILL.md b/src/nerveforge/toolkit/skills/malware-static/SKILL.md new file mode 100644 index 0000000..66283a1 --- /dev/null +++ b/src/nerveforge/toolkit/skills/malware-static/SKILL.md @@ -0,0 +1,63 @@ +--- +name: malware-static +description: "IOCs and behaviour from a sample without running it — and the rules that keep it that way. Use when working on: malware, ioc, static." +license: MIT +metadata: + category: malware + tags: malware, ioc, static + tools: strings + optional-tools: yara, binwalk, exiftool, ghidra +--- + +# Malware static analysis + +Everything here happens without executing the sample. That is the point: the +first rule of analysis is that you do not run the thing to find out what it +does. + +## Ground rules + +- Sample in a directory you created for it, mode `0700`, never opened by an + editor that might preview it. +- No double-click, no `strings | less` on a file whose name implies danger — + reading is fine, executing is not. +- Hash before and after every step. If the hash changes, you changed the + evidence. + +## Order of steps + +1. **Hashes and metadata.** SHA-256, size, file type, compile timestamp, + packer hints. Record them; they are the only stably citable facts. +2. **Container and sections.** PE/ELF/Mach-O, section names and entropy, + overlay. See `binary-triage` for the exact commands. +3. **Strings as indicators.** Not a word list — a hypothesis list. Domains, + IPs, mutexes, registry paths, user agents, error messages stolen from a + known framework. +4. **Imports and capabilities.** Which APIs would it need to do the thing the + strings hint at? A sample that talks about persistence but imports nothing + that writes to disk is telling you something. +5. **Unpack if needed** — a separate, careful step. Dump, verify the entry + point, re-triage from step 2. +6. **Write it down** before deeper reversing: a table of artefacts, a + behaviour narrative, and a confidence level per claim. + +## What people get wrong + +- Reporting strings as behaviour. "Contains the URL evil.example" is an + observation; "contacts evil.example" is a claim you have not earned. +- Believing the compile timestamp. It is attacker-controlled in every format + that has one. +- Skipping the boring sample. Most real incidents are a commodity family; the + fast identification is the value. + +## Definition of done + +An IOC table (file, network, host artefacts), a one-paragraph behaviour +summary with claims marked observed vs inferred, and a YARA rule that fires on +the sample and not on a clean corpus. + +## With the tools here + +`strings`, `binwalk` and `exiftool` cover the static pass. `yara` turns the +result into something reusable — see `yara-authoring`. `ghidra` when a +capability needs proving rather than inferring. diff --git a/src/nerveforge/toolkit/skills/memory-forensics/SKILL.md b/src/nerveforge/toolkit/skills/memory-forensics/SKILL.md new file mode 100644 index 0000000..9d42f7a --- /dev/null +++ b/src/nerveforge/toolkit/skills/memory-forensics/SKILL.md @@ -0,0 +1,56 @@ +--- +name: memory-forensics +description: "Processes, network connections and injected code out of a RAM image, in that order. Use when working on: forensics, memory, dfir." +license: MIT +metadata: + category: forensics + tags: forensics, memory, dfir + tools: volatility3 + optional-tools: yara +--- + +# Memory forensics + +A RAM image is the only place where "what was running" is a fact rather than an +inference. It is also the most fragile evidence you will touch. + +## Order of steps + +1. **Hash the image before analysis**, and work from a copy. Every tool writes + caches; a changed image is a contested image. +2. **Identify the image.** `vol -f image.raw windows.info` / `linux.info` (or + `banners`). Symbols matter: without them most plugins will refuse, and a + guessed profile is worse than no answer. +3. **Processes before everything else.** `pslist`, then `pstree`, then + `psscan`. The three disagree for a reason — `psscan` finds terminated and + unlinked processes, and the difference between the lists is the finding. +4. **Network second.** `netscan` / `netstat`. Match listening ports to the + process that should own them; a listener with no matching process is what a + rootkit looks like from here. +5. **Injected code.** `malfind` and `vadinfo`. A region that is executable and + private and has no file backing it deserves a dump and a look. +6. **Persistence and credentials** last, because they are noisy: services, + startup entries, loaded modules. +7. **Timeline what you found.** Order is the argument; a list of artefacts is + not an incident. + +## What people get wrong + +- Running `strings` first. It buries the process table in noise and teaches you + nothing about execution order. +- Trusting one plugin. Cross-view (list vs scan, with vs without) is the + method; a single clean `pslist` does not mean a clean machine. +- Forgetting that memory is a snapshot of a changing system. Two images taken + a minute apart are not two views of the same state. + +## Definition of done + +A process tree with the suspicious ones marked, network connections tied to +processes, and a short narrative that a second analyst could check against the +image without redoing the discovery. + +## With the tools here + +Volatility 3 is the engine. `yara` on dumped regions is how you go from +"suspicious" to "this family". For a disk image alongside this one, see +`disk-forensics`; the two timelines should agree. diff --git a/src/nerveforge/toolkit/skills/native-debugging/SKILL.md b/src/nerveforge/toolkit/skills/native-debugging/SKILL.md new file mode 100644 index 0000000..1b0ae01 --- /dev/null +++ b/src/nerveforge/toolkit/skills/native-debugging/SKILL.md @@ -0,0 +1,53 @@ +--- +name: native-debugging +description: "From a crash to the line that caused it: cores, symbols, and the checklist that finds the frame. Use when working on: debugging, crash, c." +license: MIT +metadata: + category: dev + tags: debugging, crash, c + tools: gdb + optional-tools: objdump +--- + +# Crash and native debugging + +A crash is a question the program asked and the OS answered by killing it. The +job is to turn the answer back into a question. + +## Order of steps + +1. **Read the signal first, not the stack.** `SIGSEGV` at address `0x0` and + `SIGABRT` after a `free()` are different stories. `dmesg | tail` has the + faulting address and often the offset. +2. **Get symbols or get offsets.** A core without symbols still has frames; + `bt` gives you addresses, `addr2line` and the build's `.debug` file turn + them into lines. Reproduce with `-g -O0` if you build the target yourself. +3. **Find the first bad frame, working up.** The frame that crashed is usually + innocent; the one that passed a bad pointer is the culprit. +4. **Print the invariants.** For the suspected frame: the pointer, whether it + is NULL/freed/overwritten, and when it was last valid. A watchpoint answers + "when did this change" faster than stepping. +5. **Reduce to a minimal reproduction.** Fewer inputs, fewer threads, fewer + features. A crash you cannot reproduce on demand is not fixed, only + postponed. +6. **Then fix, and add the test that would have caught it.** The test is part + of the fix. + +## What people get wrong + +- Rebuilding with optimisations changed and calling it the same bug. `-O2` + inlining moves the fault; keep the original build for the diagnosis. +- Reading the stack top-down as if the top frame were the cause. +- Debugging threads by pausing them. A data race that disappears under a + debugger was still a data race. + +## Definition of done + +A reproduction command, the frame and line at fault, the value that was wrong +and why, plus a test that fails before the fix and passes after. + +## With the tools here + +`gdb` for cores and live sessions; `objdump` when you need to look at the +instruction the faulting address lands in. For Windows binaries, the same +method applies with `x64dbg` — see `dynamic-tracing`. diff --git a/src/nerveforge/toolkit/skills/protocol-reversing/SKILL.md b/src/nerveforge/toolkit/skills/protocol-reversing/SKILL.md new file mode 100644 index 0000000..5ff07b0 --- /dev/null +++ b/src/nerveforge/toolkit/skills/protocol-reversing/SKILL.md @@ -0,0 +1,57 @@ +--- +name: protocol-reversing +description: "Turn captured traffic into a message grammar, then into a client that can speak it. Use when working on: network, protocol, pcap." +license: MIT +metadata: + category: protocol + tags: network, protocol, pcap + tools: tshark + optional-tools: scapy, strings +--- + +# Protocol reversing + +A capture is a recording, not a specification. The job is to turn it into a +grammar and then into a client that can talk. + +## Order of steps + +1. **Get a second capture before decoding the first.** One session cannot show + you which bytes are fixed and which are data. Two sessions of the *same* + action, with one thing changed between them, can. +2. **Start at the transport, not the payload.** Ports, TLS, length prefixes. + If it is TLS and you are authorised, note that and say where a key would + come from; if it is not, `tshark -d tcp.port==NNNN,foo` gives you a stream + you can follow by eye. +3. **Find the framing.** Every protocol answers "where does this message end". + Length field, delimiter, TCP segment, or nothing at all. Everything else is + easier once you know. +4. **Diff two requests that differ in one field.** Human memory is bad at hex; + a diff is good at it. This is the single highest-value step. +5. **Guess the encoding of each field separately.** Integers big/little endian, + timestamps as epoch or tick count, ids as random or sequential, strings as + UTF-8/UTF-16/null-padded. +6. **Write the parser, then the generator.** A `scapy` layer that can both + dissect and build is the compact way to prove you understand the format: + if you can re-encode a captured message byte for byte, the grammar is right. + +## What people get wrong + +- Believing a checksum is encryption. If flipping a byte makes the field change + predictably, it is a checksum. +- Ignoring compression. The "random 40 bytes" in the middle is often zlib or + brotli, and `strings` on the decompressed payload answers half the questions. +- Reversing the protocol when the client is easier to read. If there is a + binary client, `binary-triage` may get you there faster. + +## Definition of done + +A message can be described field by field, a captured request can be +reconstructed exactly, and you can name the checksum, the framing and the +encoding of every field. A crafted request gets a sensible reply. + +## With the tools here + +`tshark` for reading and extracting fields from captures, `scapy` for the +parser/generator. When the endpoint is HTTP with signed requests, capture the +signing function once and the rest is `dynamic-tracing`. diff --git a/src/nerveforge/toolkit/skills/yara-authoring/SKILL.md b/src/nerveforge/toolkit/skills/yara-authoring/SKILL.md new file mode 100644 index 0000000..638c032 --- /dev/null +++ b/src/nerveforge/toolkit/skills/yara-authoring/SKILL.md @@ -0,0 +1,51 @@ +--- +name: yara-authoring +description: "A rule that catches the family without catching the operating system. Use when working on: yara, detection." +license: MIT +metadata: + category: forensics + tags: yara, detection + tools: yara + optional-tools: strings +--- + +# Writing YARA rules + +A rule has two jobs: match the family, and not match everything else. Most +published rules do the first and skip the second. + +## Order of steps + +1. **Collect, don't invent.** Strings come from samples you have (`strings + -n 6`), not from your imagination of what malware would say. +2. **Prefer structure to text.** Section names, import combinations, a + distinctive sequence of API calls, a size range. Text changes between + builds; structure survives recompilation. +3. **Pick the strongest few, not the most many.** Three good strings beat + thirty ordinary ones; the ordinary ones are what create false positives. +4. **Write the condition in the language of your intent.** `2 of them and + filesize < 2MB` says something; `any of them` says "I hope". +5. **Test against a corpus you did not write the rule on.** Clean system files + first, then the family, then a near-miss (a different version, a packer). +6. **Name and date it.** `Family_Behaviour_YYYYMMDD`. A rule without a date is + a rule nobody can maintain. + +## What people get wrong + +- `$s1 = "http://"`. That is a rule for the internet. +- Wide strings on a sample that only uses ASCII, or the reverse. `.wide` and + `ascii` are cheap; say which one you mean. +- Ignoring performance. A rule with unbounded regex over a whole disk image + costs the analyst an hour per run; anchor and bound the pattern. + +## Definition of done + +The rule fires on every sample from the family you have, fires on none of your +clean corpus, states which strings are load-bearing, and comes with a one-line +note on how someone would extend it. + +## With the tools here + +`yara` runs the rules; `strings` feeds them. When the rule is meant to catch a +memory-resident implant rather than a file, test it against `malfind` dumps +from `memory-forensics`. diff --git a/src/nerveforge/toolkit/skills/android-apk.md b/src/nerveforge/toolkit/skills_flat/android-apk.md similarity index 95% rename from src/nerveforge/toolkit/skills/android-apk.md rename to src/nerveforge/toolkit/skills_flat/android-apk.md index 69c7ee6..5beed3a 100644 --- a/src/nerveforge/toolkit/skills/android-apk.md +++ b/src/nerveforge/toolkit/skills_flat/android-apk.md @@ -1,10 +1,3 @@ ---- -id: android-apk -category: mobile -tools: [jadx] -optional: [apktool, adb, frida] ---- - # Android APK analysis An APK is a zip with opinions. Rust, Kotlin, Flutter and React Native all ship diff --git a/src/nerveforge/toolkit/skills/binary-triage.md b/src/nerveforge/toolkit/skills_flat/binary-triage.md similarity index 94% rename from src/nerveforge/toolkit/skills/binary-triage.md rename to src/nerveforge/toolkit/skills_flat/binary-triage.md index 5b379f9..a639c8e 100644 --- a/src/nerveforge/toolkit/skills/binary-triage.md +++ b/src/nerveforge/toolkit/skills_flat/binary-triage.md @@ -1,10 +1,3 @@ ---- -id: binary-triage -category: re -tools: [strings, objdump] -optional: [binwalk, yara, lief, capstone] ---- - # Binary triage The first ten minutes decide whether the next two hours are wasted. Do not open diff --git a/src/nerveforge/toolkit/skills/dependency-audit.md b/src/nerveforge/toolkit/skills_flat/dependency-audit.md similarity index 96% rename from src/nerveforge/toolkit/skills/dependency-audit.md rename to src/nerveforge/toolkit/skills_flat/dependency-audit.md index 95c472c..b2ae628 100644 --- a/src/nerveforge/toolkit/skills/dependency-audit.md +++ b/src/nerveforge/toolkit/skills_flat/dependency-audit.md @@ -1,10 +1,3 @@ ---- -id: dependency-audit -category: dev -tools: [] -optional: [nmap] ---- - # Dependency and supply-chain audit The question is not "is this package popular". It is "which of these things runs diff --git a/src/nerveforge/toolkit/skills/disk-forensics.md b/src/nerveforge/toolkit/skills_flat/disk-forensics.md similarity index 95% rename from src/nerveforge/toolkit/skills/disk-forensics.md rename to src/nerveforge/toolkit/skills_flat/disk-forensics.md index 53b4953..8d92505 100644 --- a/src/nerveforge/toolkit/skills/disk-forensics.md +++ b/src/nerveforge/toolkit/skills_flat/disk-forensics.md @@ -1,10 +1,3 @@ ---- -id: disk-forensics -category: forensics -tools: [sleuthkit] -optional: [plaso, exiftool] ---- - # Disk and filesystem forensics Read the disk, never mount it read-write. Every step below is designed so that diff --git a/src/nerveforge/toolkit/skills/dynamic-tracing.md b/src/nerveforge/toolkit/skills_flat/dynamic-tracing.md similarity index 96% rename from src/nerveforge/toolkit/skills/dynamic-tracing.md rename to src/nerveforge/toolkit/skills_flat/dynamic-tracing.md index 8358dbe..d634b42 100644 --- a/src/nerveforge/toolkit/skills/dynamic-tracing.md +++ b/src/nerveforge/toolkit/skills_flat/dynamic-tracing.md @@ -1,10 +1,3 @@ ---- -id: dynamic-tracing -category: re -tools: [gdb] -optional: [x64dbg, frida] ---- - # Dynamic tracing Static analysis tells you what the code can do. Running it tells you what it diff --git a/src/nerveforge/toolkit/skills/firmware-iOT.md b/src/nerveforge/toolkit/skills_flat/firmware-iot.md similarity index 95% rename from src/nerveforge/toolkit/skills/firmware-iOT.md rename to src/nerveforge/toolkit/skills_flat/firmware-iot.md index b4a70eb..d387ec5 100644 --- a/src/nerveforge/toolkit/skills/firmware-iOT.md +++ b/src/nerveforge/toolkit/skills_flat/firmware-iot.md @@ -1,10 +1,3 @@ ---- -id: firmware-iOT -category: forensics -tools: [binwalk] -optional: [strings, ghidra, sleuthkit] ---- - # Firmware and embedded images A firmware blob is usually a bootloader, a compressed kernel, a filesystem, and diff --git a/src/nerveforge/toolkit/skills/function-recovery.md b/src/nerveforge/toolkit/skills_flat/function-recovery.md similarity index 95% rename from src/nerveforge/toolkit/skills/function-recovery.md rename to src/nerveforge/toolkit/skills_flat/function-recovery.md index 7fa126a..3d9a8be 100644 --- a/src/nerveforge/toolkit/skills/function-recovery.md +++ b/src/nerveforge/toolkit/skills_flat/function-recovery.md @@ -1,10 +1,3 @@ ---- -id: function-recovery -category: re -tools: [ghidra] -optional: [radare2, ida, binaryninja, capstone] ---- - # Function and symbol recovery A stripped binary is not unreadable, it is unnamed. The work is to name things diff --git a/src/nerveforge/toolkit/skills/malware-static.md b/src/nerveforge/toolkit/skills_flat/malware-static.md similarity index 95% rename from src/nerveforge/toolkit/skills/malware-static.md rename to src/nerveforge/toolkit/skills_flat/malware-static.md index 89c1a6d..bd540b5 100644 --- a/src/nerveforge/toolkit/skills/malware-static.md +++ b/src/nerveforge/toolkit/skills_flat/malware-static.md @@ -1,10 +1,3 @@ ---- -id: malware-static -category: malware -tools: [strings] -optional: [yara, binwalk, exiftool, ghidra] ---- - # Malware static analysis Everything here happens without executing the sample. That is the point: the diff --git a/src/nerveforge/toolkit/skills/memory-forensics.md b/src/nerveforge/toolkit/skills_flat/memory-forensics.md similarity index 96% rename from src/nerveforge/toolkit/skills/memory-forensics.md rename to src/nerveforge/toolkit/skills_flat/memory-forensics.md index 1193dbb..5781a59 100644 --- a/src/nerveforge/toolkit/skills/memory-forensics.md +++ b/src/nerveforge/toolkit/skills_flat/memory-forensics.md @@ -1,10 +1,3 @@ ---- -id: memory-forensics -category: forensics -tools: [volatility3] -optional: [yara] ---- - # Memory forensics A RAM image is the only place where "what was running" is a fact rather than an diff --git a/src/nerveforge/toolkit/skills/native-debugging.md b/src/nerveforge/toolkit/skills_flat/native-debugging.md similarity index 96% rename from src/nerveforge/toolkit/skills/native-debugging.md rename to src/nerveforge/toolkit/skills_flat/native-debugging.md index 22efc58..f5b4113 100644 --- a/src/nerveforge/toolkit/skills/native-debugging.md +++ b/src/nerveforge/toolkit/skills_flat/native-debugging.md @@ -1,10 +1,3 @@ ---- -id: native-debugging -category: dev -tools: [gdb] -optional: [objdump] ---- - # Crash and native debugging A crash is a question the program asked and the OS answered by killing it. The diff --git a/src/nerveforge/toolkit/skills/protocol-reversing.md b/src/nerveforge/toolkit/skills_flat/protocol-reversing.md similarity index 96% rename from src/nerveforge/toolkit/skills/protocol-reversing.md rename to src/nerveforge/toolkit/skills_flat/protocol-reversing.md index f29d324..3a345d3 100644 --- a/src/nerveforge/toolkit/skills/protocol-reversing.md +++ b/src/nerveforge/toolkit/skills_flat/protocol-reversing.md @@ -1,10 +1,3 @@ ---- -id: protocol-reversing -category: protocol -tools: [tshark] -optional: [scapy, strings] ---- - # Protocol reversing A capture is a recording, not a specification. The job is to turn it into a diff --git a/src/nerveforge/toolkit/skills/yara-authoring.md b/src/nerveforge/toolkit/skills_flat/yara-authoring.md similarity index 95% rename from src/nerveforge/toolkit/skills/yara-authoring.md rename to src/nerveforge/toolkit/skills_flat/yara-authoring.md index 4e4c5b9..c5e2606 100644 --- a/src/nerveforge/toolkit/skills/yara-authoring.md +++ b/src/nerveforge/toolkit/skills_flat/yara-authoring.md @@ -1,10 +1,3 @@ ---- -id: yara-authoring -category: forensics -tools: [yara] -optional: [strings] ---- - # Writing YARA rules A rule has two jobs: match the family, and not match everything else. Most diff --git a/tests/test_http_layer.py b/tests/test_http_layer.py index 9c6cf9e..f877544 100644 --- a/tests/test_http_layer.py +++ b/tests/test_http_layer.py @@ -15,6 +15,34 @@ class RouteTableTests(unittest.TestCase): + def test_a_specific_route_wins_over_a_prefix_that_also_covers_it(self): + """`/api/skills/*` must not swallow `/api/skills/bundle`. + + A prefix cannot say where a path ends, so registration order decided + this before — and a route added underneath an existing prefix silently + went to the wrong handler. + """ + import re + + table = RouteTable() + table.add("one", lambda h, p: "one", methods=("GET",), prefixes=("/api/skills/",)) + table.add("bundle", lambda h, p: "bundle", methods=("GET",), exact=("/api/skills/bundle",)) + table.add("doc", lambda h, p: "doc", methods=("GET",), + pattern=re.compile(r"^/api/skills/[^/]+/SKILL\.md$")) + self.assertEqual(table.resolve("/api/skills/binary-triage").name, "one") + self.assertEqual(table.resolve("/api/skills/bundle", "GET").name, "bundle") + self.assertEqual(table.resolve("/api/skills/binary-triage/SKILL.md", "GET").name, "doc") + + def test_a_pattern_with_the_wrong_method_still_beats_a_prefix(self): + """405 for the right resource, not 200 from the wrong handler.""" + import re + + table = RouteTable() + table.add("one", lambda h, p: None, methods=("GET",), prefixes=("/api/skills/",)) + table.add("doc", lambda h, p: None, methods=("GET",), + pattern=re.compile(r"^/api/skills/[^/]+/SKILL\.md$")) + self.assertEqual(table.resolve("/api/skills/x/SKILL.md", "POST").name, "doc") + def test_exact_prefix_and_pattern_matching(self): table = RouteTable() table.add("a", lambda h, p: None, methods=("GET",), exact=("/api/a",)) diff --git a/tests/test_toolkit_registry.py b/tests/test_toolkit_registry.py index 8b35194..a3bc45d 100644 --- a/tests/test_toolkit_registry.py +++ b/tests/test_toolkit_registry.py @@ -166,9 +166,73 @@ def test_every_skill_names_only_known_tools(self): def test_a_missing_file_degrades_to_the_summary(self): skill = skillcatalog.BY_ID["binary-triage"] - with mock.patch.object(skillcatalog, "SKILLS_DIR", Path("/nonexistent")): + with mock.patch.object(skillcatalog, "SKILLS_DIR", Path("/nonexistent")), \ + mock.patch.object(skillcatalog, "LEGACY_SKILLS_DIR", Path("/nonexistent")): self.assertIn(skill.summary, skillcatalog.body(skill)) + def test_skill_files_follow_the_agent_skills_layout(self): + """`skills//SKILL.md`, with the folder and the name in agreement.""" + for skill in skillcatalog.CATALOGUE: + with self.subTest(skill=skill.id): + path = skillcatalog.skill_path(skill) + self.assertEqual(path.name, "SKILL.md") + self.assertEqual(path.parent.name, skill.id) + self.assertTrue(path.is_file()) + + def test_every_name_satisfies_the_spec(self): + for skill in skillcatalog.CATALOGUE: + with self.subTest(skill=skill.id): + self.assertTrue(skillcatalog.name_is_valid(skill.id), skill.id) + self.assertLessEqual(len(skillcatalog.description(skill)), 1024) + + def test_the_skills_are_packaged_as_data(self): + """An installed bridge must ship the files, not only the catalogue. + + Read as text rather than with `tomllib`: that module is 3.11+, and this + project supports 3.10 — the first CI run of this test failed on exactly + that import while the syntax it guards is version-independent. + """ + root = Path(__file__).resolve().parents[1] + text = (root / "pyproject.toml").read_text(encoding="utf-8") + start = text.find("[tool.setuptools.package-data]") + self.assertNotEqual(start, -1, "package-data section is missing") + # Up to the next section header, which is the line starting with "[". + rest = text[start:].split("\n", 1)[1] + section = rest.split("\n[", 1)[0] + self.assertIn("toolkit/skills/", section) + + def test_the_generated_front_matter_is_the_spec_fields(self): + skill = skillcatalog.BY_ID["binary-triage"] + block = skillcatalog.front_matter(skill, version="9.9.9") + self.assertTrue(block.startswith("---\nname: binary-triage\n")) + self.assertIn("\ndescription: ", block) + self.assertIn("\nlicense: MIT\n", block) + self.assertIn("\nmetadata:\n category: re\n", block) + self.assertIn(" tools: strings, objdump\n", block) + self.assertIn(" version: 9.9.9\n", block) + self.assertTrue(block.endswith("---")) + + def test_a_description_with_a_colon_is_quoted(self): + skill = skillcatalog.BY_ID["binary-triage"] + # "First ten minutes with an unknown file: what it is" would be read as + # a mapping by a YAML parser without the quotes. + self.assertIn('description: "', skillcatalog.front_matter(skill)) + + def test_the_document_carries_the_prose_and_the_metadata(self): + skill = skillcatalog.BY_ID["yara-authoring"] + text = skillcatalog.document(skill, version="1.2.3") + self.assertIn("name: yara-authoring", text) + self.assertIn(" version: 1.2.3", text) + self.assertIn("# Writing YARA rules", text) + # The metadata block appears once, not in front of every paragraph. + self.assertEqual(text.count("---\n"), 2) + + def test_the_body_drops_the_front_matter(self): + skill = skillcatalog.BY_ID["binary-triage"] + body = skillcatalog.skill_body(skill) + self.assertFalse(body.lstrip().startswith("---")) + self.assertTrue(body.startswith("# Binary triage")) + def test_categories_and_search(self): self.assertEqual(sum(skillcatalog.categories().values()), len(skillcatalog.CATALOGUE)) self.assertEqual([s.id for s in skillcatalog.search("yara")], ["yara-authoring"]) diff --git a/tests/test_toolkit_routes.py b/tests/test_toolkit_routes.py index 6fdd8b9..3a20c49 100644 --- a/tests/test_toolkit_routes.py +++ b/tests/test_toolkit_routes.py @@ -40,6 +40,15 @@ def send_json(self, obj, status=200, extra_headers=None): self.payload = obj return obj + def send_bytes(self, data, content_type, status=200, extra_headers=None): + # The skill export answers Markdown, so the double has to carry bytes + # and a content type the way the real handler does. + self.status = status + self.raw = data + self.content_type = content_type + self.payload = data.decode("utf-8") if isinstance(data, bytes) else data + return self.payload + class FakeService: def __init__(self): @@ -100,6 +109,105 @@ def app_with(service=None): return app +class SkillRouteWiringTests(unittest.TestCase): + """The real route table, because a mocked one would have hidden the bug. + + `skills_one` is registered with the prefix `/api/skills/`, and a prefix + cannot say where a path ends: before the router learned to prefer the more + specific rule, `/api/skills/bundle` was answered by the handler for one + skill, with `bundle` as its id. + """ + + def table(self): + from nerveforge.http.app import build_routes_only + + return build_routes_only() + + def test_each_skill_path_reaches_its_own_handler(self): + table = self.table() + expected = { + "/api/skills": "skills", + "/api/skills/binary-triage": "skills_one", + "/api/skills/binary-triage/SKILL.md": "skills_document", + "/api/skills/binary-triage/skill.md": "skills_document", + "/api/skills/bundle": "skills_bundle", + "/api/skills/binary-triage/validate": "skills_validate", + } + for path, name in expected.items(): + with self.subTest(path=path): + route = table.resolve(path, "GET") + self.assertIsNotNone(route, path) + self.assertEqual(route.name, name) + + def test_a_path_that_only_looks_like_a_skill_does_not_resolve_to_one(self): + table = self.table() + for path in ("/api/skills/a/b/SKILL.md", "/api/skills/a/b/c"): + with self.subTest(path=path): + # It falls through to `skills_one`, which refuses an id with a + # slash in it: the route says "some skill", the handler says + # "not this one". + route = table.resolve(path, "GET") + self.assertEqual(route.name, "skills_one", path) + with self.assertRaises(NotFound): + routes.get_skill(FakeHandler(app=app_with(), path=path), path) + + def test_a_skill_document_route_never_matches_two_segments(self): + self.assertIsNone(routes.SKILL_DOC_RE.match("/api/skills/a/b/SKILL.md")) + self.assertIsNone(routes.SKILL_VALIDATE_RE.match("/api/skills/a/b/validate")) + self.assertIsNotNone(routes.SKILL_DOC_RE.match("/api/skills/a/SKILL.md")) + + +class SkillDocumentTests(unittest.TestCase): + """The portable `SKILL.md`: what another agent client would actually read.""" + + def test_the_document_route_answers_markdown(self): + handler = FakeHandler(app=app_with(), path="/api/skills/binary-triage/SKILL.md") + routes.get_skill_document(handler, handler.path) + self.assertEqual(handler.content_type, "text/markdown; charset=utf-8") + self.assertTrue(handler.payload.startswith("---\nname: binary-triage\n")) + self.assertIn(" version: ", handler.payload) + + def test_both_spellings_of_the_suffix_work(self): + for suffix in ("SKILL.md", "skill.md"): + with self.subTest(suffix=suffix): + path = f"/api/skills/yara-authoring/{suffix}" + handler = FakeHandler(app=app_with(), path=path) + routes.get_skill_document(handler, path) + self.assertIn("name: yara-authoring", handler.payload) + + def test_an_unknown_skill_is_a_404(self): + for path in ("/api/skills/nope/SKILL.md", "/api/skills/a/b/SKILL.md", + "/api/skills//SKILL.md"): + with self.subTest(path=path): + with self.assertRaises(NotFound): + routes.get_skill_document(FakeHandler(app=app_with(), path=path), path) + + def test_the_bundle_carries_every_skill_once(self): + handler = FakeHandler(app=app_with()) + routes.get_skills_bundle(handler, "/api/skills/bundle") + rows = handler.payload["skills"] + self.assertEqual(len(rows), 12) + self.assertEqual(len({row["id"] for row in rows}), 12) + for row in rows: + self.assertTrue(row["path"].endswith("/SKILL.md")) + self.assertTrue(row["content"].startswith("---\nname: ")) + + def test_validation_names_the_problem_or_says_it_is_fine(self): + ok = FakeHandler(app=app_with(), path="/api/skills/binary-triage/validate") + routes.get_skill_validate(ok, ok.path) + self.assertTrue(ok.payload["valid"]) + self.assertEqual(ok.payload["problems"], []) + with self.assertRaises(NotFound): + routes.get_skill_validate(FakeHandler(app=app_with(), path="/api/skills/x/validate"), + "/api/skills/x/validate") + + def test_a_skill_body_does_not_repeat_its_metadata(self): + handler = FakeHandler(app=app_with(), path="/api/skills/binary-triage") + routes.get_skill(handler, handler.path) + self.assertFalse(handler.payload["body"].lstrip().startswith("---")) + self.assertEqual(handler.payload["name"], "binary-triage") + + class SkillsRouteTests(unittest.TestCase): def test_the_catalogue_and_one_skill(self): handler = FakeHandler(app=app_with()) @@ -493,8 +601,7 @@ def test_the_front_matter_example_matches_a_real_file(self): """The sample in the guide must be copyable, not a plausible invention.""" from nerveforge.toolkit import skillcatalog - real = (skillcatalog.SKILLS_DIR / "binary-triage.md").read_text(encoding="utf-8") - head = real.split("---", 2)[1].strip() + head = skillcatalog.front_matter(skillcatalog.BY_ID["binary-triage"]).split("---", 2)[1].strip() for path in (ROOT / "docs" / "TOOLKIT.md", ROOT / "docs" / "ru" / "TOOLKIT.md"): with self.subTest(document=path.name): text = path.read_text(encoding="utf-8") @@ -512,10 +619,12 @@ def test_every_route_is_registered_with_its_methods(self): table = mock.Mock() routes.register(table, mock.Mock()) names = {call.args[0] for call in table.add.call_args_list} - self.assertTrue({"skills", "skills_one", "tools", "tool_install", + self.assertTrue({"skills", "skills_one", "skills_document", "skills_bundle", + "skills_validate", "tools", "tool_install", "mcp_status", "mcp_call", "mcp_server_call"} <= names) for call in table.add.call_args_list: - self.assertTrue(call.kwargs.get("exact") or call.kwargs.get("prefixes")) + self.assertTrue(call.kwargs.get("exact") or call.kwargs.get("prefixes") + or call.kwargs.get("pattern"), call.args[0]) if __name__ == "__main__":