Skip to content

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

feat(skills): a spoken "create a skill …" is written by the assistant itself — and never captured by a skill it merely mentions

Harald0fdbee4a496c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3d7c5b7af4..94913ae594 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -95,9 +95,41 @@ versioning per [SemVer](https://semver.org/).
a working entry point with no card anywhere in the app, so selecting it meant
hand-editing `jarvis.toml`. Both Google recognizers now appear in Voice Input
with a model picker.
+- **Create a skill by voice — and it is a real skill, not your sentence in a
+ template.** "Erstell mir einen neuen Skill: Morgenroutine, jeden Morgen um 6
+ Uhr E-Mails, Tickets und Kalender vorlesen und dann ein 80er-Klassiker auf <!-- i18n-allow: quoted voice request -->
+ YouTube Music" now ends with a written skill: the assistant itself authors
+ the whole card — name, the spoken phrase that starts it, a schedule trigger
+ (`0 6 * * *`) when you named a time, numbered steps that each name the
+ connector actually attached right now (mail, calendar, tickets, music …) and
+ a spoken answer format — and files it as a draft you switch on in the Skills
+ view. New router tool `create-skill` (one bounded call, never a background
+ worker), the same author behind `POST /api/skills/creator/author` and the new
+ `jarvis skills create "<what it should do>" [--name] [--trigger] [--schedule]`.
+ - The author is a provider LADDER, not one model: your active provider first,
+ then the pinned Tool Model, then the API quality tier, then the frontier
+ chain — a rung without a key or that times out is crossed, and if nothing
+ can author, the assistant says so and writes nothing (a template with the
+ request pasted in is never committed unreviewed).
+ - The UI's skill-creator dialog and `jarvis skills draft` see the same live
+ tool inventory now, so their drafts name real connectors too; `draft` gained
+ `--trigger`, `--schedule`, `--language`.
### Fixed
+- **A request to CREATE a skill is no longer captured by a skill it merely
+ mentions.** Voice session 2026-08-18 17:51: "… einen neuen Skill erstellst …
+ ein Lied mit YouTube Music …" was taken by the YouTube Music skill because its <!-- i18n-allow: quoted voice request -->
+ brand trigger matched the words INSIDE the description, the model spent the
+ whole tool budget reading `jarvisctl --help`, and the answer was "Das hat
+ gerade nicht geklappt." A deterministic authoring resolver <!-- i18n-allow: quoted voice request -->
+ (`jarvis/skills/authoring_request.py`) now decides "the user wants a NEW
+ skill" before any brand trigger runs — in every spoken conjugation ("Skill
+ erstellst", "skill zu erstellen", "create a skill", "crea un skill") — and
+ keeps force-spawn and the evidence gate out of such a turn. The
+ `skill-creator` builtin's own card is a short "call create-skill once" now;
+ Anthropic's long guide moved to `references/anthropic-skill-creator.md`.
+
- The key-format hint no longer calls an `AIza` key a "Google AI Studio key".
The same shape is issued for Google Cloud, so the label is endpoint-neutral
now and the note says which card decides where the key is sent. A correctly
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 2bbd80b449..a0e51e9fc6 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -10183,3 +10183,195 @@ width, however narrow, and says nothing"); `WorkspaceLauncher.crowded.test.tsx`
("says so from ten terminals up, and lets the wizard carry on", "opens
exactly the count that was asked for" with 30 panes and no confirmation);
`layout.test.ts` (the constants' arithmetic).
+
+## BUG-147: "erstell mir einen neuen Skill … mit YouTube Music" — the music skill captured the authoring request, the brain had no tool to write a skill, and the answer was "that did not work" (HIGH, FIXED 2026-08-18) <!-- i18n-allow: quoted voice request -->
+
+**Symptom.** Realtime voice session `a62cbc4d` (2026-08-18 17:51, Vertex Live,
+delegate tool mode). The user asked, in German, for a new "morning routine"
+skill: every morning at six read the new mail, the Linear tickets ("Lenya
+Tickets" in the transcript) and the day's calendar, then play an 80s classic
+on YouTube Music, a different one each time. Jarvis said "I'm still on it"
+after 9 s and, 90 s later, the spoken equivalent of "that did not work just
+now". No skill existed afterwards.
+
+**Reconstruction (desktop log + flight recorder).**
+
+1. `SkillMatchEvaluated`: source `trigger`, band `fire`, winner
+ `plugin-youtube_music`, candidates `[["plugin-youtube_music", 1.0]]`. The
+ music connector's trigger is brand-only and un-anchored
+ (`(youtube ?music|yt ?music|ytmusic)`), so it matches the brand ANYWHERE —
+ including inside the description of a skill the user wants built. The
+ `skill-creator` builtin's own trigger knew only the German infinitive
+ ("… Skill erstellen"); the user said the conjugated "… Skill erstellst"
+ after the noun, and the regex missed.
+2. `Evidence gate stood down: turn is owned by matched skill
+ plugin-youtube_music`, `force-spawn skipped: utterance matches an installed
+ skill` — the music skill's instructions were injected inline, `run-skill`
+ was dropped.
+3. The model understood the request anyway and looked for a way to write a
+ skill: `ActionExecuted cli_jarvisctl "jarvisctl --help"` (4.1 s),
+ `"jarvisctl skills --help"` (1.6 s), `"jarvisctl skills draft --help"`
+ (1.6 s) — three rounds of reading help text, each preceded by a slow
+ provider round (Vertex TTFT 2–50 s that afternoon), then
+ `tool_use_loop: 45.0s deadline reached after 53.6s / 3 round(s) — forcing
+ a final tool-less answer round`. There was NO router tool for creating a
+ skill: `spawn-skill-author` had been documented "deliberately unreachable"
+ since 2026-07-25 (it needed a runner the entry-point loader cannot supply),
+ and the live authoring path was the UI dialog plus a two-step
+ `jarvisctl skills draft` → `commit` with JSON piped between them.
+4. Even that path would not have produced what the user asked for: the
+ creator's single brain call ran on the BrainManager's active provider —
+ on this box `openrouter`, pinned by a stale shell variable and unkeyed —
+ and its fallback is a deterministic skeleton that pastes the intent 1:1
+ into `description` and a body reading "1. …", with no schedule trigger
+ and no step naming a tool.
+
+**Root cause.** Three structural gaps: (a) the trigger channel had no notion
+that a request to CREATE a skill makes every service named inside it CONTENT,
+not a command; (b) the brain had no authoring tool at all; (c) the authoring
+service was one provider deep and its degradation was a template.
+
+**Fix.**
+- `jarvis/skills/authoring_request.py` — deterministic resolver ahead of the
+ trigger channel (Channel 0.5 in `BrainManager._match_skill_for_turn`): word
+ "skill" + a creation shape (indefinite/new article, or a creation verb in
+ ANY conjugation right before/after the noun; DE/EN/ES) + not an information
+ question. Resolves to the active `skill-creator` builtin with trigger-grade
+ rights, or to NO skill when it is disabled — never to a connector named
+ inside the request. Force-spawn and the evidence gate stand down on such a
+ turn (`_skill_authoring_turn`). New veto `authoring_request` in
+ `jarvis/skills/guards.py`.
+- `create-skill` router tool (`jarvis/plugins/tool/create_skill.py`, in
+ `ROUTER_TOOLS`, monitor): ONE bounded call — live tool inventory + installed
+ skills → the brain ladder (active provider → Tool Model → quality tier →
+ frontier chain, crossing on a dead rung) → a complete draft (name,
+ description, spoken trigger regex, schedule cron when a time was named,
+ numbered steps naming the connectors that exist, spoken answer format) →
+ committed as `state: draft` (AP-15). Without an authoring brain it fails
+ honestly and writes nothing. Same `SkillCreatorService.author()` behind
+ `POST /api/skills/creator/author` and `jarvis skills create`.
+- `SkillCreatorService`: provider ladder, tool inventory in the prompt, the
+ Jarvis skill contract in the system prompt, trigger normalisation
+ (overbroad/invalid voice patterns and bad crons dropped, the caller's cron
+ hint added when the model forgot it, `requires_tools` filtered to real
+ names), name-collision suffixing.
+- `skill-creator` builtin: short instruction card ("restate, call
+ create-skill once, report"); trigger regex accepts conjugated verbs;
+ Anthropic's guide moved to `references/anthropic-skill-creator.md`.
+
+**Measured.** With the fix, the exact transcript resolves to `skill-creator`
+(the music skill no longer captures it), and a live probe of the authoring
+prompt on this box's Tool Model (Vertex) produced a complete `Morgenroutine`
+skill in 33 s: `cron: 0 6 * * *`, voice trigger
+`(morgenroutine|morgen routine|…)`, four steps naming `gmail`,
+`linear/list_issues`, `google_calendar`, `youtube_music`, "Lenya Tickets"
+mapped to Linear under `assumptions`, spoken answer format, `state: draft`.
+
+**Regression tests.** `tests/unit/skills/test_authoring_request.py` (the live
+transcript + hard negatives), `tests/unit/brain/test_skill_authoring_turn.py`,
+`tests/unit/plugins/test_create_skill_tool.py`,
+`tests/unit/skills/test_creator_service.py` (ladder crossover, inventory in
+the prompt, `author()` never commits a skeleton),
+`tests/unit/ui/web/test_skills_routes.py`,
+`tests/unit/cli_ctl/test_commands_wave23.py`,
+`tests/fixtures/skill_routing/golden.yaml` (forensic positive).
+
+## BUG-147: a Vertex Live readback is spoken twice, and three grounded answers in a row are never heard — the stale-generation guard was stamped before the speaker drained, and Vertex Live had no realtime-scoped emergency voice (HIGH, FIXED 2026-08-18)
+
+**Symptom.** Realtime voice session `28cf8436` (2026-08-18 18:39, Vertex Live,
+delegate tool mode, desktop). Turn 0 ("what music would you recommend") was
+answered with a 7.6 s readback ("Für konzentriertes Arbeiten empfehle ich
+… Lo Fi …") — and the moment it ended the same sentence was spoken again
+("… Lo-Fi …", turn 1, EMPTY user text, its own 225 output tokens). Turn 2
+("… bisschen langweilig, aber fokussieren") repeated the same way (4.6 s
+readback, then turn 3 verbatim). Then turns 4, 5 and 6 ("… was Cooles von Ed
+Sheeran", "Hallo. …", "Hallo, sprich mal mit mir.") each produced a grounded
+Brain answer that was recorded in the transcript and NEVER heard: `provider
+produced no audio for a grounded Brain result; using surface TTS fallback` →
+`Realtime surface fallback has no realtime-scoped TTS for provider
+'vertex-live' — keeping the turn text-only`. Reported by the maintainer as
+"he spoke twice, and after a while I heard no output at all".
+
+**Reconstruction (recorder + flight recorder + desktop log).**
+
+1. The doubled turns are BUG-143's shape exactly — a second server generation
+ re-rendering the injected result — and the postmortem confirms the
+ BUG-143 guard was live (`stale_generations_dropped` present) yet counted
+ ZERO drops. The guard was armed at the provider's `turn_complete` and
+ judged with a 2.5 s window. On the desktop the surface boundary that
+ follows the arm — `_complete_surface_turn` → `send_json(turn_complete)` →
+ `RealtimePlayback.finish_turn()` — BLOCKS until the speaker queue has
+ drained, and Gemini streams a reply faster than real time. So for any
+ reply whose remaining playback exceeded 2.5 s the stamp was already
+ expired when the phantom generation's first event was judged
+ (`_stale_generation_guard_reason` → window elapsed → disarm), and the
+ generation played as a user-less turn. BUG-143's live case had ~2 s
+ replies and never crossed the window; the fix was verified against a
+ test surface whose `send_json` returns immediately.
+2. The silent turns: after the trusted result was delivered (tool response
+ for the provider-requested turns 4/5, result text for the deterministic
+ turn 6) the provider sent a `turn_complete` ~0.3 s later with no audio,
+ no transcript and only the function-call's own output tokens metered.
+ The session did what it should — the no-audio net fired the surface
+ fallback — but `_REALTIME_SURFACE_TTS_FAMILY` mapped ONLY `gemini-live`
+ to a TTS sibling. `vertex-live` had none, so the strict mode-separation
+ rule (never the pipeline `[tts]` voice) left the turn text-only, on a
+ host whose pipeline had a working Vertex TTS (`Vertex TTS client built`
+ two log lines later). WHY the provider rendered nothing for those three
+ deliveries could not be attributed: nothing recorded what was sent on the
+ wire (result text vs. steering delta vs. tool response) or which
+ generation a boundary closed.
+
+**Fix.**
+
+- `jarvis/realtime/session.py`: the guard is armed AFTER
+ `_complete_surface_turn` returns, from a stamp taken then, and only if
+ `_may_arm_stale_generation_guard(boundary_at)` holds — no turn opened, no
+ server speech edge, and no local microphone voice since the provider
+ boundary (a confirmed barge-in during the drain stamps
+ `_last_voiced_input_monotonic` and stands the guard down before it arms).
+ The window comment on `_STALE_GENERATION_WINDOW_S` now states that it runs
+ from the SURFACE boundary. `_DelegateTurnState.delivered_at` plus INFO
+ lines for "delegate result delivered via text / tool result / direct
+ speech", "stale-generation guard armed", and the no-audio warning now
+ naming "boundary N s after delivery" make the next incident readable.
+- `jarvis/plugins/tts/__init__.py`: `vertex-live → vertex-tts`. The
+ emergency voice for a Vertex Live session is `VertexTTS` — same Gemini
+ voice catalogue, same one-take streaming profile — keyed through the
+ Vertex realtime slots or, keyless, the Cloud project path
+ (`vertex_credential_configured`, Application Default Credentials).
+ Provider & mode parity: every realtime family that HAS a TTS sibling gets
+ its emergency voice; `openai-realtime` still has none and stays text-only.
+- `jarvis/plugins/realtime/gemini_live.py`: wire forensics, one INFO line
+ per client text/tool input (`text input sent`, `tool response sent`,
+ `delivered a per-turn steering delta`) and one per server generation
+ boundary (`generation started N s after the last <kind> input`,
+ `turn complete — audio=… transcript=… function_calls=… generation=…`,
+ `interrupted`), so a doubled or missing readback is attributable to the
+ input that provoked it from the log alone.
+
+**Not changed, on purpose.** The provider's empty answer to a delivered
+result is NOT second-guessed at the boundary: with the wire log in place the
+next occurrence says whether that `turn_complete` was a genuine empty
+generation or a late boundary of an earlier one, and only then is a change
+to the no-audio net justified. Until then the fallback voice is audible on
+every realtime family that has one.
+
+**Class rule.** A time window measured at one boundary and consumed at
+another is only as good as the code between them: any await between the
+stamp and the judgement — here a surface call that drains a speaker — turns
+"2.5 s after the reply ended" into "2.5 s after the provider stopped
+sending". Stamp fail-open windows at the LAST boundary before they are read.
+And a fallback map keyed by provider id is a parity surface: every family
+that ships a sibling must be in it, or the honest-degradation path degrades
+one family further than the others.
+
+**Guards.** `tests/unit/realtime/test_stale_generation_after_readback.py`
+(`test_second_generation_is_discarded_even_after_a_long_speaker_drain` — a
+`send_json` that blocks on `turn_complete` longer than the window, phantom
+still discarded; `test_voice_during_the_speaker_drain_keeps_the_next_answer`
+— a barge-in during the drain never arms the guard);
+`tests/unit/plugins/tts/test_realtime_surface_tts.py`
+(`test_vertex_live_builds_vertex_tts_with_session_voice`,
+`test_vertex_live_builds_on_the_project_path_without_a_key`,
+`test_vertex_live_without_any_credential_yields_no_surface_tts`).
diff --git a/docs/LLM-CONTEXT.md b/docs/LLM-CONTEXT.md
index 408b806416..b93f00bdd9 100644
--- a/docs/LLM-CONTEXT.md
+++ b/docs/LLM-CONTEXT.md
@@ -385,7 +385,7 @@ Verified against the actual file tree (not just CLAUDE.md claims):
| 0–4 Foundations | live | Protocols, plugin system, FastAPI/React, speech pipeline, skill system, tool-use loop, harness dispatch, core memory |
| 5 Vision/Action/Admin/Async/Control + Tiered Routing | live | `jarvis/{vision,admin,tasks,control,telemetry}/`, `ROUTER_TOOLS` frozenset, ADR-0001..0011 |
| 6 Self-Healing Worker-Critic | live | `jarvis/missions/{manager,kontrollierer,critic,workers,isolation,worker_runtime,voice,safety}/`. 458 mission tests. Wired via `bootstrap_missions` |
-| 7 Self-Mod (foundation + writer + tools) | live | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). `spawn-skill-author` is **NOT** reachable from the brain — see §25; the live authoring path is the `skill-creator` builtin plus `POST /api/skills/creator/*` |
+| 7 Self-Mod (foundation + writer + tools) | live | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). `spawn-skill-author` is **NOT** reachable from the brain — see §25; the brain-reachable authoring path is the `create-skill` router tool (2026-08-18) over the same `SkillCreatorService` as `POST /api/skills/creator/*` and `jarvis skills create` |
| Awareness A0–A5 | live | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, watchers, probes). A1 + A3 router tools registered |
| Wiki B0/B1/B2/B3/B5/B7/B8/B9 | live | `jarvis/memory/wiki/` (curator, atomic_writer, page, integration, scheduler, session_rollup, voice_bridge, telemetry, vault_index, watcher, search). 3 router tools |
| Wiki B4 (legacy Curator) | soft-disabled | `factory.py:736-757` gates on `cfg.memory.legacy_curator.enabled` (default `false` since 2026-05-17). `data/workspace/` snapshot stays on disk for 35 reader sites |
@@ -673,7 +673,7 @@ Self-mod writeup: [`docs/self_mod.md`](docs/self_mod.md) — 8 mutable settings
Two drifts surfaced during the agent audit; flag them before quoting CLAUDE.md to a fresh chat:
-1. **`spawn-skill-author` is NOT wired** (corrected 2026-07-25). It carried a `pyproject.toml` entry point, and this document previously concluded from that registration that the tool was live — it was not, and that claim misled every agent session reading this file. The tool is absent from `ROUTER_TOOLS` (the only allow-set, so `factory.py` filters it out), AND its `__init__` requires a `runner=` argument the entry-point loader cannot supply — so adding it to `ROUTER_TOOLS` raises `TypeError` at tool load rather than fixing anything. The entry point has been removed; skill authoring lives in the `skill-creator` builtin and `POST /api/skills/creator/{draft,refine,validate,commit}`, which already enforce the AP-15 draft guard. Guarded by `tests/unit/brain/test_router_tool_entrypoint_parity.py`.
+1. **`spawn-skill-author` is NOT wired** (corrected 2026-07-25). It carried a `pyproject.toml` entry point, and this document previously concluded from that registration that the tool was live — it was not, and that claim misled every agent session reading this file. The tool is absent from `ROUTER_TOOLS` (the only allow-set, so `factory.py` filters it out), AND its `__init__` requires a `runner=` argument the entry-point loader cannot supply — so adding it to `ROUTER_TOOLS` raises `TypeError` at tool load rather than fixing anything. The entry point has been removed. **Since 2026-08-18 the brain CAN author skills** — through the `create-skill` router tool (`jarvis/plugins/tool/create_skill.py`, in `ROUTER_TOOLS`, loader-constructible), which calls the same `SkillCreatorService.author()` as `POST /api/skills/creator/author` and `jarvis skills create`; every path lands the skill as `state: draft` (AP-15) because `commit` forces it. A spoken "erstell mir einen neuen Skill …" is recognised deterministically by `jarvis/skills/authoring_request.py` BEFORE any brand trigger, so a service named inside the request can no longer capture the turn. Guarded by `tests/unit/brain/test_router_tool_entrypoint_parity.py`, `tests/unit/plugins/test_create_skill_tool.py`, `tests/unit/brain/test_skill_authoring_turn.py`.
2. **`jarvis/sub_jarvis/` directory still exists** as an **empty placeholder** (no `__init__.py`, no files) despite CLAUDE.md and `docs/jarvis-agents-bridge.md §11` declaring it deleted in Welle 4. Cleanup is structurally complete (no code references), but the empty dir itself is leftover.
diff --git a/docs/adr/0011-router-pure-dispatcher.md b/docs/adr/0011-router-pure-dispatcher.md
index 243a6be23a..af4c646f65 100644
--- a/docs/adr/0011-router-pure-dispatcher.md
+++ b/docs/adr/0011-router-pure-dispatcher.md
@@ -1095,3 +1095,78 @@ the process.
- `tests/unit/brain/test_modes.py`
- `tests/integration/test_modes_routes.py`
- `tests/unit/brain/test_routing.py` (ROUTER_TOOLS exact set)
+
+## Amendment: `create-skill` router tool (2026-08-18)
+
+`create-skill` joins `ROUTER_TOOLS`: the brain can now WRITE a new skill from
+the user's spoken description (`jarvis/plugins/tool/create_skill.py`).
+
+### Context
+
+Voice session 2026-08-18 17:51: "Ich möchte, dass du mir bitte einen neuen
+Skill erstellst — Morgenroutine, jeden Morgen um 6 Uhr E-Mails, Linear-Tickets
+und Kalender vorlesen, dann ein 80er-Klassiker auf YouTube Music."
+Three things went wrong at once, and each was structural:
+
+1. **The wrong skill captured the turn.** The trigger channel captures on the
+ longest author regex, and `plugin-youtube_music`'s brand-only trigger
+ matched the words INSIDE the description of the skill to be built. The
+ `skill-creator` builtin's own trigger knew only the infinitive ("Skill
+ erstellen"), not the conjugated verb the user said ("Skill erstellst").
+2. **The brain had no tool to write a skill.** The only live authoring path
+ was the UI dialog (`POST /api/skills/creator/{draft,commit}`) and, two
+ commands deep, `jarvisctl skills draft` + `commit` with JSON piped between
+ them. The model spent three tool rounds on `jarvisctl --help`, hit the 45 s
+ loop deadline and said "Das hat gerade nicht geklappt."
+3. **Even that path could produce a template, not a skill.** The creator's
+ deterministic skeleton copies the intent 1:1 into `description` and a body
+ that says "1. …", never derives a schedule trigger, and its single brain
+ call died on the dev box's unkeyed active provider.
+
+The 2026-07-25 note that a router tool "would be a third route to the same
+behaviour and a fourth place to forget the AP-15 guard" was reasoning about
+the phantom `spawn-skill-author`; the guard is enforced in ONE place
+(`SkillCreatorService.commit` forces `state="draft"`), so a tool that calls
+that service adds a caller, not a place to forget.
+
+### Decision
+
+- `jarvis/skills/authoring_request.py` — a deterministic resolver ahead of the
+ trigger channel (Channel 0.5 in `BrainManager._match_skill_for_turn`): word
+ "skill" + a creation shape (indefinite/new article, or a creation verb in
+ any conjugation right before/after the noun) + not an information question.
+ An authoring request resolves to the active `skill-creator` builtin with
+ trigger-grade rights, or to NO skill when that builtin is off — never to a
+ connector named inside the request. Force-spawn and the evidence gate stand
+ down on such a turn (`_skill_authoring_turn`).
+- `create-skill` (monitor): ONE bounded call — live tool inventory + installed
+ skills → the brain ladder (active provider → Tool Model → quality tier →
+ frontier chain, crossing on a dead rung, AP-21/AP-22) → a complete draft
+ (name, description, spoken trigger regex, schedule cron when a time was
+ named, numbered steps per connected tool, spoken answer format) → committed
+ as `state: draft` (AP-15). Never a skeleton: without an authoring brain the
+ tool fails honestly and writes nothing (`SkillCreatorUnavailable`).
+- Parity across surfaces (§3 provider & mode parity): the same
+ `SkillCreatorService.author()` backs `POST /api/skills/creator/author` and
+ `jarvis skills create`; the realtime engines reach it through the delegate
+ router brain like every other router tool; the UI dialog keeps its
+ review-then-commit flow and now sees the same tool inventory.
+- The `skill-creator` builtin's body is a short card ("restate, call
+ create-skill once, report") — Anthropic's 450-line guide moved to
+ `references/anthropic-skill-creator.md`; its regex accepts conjugated verbs.
+
+Direct gated action, never a spawn, never in a worker tool set (AP-5/AP-14).
+
+### Regression guards
+
+- `tests/unit/skills/test_authoring_request.py` (the live transcript, hits and
+ hard negatives)
+- `tests/unit/brain/test_skill_authoring_turn.py` (youtube_music no longer
+ captures the authoring turn; stand-downs)
+- `tests/unit/plugins/test_create_skill_tool.py` (registered, router-visible,
+ loader-constructible; draft on disk; honest failure writes nothing)
+- `tests/unit/skills/test_creator_service.py` (brain ladder crossover,
+ inventory in the prompt, trigger normalisation, `author()` refuses a
+ skeleton, collision suffix)
+- `tests/unit/ui/web/test_skills_routes.py`, `tests/unit/cli_ctl/test_commands_wave23.py`
+- `tests/fixtures/skill_routing/golden.yaml` (forensic positive)
diff --git a/docs/architecture-overview.md b/docs/architecture-overview.md
index d7bafeee69..1b9932dd82 100644
--- a/docs/architecture-overview.md
+++ b/docs/architecture-overview.md
@@ -44,7 +44,7 @@ subprocess flicker, audio host-API) are catalogued there.
| **0–4 — Foundations** | ✅ | Plugin system + protocols, FastAPI/React desktop app, speech pipeline, skill system, tool-use loop, risk-tier executor, core memory, harness dispatch. Detail in `docs/phase{0,1,1a,1c,2,4}-*.md`. |
| **5 — Vision/Action/Admin/Async/Control + Tiered Routing** | ✅ | `jarvis/{vision,admin,tasks,control,telemetry}/`. Computer-Use enabled. Tiered routing via `ROUTER_TOOLS` frozenset. ADR-0001..0011. |
| **6 — Self-Healing Worker-Critic** | ✅ | `jarvis/missions/` (event store, manager, recovery, state machine, budget, cleanup, workers, critic, kontrollierer, safety, voice, isolation). ADR-0009, `docs/phase6-*.md`. Wired into REST + voice path via `bootstrap_missions`. **Live progress (2026-06-15):** both the Codex worker and `ClaudeDirectWorker` stream stdout line-by-line; the orchestrator drain loop emits throttled `WorkerProgress` (`jarvis/missions/events.py`) → WS → `ReasoningPanel`. **Re-run (2026-06-15):** `POST /api/missions/{id}/rerun` re-dispatches a terminal mission's stored prompt as a NEW mission linked via `parent_mission_id` ("Continue" cancelled / "Restart" failed) — the source card is untouched audit; **no state-machine or idempotency change** (deliberate, avoids AP-14). |
-| **7 — Self-Mod (foundation + writer + tools)** | ✅ | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). Three router-tier tools: `list_mutable_settings`, `get_config_value`, `set_config_value`. ADR + writeup in `docs/self_mod.md`. **7.5 `spawn-skill-author` IS now registered** (`pyproject.toml` → `jarvis.brain.tools.skill_authoring:SpawnSkillAuthorTool`, router-tier, `ask`; spawns the `SkillAuthoringRunner`). Generated skills land as `state="draft"` and are never auto-activated (AP-15). |
+| **7 — Self-Mod (foundation + writer + tools)** | ✅ | `jarvis/core/self_mod/` (audit, errors, pending, registry, schema, writer). Three router-tier tools: `list_mutable_settings`, `get_config_value`, `set_config_value`. ADR + writeup in `docs/self_mod.md`. **7.5 skill authoring by voice/chat is the `create-skill` router tool** (2026-08-18; `pyproject.toml` → `jarvis.plugins.tool.create_skill:CreateSkillTool`, router-tier, `monitor`; one bounded brain call through `SkillCreatorService`, the same service behind `POST /api/skills/creator/*` and `jarvis skills create`). The older `spawn-skill-author` class is NOT wired (see `docs/LLM-CONTEXT.md` §25). Generated skills land as `state="draft"` and are never auto-activated (AP-15). |
| **Awareness A0–A5** | ✅ | `jarvis/awareness/` (state, story, salience, verdichter, working_set, episode, recall_store, watchers, probes). Router-tier tools `awareness-snapshot` (A1) + `awareness-recall` (A3). ADR-0009/0010/0012. Hard rule: **never on the voice critical path**. |
| **Wiki B0/B1/B2/B3/B5/B7/B8/B9** | ✅ | `jarvis/memory/wiki/` (curator, atomic_writer, page_repository, integration, session_rollup, voice_bridge, telemetry, scheduler). Three router-tier tools: `wiki-recall`, `wiki-page-read`, `wiki-ingest`. ADR-0013/0014/0015. B2 = `docs/obsidian-setup.md` + B9-Wizard. B3 = `WikiView.tsx` + 6-endpoint `wiki_routes.py` + `wiki_ws.py` live-reload. **B4 soft-disabled** 2026-05-17 via `[memory.legacy_curator] enabled = false` — legacy Curator package + `data/workspace/` snapshot stay on disk; Hart-Cut (vault migration + reader refactor + package delete) remains open. **B6 not started**. |
| **Realtime → Jarvis-Agents bridge** | ✅ canonical path live | Realtime emits the provider-neutral `jarvis_action`; `BrainManager` delegates heavy work through `spawn-worker`; `jarvis/missions/` owns worker selection, isolation, retries, Critic review, and Kontrollierer sign-off. MCP and marketplace tools are granted by capability, not exposed as worker harness names. |
diff --git a/jarvis/brain/factory.py b/jarvis/brain/factory.py
index 8d01d74b57..e5dd122a20 100644
--- a/jarvis/brain/factory.py
+++ b/jarvis/brain/factory.py
@@ -117,6 +117,18 @@ ROUTER_TOOLS = frozenset({
# Available to BOTH Router-Tier (here) and in Wave 4: bypasses the
# Jarvis-Agent worker because the worker itself has no skill layer.
"run-skill",
+ # Skill authoring by voice/chat (2026-08-18): the brain writes a NEW skill
+ # from the user's description — one bounded brain call through the
+ # SkillCreatorService ladder, committed as ``state: draft`` (AP-15, the
+ # user activates it in the Skills view). Direct gated action (monitor: an
+ # inactive file, instantly deletable), never a spawn — never in a worker
+ # tool set (AP-5/AP-14). Replaces the phantom ``spawn-skill-author`` (see
+ # jarvis/brain/tools/skill_authoring.py) with a tool the entry-point
+ # loader CAN construct: it resolves registry + brain lazily at execute
+ # time. Live reason: the 2026-08-18 17:51 voice turn "erstell mir einen
+ # neuen Skill …" had no authoring tool at all and died on `jarvisctl
+ # --help` rounds. See ADR-0011 amendment "create-skill router tool".
+ "create-skill",
# Phase B5 (recall-tool): read-only keyword search over the long-term
# Obsidian wiki vault. Router-tier only — never in SUB_TOOLS (AP-D9).
# The brain calls this when the user asks "what do we know about X" or
@@ -564,6 +576,15 @@ def _load_tools_for_tier(
)
inst = cls(service_resolver=build_ultrawiki_service_resolver())
+ elif ep.name == "create-skill":
+ # Skill authoring by voice/chat: the tool resolves the live
+ # SkillRegistry (skill_context) and the live BrainManager
+ # (runtime_refs) at execute time — both are set AFTER the
+ # brain is built — so it loads unconditionally and the tool
+ # surface stays stable. `bus` lets the writer publish
+ # SkillCreated for the live Skills view; `config` feeds the
+ # brain resolvers when the manager is not reachable yet.
+ inst = cls(bus=bus, config=config)
elif ep.name == "update-profile":
# Profile-write tool: mutate the SAME live UserProfile instance
# the BrainManager renders from (factory passes one instance to
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index f89b299a26..cce45493bd 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -4977,6 +4977,15 @@ class BrainManager:
getattr(self._skill_turn_match, "name", "?"),
)
return EvidenceVerdict(kind="pass")
+ # A skill AUTHORING request names calendar / mail / music only as the
+ # content of the skill to be written; the capability that serves the
+ # turn is the create-skill tool, not those domains' connectors.
+ if getattr(self, "_skill_authoring_turn", False):
+ log.info(
+ "Evidence gate stood down: skill authoring request — the "
+ "create-skill tool is the capability"
+ )
+ return EvidenceVerdict(kind="pass")
try:
cfg = self._config.brain.evidence_domains
@@ -5162,6 +5171,12 @@ class BrainManager:
_skill_turn_content_fallback: str = ""
_skill_turn_source_fallback: str = "match"
_skill_injected_inline_fallback: bool = False
+ # Skill AUTHORING turn (2026-08-18): the user asked to create a NEW skill
+ # (``jarvis.skills.authoring_request``). Set by ``_match_skill_for_turn``
+ # on every probe; while True the force-spawn guard and the evidence gate
+ # stand down — the create-skill router tool is the capability that owns
+ # such a turn, whether or not the skill-creator builtin captured it.
+ _skill_authoring_turn: bool = False
# AD-S6: warn exactly once per manager lifetime when the AVAILABLE
# SKILLS section cannot be rendered (RC2 used to be silent).
_skills_omit_warned: bool = False
@@ -5339,6 +5354,7 @@ class BrainManager:
self._skill_relevance = None
self._skill_match_band = "none"
self._skill_match_class = ""
+ self._skill_authoring_turn = False
try:
from jarvis.skills import guards, match_eval, match_log
from jarvis.skills.autofire_policy import classify, may_capture
@@ -5346,6 +5362,12 @@ class BrainManager:
ctx = try_get_skill_context()
if ctx is None:
+ # No registry to look anything up in — but an authoring request
+ # is still recognisable from the words alone, and the flag is
+ # what keeps the create-skill tool in charge of the turn.
+ from jarvis.skills.authoring_request import is_skill_authoring_request
+
+ self._skill_authoring_turn = is_skill_authoring_request(user_text)
return None
# Channel 0 (2026-08-12): the user NAMED a skill ("nutz den Skill
@@ -5379,6 +5401,55 @@ class BrainManager:
)
return explicit_skill
+ # Channel 0.5 (2026-08-18): the user asked to CREATE a skill
+ # ("erstell mir einen neuen Skill, der … mit YouTube Music …").
+ # Every service named inside that sentence is the CONTENT of the
+ # skill to be built, never a command to that service — yet the
+ # trigger channel below would hand the turn to whichever brand
+ # regex matches first (live 2026-08-18 17:51: plugin-youtube_music
+ # captured the authoring turn, the model burned the tool budget on
+ # `jarvisctl --help`, the user heard "Das hat gerade nicht
+ # geklappt"). Resolved BEFORE the trigger channel, deterministically:
+ # the skill-creator builtin captures with trigger-grade rights when
+ # it is active; when it is not, NO skill captures and the
+ # create-skill router tool owns the turn on its own.
+ from jarvis.skills.authoring_request import (
+ resolve_skill_authoring_request,
+ )
+
+ authoring = resolve_skill_authoring_request(user_text, ctx.registry)
+ if authoring is not None:
+ self._skill_authoring_turn = True
+ authoring_skill = authoring.skill
+ if authoring_skill is None:
+ log.info(
+ "skill authoring request — no domain skill may capture "
+ "this turn; the create-skill tool owns it"
+ )
+ self._record_skill_decision(
+ user_text, authoring.decision, lang=lang,
+ vetoed_by=guards.VETO_AUTHORING_REQUEST,
+ )
+ return None
+ if self._skill_is_blocked(authoring_skill):
+ self._record_skill_decision(
+ user_text, authoring.decision, lang=lang,
+ vetoed_by=guards.VETO_BLOCK_TIER, skill=authoring_skill,
+ )
+ return None
+ log.info(
+ "skill authoring request → %s captures the turn "
+ "(services named inside the request are content, not commands)",
+ getattr(authoring_skill, "name", "?"),
+ )
+ self._skill_match_band = authoring.decision.band
+ self._skill_match_class = classify(authoring_skill)
+ self._record_skill_decision(
+ user_text, authoring.decision, lang=lang,
+ skill=authoring_skill, fired=True,
+ )
+ return authoring_skill
+
cfg = self._skills_config()
decision = match_eval.evaluate_match(
ctx.registry,
@@ -8145,6 +8216,13 @@ class BrainManager:
if self._skill_turn_match is not None or self._match_skill_for_turn(t) is not None:
log.info("force-spawn skipped: utterance matches an installed skill")
return False
+ # A request to CREATE a skill is authored inline by the create-skill
+ # tool (one bounded LLM call, lands as a draft) — never a background
+ # mission, even when the skill-creator builtin is disabled and no skill
+ # captured the turn above.
+ if getattr(self, "_skill_authoring_turn", False):
+ log.info("force-spawn skipped: skill authoring request — create-skill owns it")
+ return False
# A connected CLI's capability already covers this intent → prefer its
# cli_<name> tool, never a Computer-Use spawn (the CLI does it headless,
# no browser login). Mirrors the skill guard above for the CLI surface
diff --git a/jarvis/cli_ctl/commands/skills.py b/jarvis/cli_ctl/commands/skills.py
index 0b8aebdb85..db81983c40 100644
--- a/jarvis/cli_ctl/commands/skills.py
+++ b/jarvis/cli_ctl/commands/skills.py
@@ -29,18 +29,56 @@ def draft(
intent: str = typer.Argument(..., help="What the skill should do."),
name_hint: str = typer.Option(None, "--name-hint"),
category: str = typer.Option(None, "--category"),
+ trigger_hint: str = typer.Option(None, "--trigger", help="Spoken phrase that should start it."),
+ schedule: str = typer.Option(None, "--schedule", help="5-field cron, local time."),
+ language: str = typer.Option(None, "--language", help="Language code (de/en/es)."),
yes: bool = options.yes_opt(),
dry_run: bool = options.dry_opt(),
) -> None:
- """Generate a skill draft from an intent (AI author; lands as state=draft)."""
+ """Generate a skill draft from an intent WITHOUT writing it (review, then `commit`)."""
body: dict[str, object] = {"intent": intent}
if name_hint:
body["name_hint"] = name_hint
if category:
body["category"] = category
+ if trigger_hint:
+ body["trigger_hint"] = trigger_hint
+ if schedule:
+ body["schedule_hint"] = schedule
+ if language:
+ body["language"] = language
invoke.run("POST", "/api/skills/creator/draft", body=body, assume_yes=yes, dry_run=dry_run)
+def create(
+ intent: str = typer.Argument(..., help="What the skill should do, in your own words."),
+ name: str = typer.Option(None, "--name", help="Name for the skill (optional)."),
+ trigger_hint: str = typer.Option(None, "--trigger", help="Spoken phrase that should start it."),
+ schedule: str = typer.Option(None, "--schedule", help="5-field cron, local time."),
+ language: str = typer.Option(None, "--language", help="Language code (de/en/es)."),
+ yes: bool = options.yes_opt(),
+ dry_run: bool = options.dry_opt(),
+) -> None:
+ """Author AND write a new skill in one step (the voice path's `create-skill`).
+
+ The assistant writes the whole skill — trigger phrase, schedule, steps per
+ connected tool, spoken answer format — and it lands as state=draft: switch
+ it on in the Skills view. Fails (503) instead of writing a template when no
+ brain can author it.
+ """
+ body: dict[str, object] = {"intent": intent}
+ if name:
+ body["name_hint"] = name
+ if trigger_hint:
+ body["trigger_hint"] = trigger_hint
+ if schedule:
+ body["schedule_hint"] = schedule
+ if language:
+ body["language"] = language
+ invoke.run("POST", "/api/skills/creator/author", body=body, assume_yes=yes, dry_run=dry_run)
+
+
@app.command()
def commit(
draft_json: str = typer.Option(..., "--draft", help="Draft JSON ('-' reads stdin)."),
diff --git a/jarvis/plugins/tool/create_skill.py b/jarvis/plugins/tool/create_skill.py
new file mode 100644
index 0000000000..46e435c4fa
--- /dev/null
+++ b/jarvis/plugins/tool/create_skill.py
@@ -0,0 +1,271 @@
+"""``create-skill`` — the brain writes a NEW skill from the user's spoken description.
+
+Why this tool exists (voice session 2026-08-18 17:51): the user asked, in
+German, for a new "morning routine" skill — every morning at six read the new
+mail, the Linear tickets and the day's calendar, then play an 80s classic on
+YouTube Music.
+The brain had NO way to write a skill — the only live authoring path was the
+UI dialog (``POST /api/skills/creator/*``) and, indirectly, ``jarvisctl skills
+draft`` + ``jarvisctl skills commit`` with JSON piped between them. The model
+spent three tool rounds reading ``jarvisctl --help`` and the turn timed out.
+The router tool documented as "deliberately unreachable" since 2026-07-25
+(``jarvis/brain/tools/skill_authoring.py``) was unreachable because it needed
+a worker runner the entry-point loader could not supply. This tool needs
+nothing the loader cannot give: it resolves the live registry and the live
+brain lazily at execute time (the wiki-ingest / spawn-worker resolver pattern).
+
+What it does — ONE bounded call, no spawn:
+
+1. builds the authoring context (attached tools + installed skills) so the
+ generated steps name connectors that actually exist,
+2. asks the brain ladder (active provider → Tool Model → quality → frontier)
+ for a complete SKILL.md draft — name, description, voice trigger phrase,
+ schedule cron when a time was named, numbered steps per tool, spoken answer
+ format — via :class:`jarvis.skills.creator_service.SkillCreatorService`,
+3. commits it as ``state: draft`` (AP-15 — never auto-active): the Skills view
+ is where the user reads it and switches it on,
+4. returns what was written so the answer can say it in one sentence.
+
+It never writes a template with the sentence pasted in: when no brain could
+author the draft, the result is an honest failure and nothing lands on disk
+(``SkillCreatorUnavailable``). Direct gated action, monitor tier — an inactive
+file in the user's skills folder, instantly deletable — never a spawn, so it
+never enters a worker tool set (AP-5/AP-14).
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, ClassVar
+
+from jarvis.core.protocols import ExecutionContext, ToolResult
+
+_LOG = logging.getLogger(__name__)
+
+#: Bound on the free-text arguments the model may pass. A spoken description is
+#: rarely over 1 000 characters; a runaway model must not ship a novel.
+_MAX_INTENT_CHARS = 4000
+_MAX_HINT_CHARS = 300
+
+
+class CreateSkillTool:
+ """Router-tier tool: author + commit a new (draft) skill from a description."""
+
+ name: ClassVar[str] = "create-skill"
+ risk_tier: ClassVar[str] = "monitor"
+ description: ClassVar[str] = (
+ "Create a NEW skill for this assistant from the user's description — use "
+ "this when the user asks to create, build, or set up a skill, routine, or "
+ "automation ('erstell mir einen Skill, der …', " # i18n-allow: quoted phrase
+ "'create a skill that …', 'jeden Morgen um 6 sollst du …'). " # i18n-allow: quoted phrase
+ "Pass the COMPLETE description in "
+ "'intent': what it should do, in which order, at what time or on which "
+ "phrase, which services (mail, calendar, tickets, music, …) and every "
+ "preference the user mentioned. The skill is written by the assistant "
+ "itself, lands as a DRAFT the user activates in the Skills view, and the "
+ "result tells you its name and triggers. Do NOT use this to run an "
+ "existing skill (that is run-skill) and never call it more than once per "
+ "request."
+ )
+ schema: ClassVar[dict[str, Any]] = {
+ "type": "object",
+ "properties": {
+ "intent": {
+ "type": "string",
+ "minLength": 1,
+ "description": (
+ "The full description of what the skill should do, restated "
+ "completely in the user's own words and language: actions in "
+ "order, services involved, timing/recurrence, trigger phrase, "
+ "preferences and examples the user gave."
+ ),
+ },
+ "name": {
+ "type": "string",
+ "description": (
+ "Name the user gave the skill, if any (e.g. 'Morgenroutine'); "
+ "empty string when they did not name it."
+ ),
+ },
+ "trigger_phrase": {
+ "type": "string",
+ "description": (
+ "The spoken phrase that should start the skill, if the user "
+ "said one ('wenn ich Morgenroutine sage'); empty string "
+ "otherwise."
+ ),
+ },
+ "schedule": {
+ "type": "string",
+ "description": (
+ "When it should run by itself, as a 5-field cron expression "
+ "in local time when the user named a time or recurrence "
+ "('jeden Morgen um 6' → '0 6 * * *', 'montags um 9' → "
+ "'0 9 * * 1'); empty string when no schedule was requested."
+ ),
+ },
+ },
+ "required": ["intent", "name", "trigger_phrase", "schedule"],
+ "additionalProperties": False,
+ "input_examples": [
+ {
+ "intent": (
+ "Morgenroutine: jeden Morgen um 6 Uhr meine neuen " # i18n-allow: example
+ "E-Mails, meine Linear-Tickets und die wichtigen " # i18n-allow: example
+ "Kalendereinträge des Tages kurz vorlesen und danach " # i18n-allow: example
+ "ein Lied zum Aufstehen auf YouTube Music spielen — " # i18n-allow: example
+ "ein 80er-Klassiker wie Country Roads, jedes Mal ein " # i18n-allow: example
+ "anderer." # i18n-allow: example
+ ),
+ "name": "Morgenroutine",
+ "trigger_phrase": "",
+ "schedule": "0 6 * * *",
+ },
+ {
+ "intent": (
+ "When I say 'focus time', pause the music, set Slack to do not "
+ "disturb and tell me my next meeting."
+ ),
+ "name": "",
+ "trigger_phrase": "focus time",
+ "schedule": "",
+ },
+ ],
+ }
+
+ def __init__(self, *, bus: Any | None = None, config: Any | None = None, **_: Any) -> None:
+ # ``bus`` lets the writer publish SkillCreated for the live Skills view;
+ # ``config`` feeds the brain resolvers when the live BrainManager is not
+ # reachable yet. Both optional — the loader may call ``cls()``.
+ self._bus = bus
+ self._config = config
+
+ async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:
+ if not isinstance(args, dict):
+ return ToolResult(
+ success=False, output=None, error="invalid_input: args must be a dict"
+ )
+ intent = args.get("intent")
+ if not isinstance(intent, str) or not intent.strip():
+ return ToolResult(
+ success=False,
+ output=None,
+ error="invalid_input: 'intent' (the full description) is required",
+ )
+ intent = intent.strip()[:_MAX_INTENT_CHARS]
+ name_hint = _clean(args.get("name"))
+ trigger_hint = _clean(args.get("trigger_phrase"))
+ schedule = _clean(args.get("schedule"))
+ language = _clean((ctx.config or {}).get("output_language")) if ctx is not None else ""
+
+ try:
+ from jarvis.skills.skill_context import try_get_skill_context
+
+ skill_ctx = try_get_skill_context()
+ except Exception: # noqa: BLE001 — a broken skill subsystem is reported, not raised
+ skill_ctx = None
+ if skill_ctx is None:
+ return ToolResult(
+ success=False,
+ output=None,
+ error=(
+ "skills_unavailable: the skill system is not loaded in this "
+ "runtime — the skill was not created"
+ ),
+ )
+
+ try:
+ from jarvis.core import runtime_refs
+ from jarvis.skills.creator_service import (
+ SkillCreatorInput,
+ SkillCreatorService,
+ SkillCreatorUnavailable,
+ build_authoring_context,
+ )
+
+ manager = runtime_refs.get_brain_manager()
+ config = self._config if self._config is not None else getattr(manager, "_config", None)
+ service = SkillCreatorService(
+ brain=manager,
+ registry=skill_ctx.registry,
+ bus=self._bus,
+ config=config,
+ context=build_authoring_context(brain_manager=manager, registry=skill_ctx.registry),
+ )
+ authored = await service.author(
+ SkillCreatorInput(
+ intent=intent,
+ name_hint=name_hint,
+ trigger_hint=trigger_hint,
+ schedule_hint=schedule,
+ language=language,
+ )
+ )
+ except SkillCreatorUnavailable as exc:
+ _LOG.warning("create-skill: %s", exc)
+ return ToolResult(
+ success=False,
+ output=None,
+ error=(
+ "author_unavailable: no language model could write the skill "
+ "right now, so nothing was created — tell the user plainly and "
+ "offer to try again in a moment"
+ ),
+ )
+ except Exception as exc: # noqa: BLE001 — surface the writer's own message
+ _LOG.warning("create-skill failed: %s", exc, exc_info=True)
+ return ToolResult(success=False, output=None, error=f"create_failed: {exc}")
+
+ draft = authored.result.draft
+ triggers = [dict(t) for t in draft.get("triggers", []) or []]
+ voice = [t.get("pattern") for t in triggers if t.get("type") == "voice"]
+ schedules = [t.get("cron") for t in triggers if t.get("type") == "schedule"]
+ output = {
+ "skill_name": authored.name,
+ "slug": authored.slug,
+ "state": "draft",
+ "path": str(getattr(authored.skill, "path", "") or ""),
+ "description": str(draft.get("description", "")),
+ "voice_triggers": voice,
+ "schedule_crons": schedules,
+ "steps_preview": _steps_preview(str(draft.get("body", ""))),
+ "assumptions": list(draft.get("assumptions", []) or []),
+ "questions": list(draft.get("questions", []) or []),
+ "authored_by": authored.result.brain_source,
+ "ui_section": "skills",
+ "message": (
+ f"Skill '{authored.name}' is written and waiting as a DRAFT in the "
+ "Skills view. Tell the user in one or two sentences what it does "
+ "and when it fires, and that they activate it there — until "
+ "then it does not run. Do not read the instructions aloud."
+ ),
+ }
+ _LOG.info(
+ "create-skill: wrote %r (voice=%s, cron=%s, by=%s)",
+ authored.name,
+ voice,
+ schedules,
+ authored.result.brain_source,
+ )
+ return ToolResult(success=True, output=output)
+
+
+def _clean(value: Any) -> str:
+ return str(value).strip()[:_MAX_HINT_CHARS] if isinstance(value, str) else ""
+
+
+def _steps_preview(body: str, *, limit: int = 6) -> list[str]:
+ """The numbered steps of the body, trimmed — enough for the answer to name
+ what the skill will do without dumping the whole card into the context."""
+ steps: list[str] = []
+ for line in body.splitlines():
+ stripped = line.strip()
+ if len(stripped) > 2 and stripped[0].isdigit() and stripped[1] in ".)":
+ text = stripped[2:].strip().lstrip(") ").strip()
+ steps.append(text[:140])
+ if len(steps) >= limit:
+ break
+ return steps
+
+
+__all__ = ["CreateSkillTool"]
diff --git a/jarvis/skills/authoring_request.py b/jarvis/skills/authoring_request.py
new file mode 100644
index 0000000000..ca128ae8ca
--- /dev/null
+++ b/jarvis/skills/authoring_request.py
@@ -0,0 +1,236 @@
+"""Deterministic resolution of "create a skill that …" — the user asked for a NEW skill.
+
+Live failure this module exists for (voice session 2026-08-18 17:51): the
+user asked, in German, for a new "morning routine" skill — read the mail,
+tickets and calendar every morning at six, "… and then a nice song on YouTube
+Music …" (the full transcript is the ``LIVE_UTTERANCE`` fixture in
+``tests/unit/skills/test_authoring_request.py``).
+
+The trigger channel gave that turn to ``plugin-youtube_music`` — its brand-only
+trigger ``(youtube ?music|…)`` matched the words INSIDE the description of the
+skill the user wanted built. The music skill's instructions were injected, the
+model spent the whole 45 s tool budget reading ``jarvisctl --help`` and the
+turn ended with the spoken "that did not work just now". The ``skill-creator``
+builtin's own trigger missed because it only knew the German infinitive
+("… Skill erstellen"), not the conjugated verb the user actually said
+("… Skill erstellst").
+
+The rule this resolver states is simple and holds regardless of vocabulary:
+**when the user asks to CREATE a skill, every service they name is the CONTENT
+of that skill, never a command to that service.** A brand mentioned inside an
+authoring request must not capture the turn.
+
+Same spirit as :mod:`jarvis.skills.explicit_request` — pure CPU, no LLM, no IO
+(AP-9/AP-11 safe), precision over recall. It fires only when ALL hold:
+
+1. the literal word "skill(s)" — the user is talking about the mechanism,
+2. the skill word is the OBJECT of a creation, in one of three shapes:
+ an indefinite / "new" article before it ("einen neuen Skill", "a skill",
+ "un skill"), a creation verb right after it in any spoken conjugation
+ ("Skill erstellst", "skill zu erstellen"), or a creation verb right before
+ it ("erstell skill morgenroutine", "create skill …"),
+3. the utterance is NOT an informational question ("wie erstelle ich einen
+ skill?" must be answered, never acted on).
+
+"use skill X" has no creation shape (that is the explicit-request resolver's
+turn), "switch skill X off" has a definite article and no creation verb, "which
+skills do I have" has no verb at all, "make me an overview of my skills" names
+the skills only in the genitive, "write me a mail" has no skill word — in every
+language the resolver knows. All of these miss by design (see the hard
+negatives in the tests).
+
+Resolution returns the ``skill-creator`` builtin as the capturing skill when it
+is installed and active — trigger-grade, so it inherits the trigger channel's
+unconditional capture and stand-down rights. When that builtin is disabled or
+absent the turn is still marked as an authoring request so no OTHER skill may
+capture it; the ``create-skill`` router tool then owns the turn on its own.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any
+
+from jarvis.skills.explicit_request import _INFO_QUESTION_OPENER_RE, _SKILL_WORD_RE
+from jarvis.skills.match_eval import (
+ BAND_FIRE,
+ BAND_NONE,
+ SOURCE_NONE,
+ SOURCE_TRIGGER,
+ TRIGGER_MATCH_SCORE,
+ MatchCandidate,
+ MatchDecision,
+)
+
+#: The builtin that carries the authoring instructions (``jarvis/skills/builtin/
+#: skill-creator/SKILL.md``). Resolved by name from the live registry so a user
+#: who disables it opts out of the instruction card, not out of the protection.
+AUTHORING_SKILL_NAME = "skill-creator"
+
+# Creation verbs, DE / EN / ES, as STEMS so every spoken conjugation matches
+# ("erstell", "erstellst", "erstellen", "erstelle"; "create", "creates",
+# "creating"; "crea", "crear", "creas"). Umlaut and digraph forms both listed.
+# Deliberately EXCLUDES the run/use verbs ("nutz", "starte", "run", "use") —
+# those belong to :mod:`jarvis.skills.explicit_request` — and the delete /
+# disable verbs, because removing a skill is not authoring one.
+_VERB_STEMS = (
+ # German
+ r"erstell\w*|erzeug\w*|kreier\w*|generier\w*|entwick\w*|entwerf\w*|" # i18n-allow: speech vocab
+ r"programmier\w*|definier\w*|konfigurier\w*|schreib\w*|" # i18n-allow: speech vocab
+ r"bau\w*|mach\w*|anleg\w*|leg\w*|einricht\w*|richt\w*|" # i18n-allow: speech vocab
+ # English
+ r"creat\w*|build\w*|mak\w*|make|writ\w*|generat\w*|design\w*|set\s?up|"
+ r"add\w*|defin\w*|author\w*|develop\w*|program\w*|turn\w*|"
+ # Spanish
+ r"cre\w*|constru\w*|haz|hac\w*|escrib\w*|gener\w*|dise[ñn]\w*|" # i18n-allow: speech vocab
+ r"a[ñn]ad\w*|agreg\w*|configur\w*" # i18n-allow: speech vocab
+)
+
+# Shape A — an indefinite or "new" article ahead of the skill word. Up to two
+# words may sit between them ("einen ganz neuen skill", "a brand new skill"),
+# but never a genitive / possessive / definite word: "eine Übersicht MEINER # i18n-allow: example
+# skills" and "a list OF my skills" are requests ABOUT skills, not for one.
+_GAP_STOP = (
+ r"meiner|meine|meinen|meines|deiner|deine|seiner|ihrer|" # i18n-allow: speech vocab
+ r"unserer|aller|der|des|dieser|jener|" # i18n-allow: speech vocab
+ r"my|your|his|her|our|their|of|the|these|those|all|"
+ r"de|mis|tus|sus|los|las|del" # i18n-allow: speech vocab
+)
+_INDEFINITE_SKILL_RE = re.compile(
+ r"\b(?:ein(?:e|en|es)?|neue[nrs]?|a|an|another|new|" # i18n-allow: speech vocab
+ r"un|una|nuevo|nueva|otro|otra)\s+" # i18n-allow: speech vocab
+ rf"(?:(?!(?:{_GAP_STOP})\b)[\w-]+\s+){{0,2}}skills?\b",
+ re.IGNORECASE,
+)
+
+# Shape B — a creation verb shortly AFTER the skill word (German verb-final
+# clauses: "… einen skill erstellst", "… skill zu erstellen", "skill für mich # i18n-allow: example
+# bauen"). Only the unambiguous creation stems here — "mach", "leg", "turn",
+# "add" after a skill word are usually toggles ("mach den skill AN"). A German
+# participle inside a relative clause ("den skill, den du gestern erstellt
+# HAST") and an English past tense ("the skill I createD") describe an
+# EXISTING skill and are excluded, so "starte den skill den du erstellt hast"
+# and "run the skill I created" stay with the run/use paths.
+_SKILL_THEN_VERB_RE = re.compile(
+ r"\bskills?\s+(?:[\w-]+\s+){0,3}(?:"
+ r"(?:erstell\w*|erzeug\w*|kreier\w*|generier\w*|anleg\w*|" # i18n-allow: speech vocab
+ r"einricht\w*|schreib\w*|bau\w*|entwick\w*|entwerf\w*|" # i18n-allow: speech vocab
+ r"programmier\w*)" # i18n-allow: speech vocab
+ r"(?!\s+(?:hast|hattest|hattet|habe|hatte|haben|hat|wurde|worden)\b)" # i18n-allow: vocab
+ r"|"
+ r"creat(?:e|es|ing)|generat(?:e|es|ing)|build(?:s|ing)?|writ(?:e|es|ing)|"
+ r"design(?:s|ing)?|"
+ # Spanish present / infinitive forms only — ``crea\w*`` would swallow the
+ # English "created" and ``gener\w*`` the English "generated".
+ r"crea(?:r|s|mos|n|ndo)?|constru(?:ir|ye|yes|yamos|yen|yendo|ya)?|" # i18n-allow: speech vocab
+ r"gener(?:a|ar|as|amos|an|ando|e|es)?|escrib\w*|dise[ñn]\w*" # i18n-allow: speech vocab
+ r")\b",
+ re.IGNORECASE,
+)
+
+# Shape C — a creation verb right BEFORE the skill word, with only politeness /
+# indefinite glue between ("erstell mir mal skill morgenroutine", "create skill
+# …", "haz un skill"). Definite articles are NOT glue: "mach DEN skill aus". # i18n-allow: example
+_VERB_THEN_SKILL_RE = re.compile(
+ rf"\b(?:{_VERB_STEMS})\s+"
+ r"(?:(?:mir|me|uns|us|bitte|please|doch|mal|jetzt|now|schnell|" # i18n-allow: speech vocab
+ r"quick(?:ly)?|einen?|neuen?|new|a|an|un|una|nuevo|nueva|otro|otra)" # i18n-allow: speech vocab
+ r"\s+){0,4}"
+ r"skills?\b",
+ re.IGNORECASE,
+)
+
+_ANY_VERB_RE = re.compile(rf"\b(?:{_VERB_STEMS})\b", re.IGNORECASE)
+
+
+@dataclass(frozen=True, slots=True)
+class AuthoringResolution:
+ """What an authoring request resolved to.
+
+ ``skill`` is the active ``skill-creator`` builtin when installed, else
+ ``None`` — the turn is an authoring request either way (that is what
+ ``decision`` records), the difference is only whether an instruction card
+ captures it or the ``create-skill`` tool stands alone.
+ """
+
+ skill: Any | None
+ decision: MatchDecision
+
+
+def is_skill_authoring_request(utterance: str) -> bool:
+ """True when the user asks for a NEW skill to be created.
+
+ Pure regex, no registry: usable by the force-spawn guard and the evidence
+ gate before any skill lookup. Never raises.
+ """
+ if not utterance:
+ return False
+ try:
+ if not _SKILL_WORD_RE.search(utterance):
+ return False
+ if not _ANY_VERB_RE.search(utterance):
+ return False
+ if _INFO_QUESTION_OPENER_RE.match(utterance):
+ # A question ABOUT creating skills must be ANSWERED, never acted on.
+ return False
+ return bool(
+ _INDEFINITE_SKILL_RE.search(utterance)
+ or _SKILL_THEN_VERB_RE.search(utterance)
+ or _VERB_THEN_SKILL_RE.search(utterance)
+ )
+ except Exception: # noqa: BLE001 — detection must never break a turn
+ return False
+
+
+def resolve_skill_authoring_request(utterance: str, registry: Any) -> AuthoringResolution | None:
+ """Resolve "create a skill …" to the authoring builtin, or to "nobody".
+
+ Returns ``None`` when the utterance is not an authoring request at all.
+ Otherwise returns an :class:`AuthoringResolution` whose ``decision``
+ carries ``SOURCE_TRIGGER`` / ``BAND_FIRE`` when ``skill-creator`` is active
+ (a stated intent is trigger-grade evidence, exactly like a spoken skill
+ name), and an empty ``BAND_NONE`` decision when the builtin is unavailable
+ — the caller then lets NO skill capture. Never raises.
+ """
+ if not is_skill_authoring_request(utterance):
+ return None
+ try:
+ skill = None
+ if registry is not None:
+ for candidate in registry.list_active():
+ if str(getattr(candidate, "name", "") or "") == AUTHORING_SKILL_NAME:
+ skill = candidate
+ break
+ if skill is None:
+ return AuthoringResolution(
+ skill=None,
+ decision=MatchDecision(band=BAND_NONE, source=SOURCE_NONE),
+ )
+ candidate = MatchCandidate(
+ skill_name=AUTHORING_SKILL_NAME,
+ score=TRIGGER_MATCH_SCORE,
+ band=BAND_FIRE,
+ source=SOURCE_TRIGGER,
+ evidence="skill",
+ reason="user asked to create a new skill (authoring request)",
+ )
+ decision = MatchDecision(
+ band=BAND_FIRE,
+ source=SOURCE_TRIGGER,
+ top=candidate,
+ candidates=(candidate,),
+ )
+ return AuthoringResolution(skill=skill, decision=decision)
+ except Exception: # noqa: BLE001 — resolution must never break a turn
+ return AuthoringResolution(
+ skill=None, decision=MatchDecision(band=BAND_NONE, source=SOURCE_NONE)
+ )
+
+
+__all__ = [
+ "AUTHORING_SKILL_NAME",
+ "AuthoringResolution",
+ "is_skill_authoring_request",
+ "resolve_skill_authoring_request",
+]
diff --git a/jarvis/skills/builtin/skill-creator/SKILL.md b/jarvis/skills/builtin/skill-creator/SKILL.md
index 626320ef2d..c34b57abb0 100644
--- a/jarvis/skills/builtin/skill-creator/SKILL.md
+++ b/jarvis/skills/builtin/skill-creator/SKILL.md
@@ -1,14 +1,17 @@
---
schema_version: "1"
name: skill-creator
-version: "1.1.0"
+version: "1.2.0"
description: |
- Creates new Jarvis skills and iteratively improves existing ones. Activates when
- the user wants to build a new skill ("erstell einen skill fuer X" / "create a
- skill for X" / "mach aus diesem Workflow einen Skill").
+ Creates a new Jarvis skill from the user's description — the assistant writes
+ the whole skill (name, trigger phrase, schedule, steps, spoken answer format)
+ and files it as a draft. Use when the user wants to build a new skill,
+ routine or automation ("erstell mir einen Skill, der …" / "create a skill
+ that …" / "mach aus diesem Workflow einen Skill").
when_to_use: >-
- Use when the user wants to build a new skill, turn a workflow into a
- skill, or iteratively improve an existing skill.
+ Use when the user asks to create, build, or set up a new skill, routine, or
+ recurring automation — including when the request names other services that
+ are the CONTENT of the new skill, not commands to run now.
category: meta
tags: [meta, authoring, developer, skill-creator]
# Matcher vocabulary (2026-08-12): authoring requests name the mechanism, so
@@ -17,14 +20,17 @@ tags: [meta, authoring, developer, skill-creator]
# (home assistant) because only the domain words carried weight. No
# intent_verbs on purpose (plugin_coupling needs verbs AND objects to
# register a capability; this feeds only the matcher).
-intent_objects: [skill, skills, automatisierung, automation, workflow, ablauf, faehigkeit] # i18n-allow: speech-input vocabulary
-author: anthropic (adapted for jarvis)
+intent_objects: [skill, skills, automatisierung, automation, workflow, ablauf, faehigkeit, routine] # i18n-allow: speech-input vocabulary
+author: builtin (Anthropic skill-creator guide kept in references/)
license: MIT
-# 2026-08-12: precise authoring trigger. Historically "no auto voice trigger —
-# the Supervisor dispatches on an intent basis", but the measured intent path
-# was zero invocations; an explicit "…einen Skill erstellen/bauen…" phrase is
-# unambiguous authoring intent and now fires deterministically. The generated
-# draft still lands as state=draft behind the review pipeline either way.
+# 2026-08-18: the deterministic authoring resolver
+# (jarvis/skills/authoring_request.py) now decides "the user wants a NEW skill"
+# BEFORE any brand trigger runs, so a request that mentions YouTube Music or
+# Gmail inside the description can no longer be captured by that connector's
+# skill. This regex stays as the offline-eval / match-test evidence and as the
+# second line of defence, and it now accepts every spoken conjugation after the
+# noun ("… einen neuen Skill erstellst") — the 2026-08-18 17:51 turn used
+# exactly that form and missed the old infinitive-only alternative.
# Verb heads are written with a character class ([e]rstell, b[a]u, …) ON
# PURPOSE: mine_pattern_literals flushes literal runs at "[", so the generic
# creation verbs never enter the relevance index as trigger-weight vocabulary.
@@ -33,501 +39,49 @@ license: MIT
# skill-specific noun ("skill") is the only strong literal this pattern feeds.
triggers:
- type: voice
- pattern: "([e]rstell\\w*|b[a]u\\w*|m[a]ch\\w*|schr[e]ib\\w*|gener[i]er\\w*)\\s+(mir\\s+)?(bitte\\s+)?(doch\\s+)?einen?\\s+(neuen?\\s+)?skill|einen?\\s+(neuen?\\s+)?skill\\s+([e]rstellen|[b]auen|[a]nlegen|[s]chreiben|[g]enerieren)|aus\\s+(diesem|dem|meinem)\\s+\\w+\\s+einen\\s+skill|(cre[a]te|b[u]ild|m[a]ke)\\s+(me\\s+)?an?\\s+(new\\s+)?skill|t[u]rn\\s+(this|that|it)\\s+into\\s+a\\s+skill"
- language: [de, en]
+ pattern: "([e]rstell\\w*|b[a]u\\w*|m[a]ch\\w*|schr[e]ib\\w*|gener[i]er\\w*|[a]nleg\\w*)\\s+(mir\\s+)?(bitte\\s+)?(doch\\s+)?(mal\\s+)?einen?\\s+(neuen?\\s+)?skill|einen?\\s+(neuen?\\s+)?skill\\s+(\\w+\\s+){0,3}([e]rstell\\w*|[b]au\\w*|[a]nleg\\w*|[s]chreib\\w*|[g]enerier\\w*)|aus\\s+(diesem|dem|meinem)\\s+\\w+\\s+einen\\s+skill|(cre[a]te|b[u]ild|m[a]ke|s[e]t\\s+up)\\s+(me\\s+)?an?\\s+(new\\s+)?skill|t[u]rn\\s+(this|that|it)\\s+into\\s+a\\s+skill|(cre[a]\\w*|h[a]z|constr[u]\\w*)\\s+(me\\s+)?una?\\s+(nuevo\\s+|nueva\\s+)?skill"
+ language: [de, en, es]
requires_tools: []
risk_policy:
- default_tier: ask
- require_confirmation:
- - write_skill_file
+ default_tier: monitor
config:
target_dir: user
default_category: general
-token_budget_estimate: 8000
----
-
-# Skill Creator (Jarvis adaptation)
-
-> **Phase 8 note (v0.8.0):** As of this version, voice triggers for skill
-> authoring run through the review pipeline (`dispatch_with_review` with
-> `rubric_id="skill_authoring"`). The generated SKILL.md is checked by the
-> reviewer against the rubric (`frontmatter_valid`, `trigger_keywords_unique`,
-> `instructions_actionable`, `no_malicious_bash`) before it lands as a draft
-> in `user_skills_dir`. Direct invocations of this skill (without voice)
-> remain without a review gate.
->
-> **Jarvis note:** This is an adaptation of Anthropic's official
-> Skill Creator (https://github.com/anthropics/skills/tree/main/skills/skill-creator).
-> The main body below is unchanged — the core philosophy (Intent -> Draft ->
-> Test -> Iterate) applies to Jarvis just the same. **What is different:**
->
-> 1. **Frontmatter schema:** Jarvis requires more than Anthropic's minimal format
-> (just `name` + `description`). See `references/jarvis-schema.md` for the
-> full Jarvis ``SkillFrontmatter`` with triggers, risk tiers, and
-> tool requirements.
->
-> 2. **Skill location:** Finished skills land in ``%LOCALAPPDATA%\Jarvis\skills\<name>\``,
-> not in a Jarvis-Agent project folder. ``user_skills_dir()`` returns the
-> path programmatically.
->
-> 3. **Eval framework:** Anthropic's original uses Claude Code subagents +
-> ``eval-viewer/generate_review.py`` for quantitative evals. That is not
-> (yet) ported to Jarvis — the folders ``scripts/``, ``agents/`` and ``assets/``
-> are intentionally empty and contain placeholder READMEs. For the MVP,
-> qualitative testing via ``python -m jarvis.skills.cli --run <name>`` is enough.
->
-> 4. **Runner calls:** When the original text below speaks of ``claude-with-access-to-the-skill``,
-> in Jarvis this means the ``SkillRunner`` via Supervisor dispatch
-> (``jarvis/skills/runner.py``). Subagent spawning is substituted by harness dispatch
-> (``jarvis/plugins/tool/dispatch_to_harness.py``).
->
-> With this context in mind: the rest is Anthropic's original guide.
-
+token_budget_estimate: 1500
---
# Skill Creator
-A skill for creating new skills and iteratively improving them.
-
-At a high level, the process of creating a skill goes like this:
-
-- Decide what you want the skill to do and roughly how it should do it
-- Write a draft of the skill
-- Create a few test prompts and run claude-with-access-to-the-skill on them
-- Help the user evaluate the results both qualitatively and quantitatively
- - While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist)
- - Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics
-- Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks)
-- Repeat until you're satisfied
-- Expand the test set and try again at larger scale
-
-Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat.
-
-On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop.
-
-Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead.
-
-Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill.
-
-Cool? Cool.
-
-## Communicating with the user
-
-The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate.
-
-So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea:
-
-- "evaluation" and "benchmark" are borderline, but OK
-- for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them
-
-It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it.
-
----
-
-## Creating a skill
-
-### Capture Intent
-
-Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step.
-
-1. What should this skill enable Claude to do?
-2. When should this skill trigger? (what user phrases/contexts)
-3. What's the expected output format?
-4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide.
-
-### Interview and Research
-
-Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out.
-
-Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user.
-
-### Write the SKILL.md
-
-Based on the user interview, fill in these components:
-
-- **name**: Skill identifier
-- **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently Claude has a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'"
-- **compatibility**: Required tools, dependencies (optional, rarely needed)
-- **the rest of the skill :)**
-
-### Skill Writing Guide
-
-#### Anatomy of a Skill
-
-```
-skill-name/
-├── SKILL.md (required)
-│ ├── YAML frontmatter (name, description required)
-│ └── Markdown instructions
-└── Bundled Resources (optional)
- ├── scripts/ - Executable code for deterministic/repetitive tasks
- ├── references/ - Docs loaded into context as needed
- └── assets/ - Files used in output (templates, icons, fonts)
-```
-
-#### Progressive Disclosure
-
-Skills use a three-level loading system:
-1. **Metadata** (name + description) - Always in context (~100 words)
-2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal)
-3. **Bundled resources** - As needed (unlimited, scripts can execute without loading)
-
-These word counts are approximate and you can feel free to go longer if needed.
-
-**Key patterns:**
-- Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up.
-- Reference files clearly from SKILL.md with guidance on when to read them
-- For large reference files (>300 lines), include a table of contents
-
-**Domain organization**: When a skill supports multiple domains/frameworks, organize by variant:
-```
-cloud-deploy/
-├── SKILL.md (workflow + selection)
-└── references/
- ├── aws.md
- ├── gcp.md
- └── azure.md
-```
-Claude reads only the relevant reference file.
-
-#### Principle of Lack of Surprise
-
-This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though.
-
-#### Writing Patterns
-
-Prefer using the imperative form in instructions.
-
-**Defining output formats** - You can do it like this:
-```markdown
-## Report structure
-ALWAYS use this exact template:
-# [Title]
-## Executive summary
-## Key findings
-## Recommendations
-```
-
-**Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little):
-```markdown
-## Commit message format
-**Example 1:**
-Input: Added user authentication with JWT tokens
-Output: feat(auth): implement JWT-based authentication
-```
-
-### Writing Style
-
-Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it.
-
-### Test Cases
-
-After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them.
-
-Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress.
-
-```json
-{
- "skill_name": "example-skill",
- "evals": [
- {
- "id": 1,
- "prompt": "User's task prompt",
- "expected_output": "Description of expected result",
- "files": []
- }
- ]
-}
-```
-
-See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later).
-
-## Running and evaluating test cases
-
-This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill.
-
-Put results in `<skill-name>-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go.
-
-### Step 1: Spawn all runs (with-skill AND baseline) in the same turn
-
-For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time.
-
-**With-skill run:**
-
-```
-Execute this task:
-- Skill path: <path-to-skill>
-- Task: <eval prompt>
-- Input files: <eval files if any, or "none">
-- Save outputs to: <workspace>/iteration-<N>/eval-<ID>/with_skill/outputs/
-- Outputs to save: <what the user cares about — e.g., "the .docx file", "the final CSV">
-```
-
-**Baseline run** (same prompt, but the baseline depends on context):
-- **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`.
-- **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r <skill-path> <workspace>/skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`.
-
-Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations.
-
-```json
-{
- "eval_id": 0,
- "eval_name": "descriptive-name-here",
- "prompt": "The user's task prompt",
- "assertions": []
-}
-```
-
-### Step 2: While runs are in progress, draft assertions
-
-Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check.
-
-Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment.
-
-Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark.
-
-### Step 3: As runs complete, capture timing data
-
-When each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory:
-
-```json
-{
- "total_tokens": 84852,
- "duration_ms": 23332,
- "total_duration_seconds": 23.3
-}
-```
-
-This is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them.
-
-### Step 4: Grade, aggregate, and launch the viewer
-
-Once all runs are done:
-
-1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations.
-
-2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory:
- ```bash
- python -m scripts.aggregate_benchmark <workspace>/iteration-N --skill-name <name>
- ```
- This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects.
-Put each with_skill version before its baseline counterpart.
-
-3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs.
-
-4. **Launch the viewer** with both qualitative outputs and quantitative data:
- ```bash
- nohup python <skill-creator-path>/eval-viewer/generate_review.py \
- <workspace>/iteration-N \
- --skill-name "my-skill" \
- --benchmark <workspace>/iteration-N/benchmark.json \
- > /dev/null 2>&1 &
- VIEWER_PID=$!
- ```
- For iteration 2+, also pass `--previous-workspace <workspace>/iteration-<N-1>`.
-
- **Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks "Submit All Reviews". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up.
-
-Note: please use generate_review.py to create the viewer; there's no need to write custom HTML.
-
-5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know."
-
-### What the user sees in the viewer
-
-The "Outputs" tab shows one test case at a time:
-- **Prompt**: the task that was given
-- **Output**: the files the skill produced, rendered inline where possible
-- **Previous Output** (iteration 2+): collapsed section showing last iteration's output
-- **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail
-- **Feedback**: a textbox that auto-saves as they type
-- **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox
-
-The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations.
-
-Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`.
-
-### Step 5: Read the feedback
-
-When the user tells you they're done, read `feedback.json`:
-
-```json
-{
- "reviews": [
- {"run_id": "eval-0-with_skill", "feedback": "the chart is missing axis labels", "timestamp": "..."},
- {"run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..."},
- {"run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..."}
- ],
- "status": "complete"
-}
-```
-
-Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints.
-
-Kill the viewer server when you're done with it:
-
-```bash
-kill $VIEWER_PID 2>/dev/null
-```
-
----
-
-## Improving the skill
-
-This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback.
-
-### How to think about improvements
-
-1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great.
-
-2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens.
-
-3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach.
-
-4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel.
-
-This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need.
-
-### The iteration loop
-
-After improving the skill:
-
-1. Apply your improvements to the skill
-2. Rerun all test cases into a new `iteration-<N+1>/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration.
-3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration
-4. Wait for the user to review and tell you they're done
-5. Read the new feedback, improve again, repeat
-
-Keep going until:
-- The user says they're happy
-- The feedback is all empty (everything looks good)
-- You're not making meaningful progress
-
----
-
-## Advanced: Blind comparison
-
-For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won.
-
-This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient.
-
----
-
-## Description Optimization
-
-The description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy.
-
-### Step 1: Generate trigger eval queries
-
-Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON:
-
-```json
-[
- {"query": "the user prompt", "should_trigger": true},
- {"query": "another prompt", "should_trigger": false}
-]
-```
-
-The queries must be realistic and something a Jarvis user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them).
-
-Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"`
-
-Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"`
-
-For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win.
-
-For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate.
-
-The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky.
-
-### Step 2: Review with user
-
-Present the eval set to the user for review using the HTML template:
-
-1. Read the template from `assets/eval_review.html`
-2. Replace the placeholders:
- - `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment)
- - `__SKILL_NAME_PLACEHOLDER__` → the skill's name
- - `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description
-3. Write to a temp file (e.g., `/tmp/eval_review_<skill-name>.html`) and open it: `open /tmp/eval_review_<skill-name>.html`
-4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set"
-5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`)
-
-This step matters — bad eval queries lead to bad descriptions.
-
-### Step 3: Run the optimization loop
-
-Tell the user: "This will take some time — I'll run the optimization loop in the background and check on it periodically."
-
-Save the eval set to the workspace, then run in the background:
-
-```bash
-python -m scripts.run_loop \
- --eval-set <path-to-trigger-eval.json> \
- --skill-path <path-to-skill> \
- --model <model-id-powering-this-session> \
- --max-iterations 5 \
- --verbose
-```
-
-Use the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences.
-
-While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like.
-
-This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting.
-
-### How skill triggering works
-
-Understanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches.
-
-This means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality.
-
-### Step 4: Apply the result
-
-Take `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores.
-
----
-
-### Package and Present (only if `present_files` tool is available)
-
-Check whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user:
-
-```bash
-python -m scripts.package_skill <path/to/skill-folder>
-```
-
-After packaging, direct the user to the resulting `.skill` file path so they can install it.
-
----
-
-## Platform-specific instructions
-
-For authoring notes specific to the external `openclaw` CLI and Cowork, read
-[references/platform-notes.md](references/platform-notes.md).
-
-## Reference files
-
-The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent.
-
-- `agents/grader.md` — How to evaluate assertions against outputs
-- `agents/comparator.md` — How to do blind A/B comparison between two outputs
-- `agents/analyzer.md` — How to analyze why one version beat another
-
-The references/ directory has additional documentation:
-- `references/schemas.md` — JSON structures for evals.json, grading.json, etc.
-
----
-
-Repeating one more time the core loop here for emphasis:
-
-- Figure out what the skill is about
-- Draft or edit the skill
-- Run claude-with-access-to-the-skill on test prompts
-- With the user, evaluate the outputs:
- - Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them
- - Run quantitative evals
-- Repeat until you and the user are satisfied
-- Package the final skill and return it to the user.
-
-Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put "Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases" in your TodoList to make sure it happens.
-
-Good luck!
+The user wants a NEW skill. Write it for them — do not interview them.
+
+## Steps
+
+1. Restate everything the user asked for as one complete description: what the
+ skill does, in which order, at what time or on which spoken phrase it should
+ fire, which services it touches (mail, calendar, tickets, music, smart home,
+ …), and every preference or example they gave (counts, genres, "always
+ something new"). Services named inside the request are the skill's content —
+ never act on them now (do not play the song, do not read the mail).
+2. Call the `create-skill` tool ONCE with that description as `intent`, the
+ name the user gave (or an empty string), the spoken trigger phrase if they
+ named one, and the schedule as a 5-field cron when they named a time
+ ("jeden Morgen um 6" → `0 6 * * *`). The assistant writes the whole skill
+ itself — steps per connected tool, trigger, spoken answer format — and files
+ it as a draft.
+3. If the result says no model could write it, say so plainly and offer to try
+ again in a moment. Do not fall back to a worker and do not paste the request
+ into a file yourself.
+4. If the user asks to change an EXISTING skill, tell them that editing lives in
+ the Skills view (this card only creates); name the skill they mean.
+
+## Answer format
+
+One or two spoken sentences in the user's language: the skill's name, what it
+does and when it fires, and that it is waiting as a draft in the Skills view
+until they switch it on. Never read the generated instructions aloud.
+
+## Reference
+
+Anthropic's full Skill Creator guide (intent → draft → test → iterate) is kept
+in `references/anthropic-skill-creator.md`; the Jarvis frontmatter contract is
+in `references/jarvis-schema.md`.
diff --git a/jarvis/skills/builtin/skill-creator/references/anthropic-skill-creator.md b/jarvis/skills/builtin/skill-creator/references/anthropic-skill-creator.md
new file mode 100644
index 0000000000..ab01d1a438
--- /dev/null
+++ b/jarvis/skills/builtin/skill-creator/references/anthropic-skill-creator.md
@@ -0,0 +1,473 @@
+# Anthropic's Skill Creator guide (reference)
+
+This is Anthropic's official Skill Creator guide
+(https://github.com/anthropics/skills/tree/main/skills/skill-creator),
+kept verbatim as background reading for a coding agent that iterates on a
+skill by hand: intent → draft → test → iterate, quantitative evals, blind
+comparison, description optimisation. Licensed under the Apache License 2.0
+(see `LICENSE.txt` next to `SKILL.md`).
+
+It is NOT the runtime instruction card of the `skill-creator` builtin — that
+card is `SKILL.md` and is deliberately short, because a spoken "create a skill
+that …" is answered by ONE `create-skill` tool call, not by an interview. Differences that matter when you read the guide against this
+runtime:
+
+1. **Frontmatter schema:** Jarvis requires more than Anthropic's minimal
+ `name` + `description` — see `references/jarvis-schema.md` for the full
+ `SkillFrontmatter` with triggers, risk tiers and tool requirements.
+2. **Skill location:** finished skills land in the user skills directory
+ (`user_skills_dir()`), not in a coding-agent project folder.
+3. **Eval framework:** the `scripts/`, `agents/`, `assets/` folders and
+ `eval-viewer/generate_review.py` are NOT ported — qualitative testing via
+ `python -m jarvis.skills.cli --run <name>` is the MVP path.
+4. **Runner:** where the guide says `claude-with-access-to-the-skill`, Jarvis
+ means the `SkillRunner` via the brain's `run-skill` tool.
+
+---
+
+# Skill Creator
+
+A skill for creating new skills and iteratively improving them.
+
+At a high level, the process of creating a skill goes like this:
+
+- Decide what you want the skill to do and roughly how it should do it
+- Write a draft of the skill
+- Create a few test prompts and run claude-with-access-to-the-skill on them
+- Help the user evaluate the results both qualitatively and quantitatively
+ - While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist)
+ - Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics
+- Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks)
+- Repeat until you're satisfied
+- Expand the test set and try again at larger scale
+
+Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat.
+
+On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop.
+
+Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead.
+
+Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill.
+
+Cool? Cool.
+
+## Communicating with the user
+
+The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of Claude is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate.
+
+So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea:
+
+- "evaluation" and "benchmark" are borderline, but OK
+- for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them
+
+It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it.
+
+---
+
+## Creating a skill
+
+### Capture Intent
+
+Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step.
+
+1. What should this skill enable Claude to do?
+2. When should this skill trigger? (what user phrases/contexts)
+3. What's the expected output format?
+4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide.
+
+### Interview and Research
+
+Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out.
+
+Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user.
+
+### Write the SKILL.md
+
+Based on the user interview, fill in these components:
+
+- **name**: Skill identifier
+- **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently Claude has a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'"
+- **compatibility**: Required tools, dependencies (optional, rarely needed)
+- **the rest of the skill :)**
+
+### Skill Writing Guide
+
+#### Anatomy of a Skill
+
+```
+skill-name/
+├── SKILL.md (required)
+│ ├── YAML frontmatter (name, description required)
+│ └── Markdown instructions
+└── Bundled Resources (optional)
+ ├── scripts/ - Executable code for deterministic/repetitive tasks
+ ├── references/ - Docs loaded into context as needed
+ └── assets/ - Files used in output (templates, icons, fonts)
+```
+
+#### Progressive Disclosure
+
+Skills use a three-level loading system:
+1. **Metadata** (name + description) - Always in context (~100 words)
+2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal)
+3. **Bundled resources** - As needed (unlimited, scripts can execute without loading)
+
+These word counts are approximate and you can feel free to go longer if needed.
+
+**Key patterns:**
+- Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up.
+- Reference files clearly from SKILL.md with guidance on when to read them
+- For large reference files (>300 lines), include a table of contents
+
+**Domain organization**: When a skill supports multiple domains/frameworks, organize by variant:
+```
+cloud-deploy/
+├── SKILL.md (workflow + selection)
+└── references/
+ ├── aws.md
+ ├── gcp.md
+ └── azure.md
+```
+Claude reads only the relevant reference file.
+
+#### Principle of Lack of Surprise
+
+This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though.
+
+#### Writing Patterns
+
+Prefer using the imperative form in instructions.
+
+**Defining output formats** - You can do it like this:
+```markdown
+## Report structure
+ALWAYS use this exact template:
+# [Title]
+## Executive summary
+## Key findings
+## Recommendations
+```
+
+**Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little):
+```markdown
+## Commit message format
+**Example 1:**
+Input: Added user authentication with JWT tokens
+Output: feat(auth): implement JWT-based authentication
+```
+
+### Writing Style
+
+Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs. Use theory of mind and try to make the skill general and not super-narrow to specific examples. Start by writing a draft and then look at it with fresh eyes and improve it.
+
+### Test Cases
+
+After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them.
+
+Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress.
+
+```json
+{
+ "skill_name": "example-skill",
+ "evals": [
+ {
+ "id": 1,
+ "prompt": "User's task prompt",
+ "expected_output": "Description of expected result",
+ "files": []
+ }
+ ]
+}
+```
+
+See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later).
+
+## Running and evaluating test cases
+
+This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill.
+
+Put results in `<skill-name>-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go.
+
+### Step 1: Spawn all runs (with-skill AND baseline) in the same turn
+
+For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time.
+
+**With-skill run:**
+
+```
+Execute this task:
+- Skill path: <path-to-skill>
+- Task: <eval prompt>
+- Input files: <eval files if any, or "none">
+- Save outputs to: <workspace>/iteration-<N>/eval-<ID>/with_skill/outputs/
+- Outputs to save: <what the user cares about — e.g., "the .docx file", "the final CSV">
+```
+
+**Baseline run** (same prompt, but the baseline depends on context):
+- **Creating a new skill**: no skill at all. Same prompt, no skill path, save to `without_skill/outputs/`.
+- **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r <skill-path> <workspace>/skill-snapshot/`), then point the baseline subagent at the snapshot. Save to `old_skill/outputs/`.
+
+Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations.
+
+```json
+{
+ "eval_id": 0,
+ "eval_name": "descriptive-name-here",
+ "prompt": "The user's task prompt",
+ "assertions": []
+}
+```
+
+### Step 2: While runs are in progress, draft assertions
+
+Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check.
+
+Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment.
+
+Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark.
+
+### Step 3: As runs complete, capture timing data
+
+When each subagent task completes, you receive a notification containing `total_tokens` and `duration_ms`. Save this data immediately to `timing.json` in the run directory:
+
+```json
+{
+ "total_tokens": 84852,
+ "duration_ms": 23332,
+ "total_duration_seconds": 23.3
+}
+```
+
+This is the only opportunity to capture this data — it comes through the task notification and isn't persisted elsewhere. Process each notification as it arrives rather than trying to batch them.
+
+### Step 4: Grade, aggregate, and launch the viewer
+
+Once all runs are done:
+
+1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations.
+
+2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory:
+ ```bash
+ python -m scripts.aggregate_benchmark <workspace>/iteration-N --skill-name <name>
+ ```
+ This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects.
+Put each with_skill version before its baseline counterpart.
+
+3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs.
+
+4. **Launch the viewer** with both qualitative outputs and quantitative data:
+ ```bash
+ nohup python <skill-creator-path>/eval-viewer/generate_review.py \
+ <workspace>/iteration-N \
+ --skill-name "my-skill" \
+ --benchmark <workspace>/iteration-N/benchmark.json \
+ > /dev/null 2>&1 &
+ VIEWER_PID=$!
+ ```
+ For iteration 2+, also pass `--previous-workspace <workspace>/iteration-<N-1>`.
+
+ **Cowork / headless environments:** If `webbrowser.open()` is not available or the environment has no display, use `--static <output_path>` to write a standalone HTML file instead of starting a server. Feedback will be downloaded as a `feedback.json` file when the user clicks "Submit All Reviews". After download, copy `feedback.json` into the workspace directory for the next iteration to pick up.
+
+Note: please use generate_review.py to create the viewer; there's no need to write custom HTML.
+
+5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know."
+
+### What the user sees in the viewer
+
+The "Outputs" tab shows one test case at a time:
+- **Prompt**: the task that was given
+- **Output**: the files the skill produced, rendered inline where possible
+- **Previous Output** (iteration 2+): collapsed section showing last iteration's output
+- **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail
+- **Feedback**: a textbox that auto-saves as they type
+- **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox
+
+The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations.
+
+Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`.
+
+### Step 5: Read the feedback
+
+When the user tells you they're done, read `feedback.json`:
+
+```json
+{
+ "reviews": [
+ {"run_id": "eval-0-with_skill", "feedback": "the chart is missing axis labels", "timestamp": "..."},
+ {"run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..."},
+ {"run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..."}
+ ],
+ "status": "complete"
+}
+```
+
+Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints.
+
+Kill the viewer server when you're done with it:
+
+```bash
+kill $VIEWER_PID 2>/dev/null
+```
+
+---
+
+## Improving the skill
+
+This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback.
+
+### How to think about improvements
+
+1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great.
+
+2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens.
+
+3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach.
+
+4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel.
+
+This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need.
+
+### The iteration loop
+
+After improving the skill:
+
+1. Apply your improvements to the skill
+2. Rerun all test cases into a new `iteration-<N+1>/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration.
+3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration
+4. Wait for the user to review and tell you they're done
+5. Read the new feedback, improve again, repeat
+
+Keep going until:
+- The user says they're happy
+- The feedback is all empty (everything looks good)
+- You're not making meaningful progress
+
+---
+
+## Advanced: Blind comparison
+
+For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won.
+
+This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient.
+
+---
+
+## Description Optimization
+
+The description field in SKILL.md frontmatter is the primary mechanism that determines whether Claude invokes a skill. After creating or improving a skill, offer to optimize the description for better triggering accuracy.
+
+### Step 1: Generate trigger eval queries
+
+Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON:
+
+```json
+[
+ {"query": "the user prompt", "should_trigger": true},
+ {"query": "another prompt", "should_trigger": false}
+]
+```
+
+The queries must be realistic and something a Jarvis user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them).
+
+Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"`
+
+Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"`
+
+For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win.
+
+For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate.
+
+The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky.
+
+### Step 2: Review with user
+
+Present the eval set to the user for review using the HTML template:
+
+1. Read the template from `assets/eval_review.html`
+2. Replace the placeholders:
+ - `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment)
+ - `__SKILL_NAME_PLACEHOLDER__` → the skill's name
+ - `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description
+3. Write to a temp file (e.g., `/tmp/eval_review_<skill-name>.html`) and open it: `open /tmp/eval_review_<skill-name>.html`
+4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set"
+5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`)
+
+This step matters — bad eval queries lead to bad descriptions.
+
+### Step 3: Run the optimization loop
+
+Tell the user: "This will take some time — I'll run the optimization loop in the background and check on it periodically."
+
+Save the eval set to the workspace, then run in the background:
+
+```bash
+python -m scripts.run_loop \
+ --eval-set <path-to-trigger-eval.json> \
+ --skill-path <path-to-skill> \
+ --model <model-id-powering-this-session> \
+ --max-iterations 5 \
+ --verbose
+```
+
+Use the model ID from your system prompt (the one powering the current session) so the triggering test matches what the user actually experiences.
+
+While it runs, periodically tail the output to give the user updates on which iteration it's on and what the scores look like.
+
+This handles the full optimization loop automatically. It splits the eval set into 60% train and 40% held-out test, evaluates the current description (running each query 3 times to get a reliable trigger rate), then calls Claude to propose improvements based on what failed. It re-evaluates each new description on both train and test, iterating up to 5 times. When it's done, it opens an HTML report in the browser showing the results per iteration and returns JSON with `best_description` — selected by test score rather than train score to avoid overfitting.
+
+### How skill triggering works
+
+Understanding the triggering mechanism helps design better eval queries. Skills appear in Claude's `available_skills` list with their name + description, and Claude decides whether to consult a skill based on that description. The important thing to know is that Claude only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because Claude can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches.
+
+This means your eval queries should be substantive enough that Claude would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality.
+
+### Step 4: Apply the result
+
+Take `best_description` from the JSON output and update the skill's SKILL.md frontmatter. Show the user before/after and report the scores.
+
+---
+
+### Package and Present (only if `present_files` tool is available)
+
+Check whether you have access to the `present_files` tool. If you don't, skip this step. If you do, package the skill and present the .skill file to the user:
+
+```bash
+python -m scripts.package_skill <path/to/skill-folder>
+```
+
+After packaging, direct the user to the resulting `.skill` file path so they can install it.
+
+---
+
+## Platform-specific instructions
+
+For authoring notes specific to the external `openclaw` CLI and Cowork, read
+[references/platform-notes.md](references/platform-notes.md).
+
+## Reference files
+
+The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent.
+
+- `agents/grader.md` — How to evaluate assertions against outputs
+- `agents/comparator.md` — How to do blind A/B comparison between two outputs
+- `agents/analyzer.md` — How to analyze why one version beat another
+
+The references/ directory has additional documentation:
+- `references/schemas.md` — JSON structures for evals.json, grading.json, etc.
+
+---
+
+Repeating one more time the core loop here for emphasis:
+
+- Figure out what the skill is about
+- Draft or edit the skill
+- Run claude-with-access-to-the-skill on test prompts
+- With the user, evaluate the outputs:
+ - Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them
+ - Run quantitative evals
+- Repeat until you and the user are satisfied
+- Package the final skill and return it to the user.
+
+Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. If you're in Cowork, please specifically put "Create evals JSON and run `eval-viewer/generate_review.py` so human can review test cases" in your TodoList to make sure it happens.
+
+Good luck!
diff --git a/jarvis/skills/creator_service.py b/jarvis/skills/creator_service.py
index b4cf796365..b31941ac68 100644
--- a/jarvis/skills/creator_service.py
+++ b/jarvis/skills/creator_service.py
@@ -1,25 +1,57 @@
-"""AI Skill Creator — backs ``/api/skills/creator/{draft,refine,validate,commit}``.
-
-Turns a free-text intent into a structured SKILL.md draft, optionally with brain
-assistance, and commits the user-reviewed draft as a real skill.
-
-Cloud-first contract: the creator is brain-*assisted*, never brain-*dependent*.
-``draft`` always returns a valid deterministic skeleton; if a brain is reachable
-and returns parseable JSON, the skeleton is replaced by the brain's richer draft
-(``brain_used=True``). A missing brain, a timeout, a refusal, or malformed JSON
-all degrade silently to the skeleton — so the feature works on a headless €5 VPS
-with no provider configured.
+"""AI Skill Creator — backs ``/api/skills/creator/{draft,refine,validate,commit,author}``
+and the brain's ``create-skill`` router tool.
+
+Turns a free-text intent into a structured SKILL.md draft with brain assistance,
+and commits the draft as a real (inactive) skill.
+
+Two callers, two contracts:
+
+* **The UI creator dialog** (``draft`` / ``refine`` → user reviews → ``commit``)
+ is brain-*assisted*, never brain-*dependent*: ``draft`` always returns a valid
+ deterministic skeleton; if a brain is reachable and returns parseable JSON,
+ the skeleton is replaced by the brain's draft (``brain_used=True``). A missing
+ brain, a timeout, a refusal or malformed JSON degrade to the skeleton, which
+ the user then edits before committing — so the dialog works on a headless
+ box with no provider configured.
+
+* **The voice / chat path** (``author`` — one shot: draft + commit) is
+ brain-*required*. Nobody edits between draft and commit there, and a skeleton
+ is the user's sentence pasted into a template, not a skill: the description
+ is the raw intent, the body says "1. …", there is no schedule trigger and no
+ step names a tool. Committing that would be exactly the "1:1 copy" a spoken
+ request must never produce. So ``author`` raises
+ :class:`SkillCreatorUnavailable` when no brain authored the draft, and the
+ caller says so honestly instead of pretending a skill exists.
+
+The brain call itself is a LADDER, not a single provider (AP-21/AP-22): the
+BrainManager's active provider first (the user's selection), then the pinned
+Tool Model, then the API quality tier, then the frontier chain. A dead rung —
+no key, a timeout, garbage output — crosses to the next one. Measured reason:
+on a box whose shell environment pins ``brain.primary`` to an unkeyed provider,
+the old single-provider call died on the first attempt and every voice-authored
+skill would have been a skeleton.
+
+What makes the draft a WORKING skill rather than a paraphrase is the prompt:
+the model receives the live tool inventory (which connectors are attached
+right now, by name) and the installed skills, plus the Jarvis skill contract —
+voice trigger = the short spoken phrase, schedule trigger = cron when a time
+was named, body = numbered steps that each name the tool to use and skip
+gracefully when it is missing, one flowing spoken answer at the end.
``commit`` persists the reviewed draft through the same deterministic writer as
-the manual "New skill" form (``SkillAuthoringService``), so there is one
-code path that touches the registry.
+the manual "New skill" form (``SkillAuthoringService``), so there is one code
+path that touches the registry, and it ALWAYS lands as ``state: draft``
+(AP-15): the content is LLM-generated, a human activates it in the Skills view.
"""
+
from __future__ import annotations
import asyncio
import json
import logging
import re
+import time
+from collections.abc import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -28,6 +60,7 @@ import yaml
from pydantic import ValidationError
from jarvis.skills.authoring.service import (
+ SkillAuthoringError,
SkillAuthoringService,
SkillCreateRequest,
)
@@ -35,12 +68,40 @@ from jarvis.skills.schema import Skill, SkillFrontmatter
_LOG = logging.getLogger(__name__)
-# Bounded brain call — the creator runs from a UI click, not the voice hot path,
-# but we still cap it so a hung provider cannot wedge the request.
-_BRAIN_TIMEOUT_S = 45.0
-_BRAIN_MAX_TOKENS = 1500
+# Bounded brain calls. One attempt may take a while — a good skill body is
+# 600-1200 tokens and the first token on a cold cloud provider is measured in
+# seconds — but a hung provider must not wedge a voice turn: the ladder crosses
+# to the next rung after ``_BRAIN_TIMEOUT_S`` and stops for good after
+# ``_BRAIN_TOTAL_BUDGET_S``.
+_BRAIN_TIMEOUT_S = 40.0
+_BRAIN_TOTAL_BUDGET_S = 80.0
+_BRAIN_MAX_TOKENS = 2200
+
+# How much of the live surface the model gets to see. Names + one line each;
+# a full tool schema dump would cost more than the skill it produces.
+_MAX_TOOLS_IN_PROMPT = 48
+_MAX_SKILLS_IN_PROMPT = 32
+_TOOL_DESCRIPTION_CHARS = 170
+_SKILL_DESCRIPTION_CHARS = 110
_WORD_RE = re.compile(r"[A-Za-z0-9]+")
+_CRON_RE = re.compile(r"^\s*(\S+\s+){4}\S+\s*$")
+
+_ALLOWED_TIERS = ("safe", "monitor", "ask")
+
+# Voice-trigger patterns that would match every utterance. A model that pastes
+# the whole description, or writes ``.*``, hands the skill every turn.
+_OVERBROAD_PATTERN_RE = re.compile(r"^\W*(\.\*|\.\+|\^\s*\$|\(\.\*\))\W*$")
+_MAX_PATTERN_CHARS = 200
+
+
+class SkillCreatorUnavailable(RuntimeError):
+ """``author`` could not get a brain to write the skill.
+
+ Raised instead of committing a deterministic skeleton: on the voice/chat
+ path nobody reviews the draft, and a template with the sentence pasted in
+ is not a skill the user asked for.
+ """
# ----------------------------------------------------------------------
@@ -51,8 +112,13 @@ _WORD_RE = re.compile(r"[A-Za-z0-9]+")
@dataclass(frozen=True)
class SkillCreatorInput:
"""A creator request. ``intent`` is the user's free-text description; the
- rest are optional UI hints. ``existing_draft`` + ``feedback`` drive
- ``refine`` (a revision of a prior draft)."""
+ rest are optional hints. ``existing_draft`` + ``feedback`` drive
+ ``refine`` (a revision of a prior draft).
+
+ ``schedule_hint`` is a cron expression or a spoken recurrence ("every
+ morning at 6") the caller already extracted; ``language`` is the user's
+ language code so the skill's text and trigger phrases are written in it.
+ """
intent: str
name_hint: str = ""
@@ -61,16 +127,49 @@ class SkillCreatorInput:
extra_context: str = ""
existing_draft: dict[str, Any] | None = None
feedback: str = ""
+ schedule_hint: str = ""
+ language: str = ""
@dataclass(frozen=True)
class SkillCreatorResult:
- """What ``draft``/``refine`` return — mirrors the frontend response type."""
+ """What ``draft``/``refine`` return — mirrors the frontend response type.
+
+ ``brain_source`` names the provider that authored the draft (empty when the
+ deterministic skeleton is what came back).
+ """
draft: dict[str, Any]
skill_md: str
validation: dict[str, Any]
brain_used: bool
+ brain_source: str = ""
+
+
+@dataclass(frozen=True)
+class AuthoredSkill:
+ """``author``'s answer: the committed (draft-state) skill plus the draft."""
+
+ skill: Skill
+ result: SkillCreatorResult
+ #: The name actually written — differs from the draft's when a collision
+ #: forced a numeric suffix.
+ name: str
+ slug: str
+
+
+@dataclass(frozen=True)
+class AuthoringContext:
+ """The live surface the author gets to see: attached tools and installed
+ skills, as ``(name, one-line description)`` pairs. Empty tuples are fine —
+ the prompt then simply says nothing is attached."""
+
+ tools: tuple[tuple[str, str], ...] = ()
+ skills: tuple[tuple[str, str], ...] = ()
+
+ @property
+ def tool_names(self) -> frozenset[str]:
+ return frozenset(name for name, _ in self.tools)
# ----------------------------------------------------------------------
@@ -105,18 +204,21 @@ def _title_from_intent(intent: str) -> str:
def _skeleton_draft(inp: SkillCreatorInput) -> dict[str, Any]:
"""A valid deterministic draft from the intent alone — no brain.
- This is the always-available fallback. It is intentionally minimal but
- complete enough to validate and commit unchanged.
+ This is the always-available fallback for the UI dialog. It is
+ intentionally minimal but complete enough to validate and commit unchanged
+ — after the user has edited it. ``author`` never commits it.
"""
draft = _empty_draft()
name = inp.name_hint.strip() or _title_from_intent(inp.intent)
draft["name"] = name
draft["description"] = inp.intent.strip()[:400] or name
draft["category"] = (inp.category or "general").strip() or "general"
+ triggers: list[dict[str, Any]] = []
if inp.trigger_hint.strip():
- draft["triggers"] = [
- {"type": "voice", "pattern": inp.trigger_hint.strip()}
- ]
+ triggers.append({"type": "voice", "pattern": inp.trigger_hint.strip()})
+ if _CRON_RE.match(inp.schedule_hint or ""):
+ triggers.append({"type": "schedule", "cron": inp.schedule_hint.strip()})
+ draft["triggers"] = triggers
body_lines = [
f"## {name}",
"",
@@ -129,17 +231,77 @@ def _skeleton_draft(inp: SkillCreatorInput) -> dict[str, Any]:
if inp.extra_context.strip():
body_lines += ["", "## Notes", "", inp.extra_context.strip()]
draft["body"] = "\n".join(body_lines) + "\n"
- draft["assumptions"] = [
- "Generated deterministically without a brain — edit before committing."
- ]
+ draft["assumptions"] = ["Generated deterministically without a brain — edit before committing."]
return draft
+def _clean_triggers(raw: Any, inp: SkillCreatorInput) -> list[dict[str, Any]]:
+ """Keep only triggers the loader will accept and that cannot hijack turns.
+
+ * a voice trigger needs a compilable, non-empty, non-overbroad pattern;
+ * a schedule trigger needs a 5-field cron (croniter-validated when the
+ library is present);
+ * a hotkey trigger needs a combo;
+ * when the caller supplied a cron ``schedule_hint`` and the model produced
+ no schedule trigger, the hint is added — the user said "every morning
+ at 6" and a skill without that trigger would not be what they asked for.
+ """
+ cleaned: list[dict[str, Any]] = []
+ have_schedule = False
+ for item in raw if isinstance(raw, list) else []:
+ if not isinstance(item, dict):
+ continue
+ kind = str(item.get("type", "")).strip().lower()
+ if kind == "voice":
+ pattern = str(item.get("pattern", "") or "").strip()
+ if not pattern or len(pattern) > _MAX_PATTERN_CHARS:
+ continue
+ if _OVERBROAD_PATTERN_RE.match(pattern):
+ continue
+ try:
+ re.compile(pattern)
+ except re.error:
+ continue
+ trig: dict[str, Any] = {"type": "voice", "pattern": pattern}
+ langs = item.get("language")
+ if isinstance(langs, list) and all(isinstance(x, str) for x in langs) and langs:
+ trig["language"] = [x.strip().lower()[:5] for x in langs if x.strip()]
+ cleaned.append(trig)
+ elif kind == "schedule":
+ cron = str(item.get("cron", "") or "").strip()
+ if not _cron_is_valid(cron):
+ continue
+ have_schedule = True
+ cleaned.append({"type": "schedule", "cron": cron})
+ elif kind == "hotkey":
+ combo = str(item.get("combo", "") or "").strip()
+ if combo:
+ cleaned.append({"type": "hotkey", "combo": combo})
+ hint = (inp.schedule_hint or "").strip()
+ if not have_schedule and _cron_is_valid(hint):
+ cleaned.append({"type": "schedule", "cron": hint})
+ return cleaned
+
+
+def _cron_is_valid(cron: str) -> bool:
+ if not cron or not _CRON_RE.match(cron):
+ return False
+ try:
+ from croniter import croniter # type: ignore
+
+ return bool(croniter.is_valid(cron))
+ except Exception: # noqa: BLE001 — croniter optional; superficial check stands
+ return True
+
+
def _coerce_brain_draft(
- data: dict[str, Any], inp: SkillCreatorInput
+ data: dict[str, Any],
+ inp: SkillCreatorInput,
+ context: AuthoringContext | None = None,
) -> dict[str, Any]:
"""Merge a brain-produced dict onto the empty-draft shape, dropping unknown
- keys and backfilling required ones from the skeleton."""
+ keys, backfilling required ones from the skeleton, and normalising the
+ fields the loader is strict about."""
skeleton = _skeleton_draft(inp)
draft = _empty_draft()
for key in draft:
@@ -150,7 +312,6 @@ def _coerce_brain_draft(
# Normalise list/dict typed fields defensively.
for list_key in (
"tags",
- "triggers",
"requires_tools",
"questions",
"assumptions",
@@ -158,10 +319,27 @@ def _coerce_brain_draft(
):
if not isinstance(draft[list_key], list):
draft[list_key] = []
+ else:
+ draft[list_key] = [str(x) for x in draft[list_key] if isinstance(x, (str, int, float))]
+ draft["triggers"] = _clean_triggers(draft.get("triggers"), inp)
if not isinstance(draft["risk_policy"], dict):
draft["risk_policy"] = {"default_tier": "ask"}
- draft["name"] = str(draft["name"]).strip() or skeleton["name"]
- draft["body"] = str(draft["body"]).strip() and draft["body"] or skeleton["body"]
+ tier = str(draft["risk_policy"].get("default_tier", "") or "").strip().lower()
+ if tier not in _ALLOWED_TIERS:
+ draft["risk_policy"]["default_tier"] = "ask"
+ else:
+ draft["risk_policy"]["default_tier"] = tier
+ # ``requires_tools`` must name tools that exist, or the skill carries a
+ # permanent validator warning for a name the model invented. With a live
+ # inventory the list is filtered against it; without one it stays as is.
+ if context is not None and context.tools:
+ known = context.tool_names
+ draft["requires_tools"] = [t for t in draft["requires_tools"] if t in known]
+ draft["name"] = str(draft["name"]).strip()[:80] or skeleton["name"]
+ draft["description"] = str(draft["description"]).strip() or skeleton["description"]
+ draft["category"] = str(draft["category"]).strip() or "general"
+ body = str(draft["body"]).strip()
+ draft["body"] = body if body else skeleton["body"]
return draft
@@ -307,6 +485,53 @@ def validate_skill_md(content: str) -> tuple[dict[str, Any], dict[str, Any] | No
)
+# ----------------------------------------------------------------------
+# Live authoring context (what the model gets to see)
+# ----------------------------------------------------------------------
+
+
+def _one_line(text: Any, limit: int) -> str:
+ flat = " ".join(str(text or "").split())
+ return flat if len(flat) <= limit else flat[: limit - 1] + "…"
+
+
+def build_authoring_context(
+ *,
+ brain_manager: Any | None = None,
+ registry: Any | None = None,
+) -> AuthoringContext:
+ """Collect the attached tools and installed skills for the author prompt.
+
+ ``brain_manager`` is the live BrainManager (its ``_tools`` dict IS the
+ surface the assistant will use at run time, so the names here are the
+ names the skill body may reference); ``registry`` is the skill registry.
+ Both optional; both read defensively — this must never break a turn.
+ """
+ tools: list[tuple[str, str]] = []
+ try:
+ live = getattr(brain_manager, "_tools", None) or {}
+ for name in sorted(live):
+ tool = live[name]
+ desc = _one_line(getattr(tool, "description", ""), _TOOL_DESCRIPTION_CHARS)
+ tools.append((str(name), desc))
+ if len(tools) >= _MAX_TOOLS_IN_PROMPT:
+ break
+ except Exception: # noqa: BLE001 — a broken tool object costs one line, not the draft
+ _LOG.debug("authoring context: tool inventory unreadable", exc_info=True)
+ skills: list[tuple[str, str]] = []
+ try:
+ active = registry.list_active() if registry is not None else []
+ for skill in active:
+ fm = getattr(skill, "frontmatter", None)
+ desc = _one_line(getattr(fm, "description", ""), _SKILL_DESCRIPTION_CHARS)
+ skills.append((str(getattr(skill, "name", "")), desc))
+ if len(skills) >= _MAX_SKILLS_IN_PROMPT:
+ break
+ except Exception: # noqa: BLE001
+ _LOG.debug("authoring context: skill list unreadable", exc_info=True)
+ return AuthoringContext(tools=tuple(tools), skills=tuple(skills))
+
+
# ----------------------------------------------------------------------
# Service
# ----------------------------------------------------------------------
@@ -323,12 +548,14 @@ class SkillCreatorService:
bus: Any | None = None,
config: Any | None = None,
user_skills_root: Path | None = None,
+ context: AuthoringContext | None = None,
) -> None:
self._brain = brain
self._registry = registry
self._bus = bus
self._config = config
self._user_skills_root = user_skills_root
+ self._context = context
async def draft(self, inp: SkillCreatorInput) -> SkillCreatorResult:
return await self._draft_or_refine(inp)
@@ -336,6 +563,50 @@ class SkillCreatorService:
async def refine(self, inp: SkillCreatorInput) -> SkillCreatorResult:
return await self._draft_or_refine(inp, refine=True)
+ async def author(self, inp: SkillCreatorInput) -> AuthoredSkill:
+ """One shot for voice/chat: brain-authored draft, committed as a draft.
+
+ Raises :class:`SkillCreatorUnavailable` when no brain produced the
+ draft — the deterministic skeleton is never committed from here (see
+ the module docstring). Raises :class:`SkillAuthoringError` when the
+ writer refuses (bad name, dead body, disk error). A name collision is
+ resolved by suffixing " 2", " 3", … — the user asked for the skill and
+ gets it, under a name the answer reports.
+ """
+ result = await self._draft_or_refine(inp)
+ if not result.brain_used:
+ raise SkillCreatorUnavailable(
+ "no brain could author the skill right now — nothing was written"
+ )
+ draft = dict(result.draft)
+ base_name = str(draft.get("name", "")).strip()
+ last_error: SkillAuthoringError | None = None
+ for attempt in range(1, 6):
+ draft["name"] = base_name if attempt == 1 else f"{base_name} {attempt}"
+ try:
+ skill = await self.commit(draft)
+ except SkillAuthoringError as exc:
+ if exc.status != 409:
+ raise
+ last_error = exc
+ continue
+ from jarvis.skills.authoring.service import slugify
+
+ return AuthoredSkill(
+ skill=skill,
+ result=SkillCreatorResult(
+ draft=draft,
+ skill_md=render_skill_md(draft),
+ validation=result.validation,
+ brain_used=True,
+ brain_source=result.brain_source,
+ ),
+ name=draft["name"],
+ slug=slugify(draft["name"]),
+ )
+ assert last_error is not None
+ raise last_error
+
async def commit(self, draft: dict[str, Any]) -> Skill:
"""Persist a reviewed draft as a real skill via the shared writer.
@@ -374,10 +645,13 @@ class SkillCreatorService:
skeleton = _skeleton_draft(inp)
draft = skeleton
brain_used = False
+ brain_source = ""
- brain_draft = await self._try_brain(inp, refine=refine)
- if brain_draft is not None:
- draft = _coerce_brain_draft(brain_draft, inp)
+ context = self._authoring_context()
+ brain_answer = await self._try_brain(inp, refine=refine, context=context)
+ if brain_answer is not None:
+ brain_draft, brain_source = brain_answer
+ draft = _coerce_brain_draft(brain_draft, inp, context)
brain_used = True
skill_md = render_skill_md(draft)
@@ -385,8 +659,14 @@ class SkillCreatorService:
# If a brain draft somehow failed validation, fall back to the skeleton
# (which is constructed to always validate).
if not validation["ok"] and brain_used:
+ _LOG.warning(
+ "creator: brain draft from %s failed validation (%s) — using skeleton",
+ brain_source,
+ "; ".join(validation.get("errors") or []),
+ )
draft = skeleton
brain_used = False
+ brain_source = ""
skill_md = render_skill_md(draft)
validation, _ = validate_skill_md(skill_md)
@@ -395,57 +675,108 @@ class SkillCreatorService:
skill_md=skill_md,
validation=validation,
brain_used=brain_used,
+ brain_source=brain_source,
)
- def _resolve_brain(self) -> Any | None:
- """A brain with a ``.complete()`` method, or None.
-
- Multi-provider contract (AP-21): follow the user's ACTIVE selection,
- never a hardcoded frontier favourite. The injected ``brain`` is the live
- ``BrainManager``; ask it for the provider the user currently has active
- (e.g. Gemini) rather than letting the frontier resolver pick an unkeyed
- Claude-API and 401. Order:
- 1. the BrainManager's active provider (``active_provider`` +
- ``_get_or_create``),
- 2. an injected raw provider that already exposes ``.complete``,
- 3. the frontier resolver from config (only when no usable brain was
- injected — e.g. the brain hasn't finished building yet).
- Any failure degrades to ``None`` → deterministic skeleton.
+ def _authoring_context(self) -> AuthoringContext:
+ """The injected context, or one collected from what was injected.
+
+ Reads ONLY the objects this service was given (the injected brain when
+ it is the live BrainManager, and the registry) — never a process-wide
+ reference. A service built without a brain must stay inert: no tool
+ inventory, no provider probing.
+ """
+ if self._context is not None:
+ return self._context
+ bm = self._brain
+ manager = bm if isinstance(getattr(bm, "_tools", None), dict) else None
+ return build_authoring_context(brain_manager=manager, registry=self._registry)
+
+ def _candidate_brains(self) -> Iterator[tuple[Any, str]]:
+ """Brains to try, best first, each with a label for the log and the
+ result. Never raises; yields nothing when nothing is reachable.
+
+ Multi-provider contract (AP-21/AP-22): follow the user's ACTIVE
+ selection first, never a hardcoded frontier favourite; then the model
+ the user pinned for the assistant's own work (Tool Model); then the API
+ quality tier; then the frontier chain. Each rung is only *tried* — a
+ rung that cannot answer (no key, timeout, garbage) crosses to the next
+ in :meth:`_try_brain`.
"""
+ seen: set[int] = set()
+
+ def _fresh(brain: Any) -> bool:
+ if brain is None or not hasattr(brain, "complete"):
+ return False
+ key = id(brain)
+ if key in seen:
+ return False
+ seen.add(key)
+ return True
+
bm = self._brain
if bm is not None:
getter = getattr(bm, "_get_or_create", None)
active = getattr(bm, "active_provider", None)
- if callable(getter) and isinstance(active, str):
+ if callable(getter) and isinstance(active, str) and active:
try:
prov = getter(active)
- if hasattr(prov, "complete"):
- return prov
except Exception as exc: # noqa: BLE001
_LOG.info("creator: active-provider resolve failed (%s)", exc)
- if hasattr(bm, "complete"):
- return bm
- if self._config is not None:
- try:
- from jarvis.brain.resolver import resolve_frontier_brain
+ prov = None
+ if _fresh(prov):
+ yield prov, f"active:{active}"
+ elif _fresh(bm):
+ # A raw provider was injected (tests, embedded use).
+ yield bm, "injected"
+
+ # The resolver rungs need a config; without one the ladder ends here.
+ # Deliberately no process-wide lookup: a service built without brain
+ # and config (a headless route, a test) must not start probing
+ # providers on its own.
+ config = self._config
+ if config is None:
+ return
- resolved = resolve_frontier_brain(self._config, bus=self._bus)
- if hasattr(resolved, "complete"):
- return resolved
+ try:
+ from jarvis.brain.resolver import (
+ resolve_frontier_brain,
+ resolve_quality_brain,
+ resolve_tool_model_brain,
+ )
+ except Exception: # noqa: BLE001
+ return
+
+ for label, resolver in (
+ ("tool_model", resolve_tool_model_brain),
+ ("quality", resolve_quality_brain),
+ ("frontier", resolve_frontier_brain),
+ ):
+ try:
+ brain = resolver(config, bus=self._bus)
except Exception as exc: # noqa: BLE001
- _LOG.info("creator: frontier resolve failed (%s)", exc)
- return None
+ _LOG.info("creator: %s resolve failed (%s)", label, exc)
+ continue
+ if _fresh(brain):
+ name = getattr(brain, "name", None) or label
+ yield brain, f"{label}:{name}"
async def _try_brain(
- self, inp: SkillCreatorInput, *, refine: bool
- ) -> dict[str, Any] | None:
- brain = self._resolve_brain()
- if brain is None:
- return None
+ self,
+ inp: SkillCreatorInput,
+ *,
+ refine: bool,
+ context: AuthoringContext | None = None,
+ ) -> tuple[dict[str, Any], str] | None:
+ """Ask the brains in ladder order; the first parseable draft wins.
+
+ Returns ``(draft_dict, source_label)`` or ``None`` when every rung
+ failed or the total budget is spent.
+ """
from jarvis.brain.streaming import aggregate
from jarvis.core.protocols import BrainMessage, BrainRequest
- system, user = _build_prompt(inp, refine=refine)
+ system, user = _build_prompt(inp, refine=refine, context=context)
request = BrainRequest(
messages=(BrainMessage(role="user", content=user),),
system=system,
@@ -453,58 +784,140 @@ class SkillCreatorService:
temperature=0.4,
stream=True,
)
- try:
- agg = await asyncio.wait_for(
- aggregate(brain.complete(request)), timeout=_BRAIN_TIMEOUT_S
- )
- except TimeoutError:
- _LOG.warning("creator: brain timed out — using skeleton")
- return None
- except Exception as exc: # noqa: BLE001
- _LOG.warning("creator: brain call failed (%s) — using skeleton", exc)
- return None
- return _extract_json(agg.text)
+ started = time.monotonic()
+ for brain, label in self._candidate_brains():
+ remaining = _BRAIN_TOTAL_BUDGET_S - (time.monotonic() - started)
+ if remaining <= 1.0:
+ _LOG.warning("creator: brain budget spent — no more rungs tried")
+ return None
+ timeout = min(_BRAIN_TIMEOUT_S, remaining)
+ try:
+ agg = await asyncio.wait_for(aggregate(brain.complete(request)), timeout=timeout)
+ except TimeoutError:
+ _LOG.warning("creator: %s timed out after %.0fs — next rung", label, timeout)
+ continue
+ except Exception as exc: # noqa: BLE001
+ _LOG.warning("creator: %s failed (%s) — next rung", label, exc)
+ continue
+ data = _extract_json(agg.text)
+ if data is None:
+ _LOG.warning("creator: %s returned no JSON draft — next rung", label)
+ continue
+ _LOG.info("creator: %s authored the draft in %.1fs", label, time.monotonic() - started)
+ return data, label
+ return None
# ----------------------------------------------------------------------
# Prompt
# ----------------------------------------------------------------------
-_SYSTEM_PROMPT = """You are Skill Creator. The user wants a new "skill" — a small \
-instruction card the assistant can trigger. Reply with ONE JSON object and nothing \
-else (no prose, no markdown fence). The object MUST have these keys:
- name (short Title Case), description (one sentence), category, tags (array of \
-strings), triggers (array of {type:"voice"|"hotkey"|"schedule", pattern/combo/cron}), \
-requires_tools (array of tool names), risk_policy ({default_tier:"safe"|"monitor"|"ask"}), \
-body (Markdown instructions), questions (array), assumptions (array), test_prompts (array).
-Never put executable code with eval/exec/os.system/subprocess(shell=True) in the body."""
-
-
-def _build_prompt(inp: SkillCreatorInput, *, refine: bool) -> tuple[str, str]:
- parts = [f"Intent: {inp.intent}"]
+_SYSTEM_PROMPT = """You are the Skill Author of a personal voice assistant. A "skill" is a \
+SKILL.md card: YAML frontmatter plus Markdown instructions that the assistant follows \
+step by step when the skill fires, using the tools it has connected. Your job is to turn \
+the user's spoken description into a COMPLETE, WORKING skill — not a paraphrase of what \
+they said. Reply with ONE JSON object and nothing else (no prose, no markdown fence).
+
+Keys of the object:
+- name: short Title Case name, 1-4 words, in the user's language ("Morgenroutine").
+- description: ONE sentence in the user's language: what the skill does AND when it \
+fires. This text is also how the assistant recognises the skill in new wording, so name \
+the actions and objects the user would say.
+- category: one of general, productivity, media, communication, dev, system, memory, home.
+- tags: 3-6 lowercase keywords.
+- triggers: array. Voice: {"type":"voice","pattern":"<regex>","language":["de","en"]} \
+where the pattern is the SHORT spoken phrase the user would say to start it — 1-4 words, \
+lowercase, alternatives allowed, no anchors, e.g. "(morgenroutine|morning routine)". \
+NEVER the description and never ".*". Schedule: {"type":"schedule","cron":"m h * * *"} \
+whenever the user named a time or recurrence ("jeden Morgen um 6" → "0 6 * * *", local \
+time). Include BOTH kinds when both apply. Omit hotkeys unless the user asked for one.
+- requires_tools: [] — unless you copy exact names from AVAILABLE TOOLS.
+- risk_policy: {"default_tier":"monitor"} for reading, playing, summarising, showing; \
+"ask" when the skill sends messages, deletes, pays, posts publicly or changes settings.
+- body: the instructions in Markdown, in the user's language, that the assistant will \
+follow at run time. Structure it as: one line stating the goal; a numbered "Steps" \
+section where EACH step names the connector/tool from AVAILABLE TOOLS it uses (or says \
+"if a tool for X is connected"), what exactly to fetch or do, and how to keep it short \
+for speech; the standing rule "skip a step gracefully in one short clause when its \
+integration is unavailable — never invent data"; then an "Answer format" section: ONE \
+flowing spoken reply of 3-6 short sentences, no lists, no markdown, no tool names, in the \
+user's language, ending with the most actionable item. Keep every specific the user gave \
+(times, counts, genres, examples such as "an 80s classic like Country Roads, a different \
+one each time", who or what to include). If the user described a routine with several \
+parts, every part becomes a step in the order they said it.
+- questions: things you genuinely could not infer (usually []).
+- assumptions: decisions you made on the user's behalf, one short line each.
+- test_prompts: 2-3 utterances that should start this skill.
+
+The user's description is a speech transcript: it may contain filler words, self-\
+corrections and misheard brand names (a ticket tool heard as a first name, a service \
+name split into two words). Infer what they meant and map it to the closest entry in \
+AVAILABLE TOOLS; mention that mapping under assumptions. Never put shell code, \
+eval/exec, credentials or API keys in the body."""
+
+
+def _build_prompt(
+ inp: SkillCreatorInput,
+ *,
+ refine: bool,
+ context: AuthoringContext | None = None,
+) -> tuple[str, str]:
+ parts = [f"USER'S DESCRIPTION (spoken transcript):\n{inp.intent.strip()}"]
if inp.name_hint:
parts.append(f"Preferred name: {inp.name_hint}")
- if inp.category:
+ if inp.category and inp.category != "general":
parts.append(f"Category hint: {inp.category}")
if inp.trigger_hint:
- parts.append(f"Trigger hint: {inp.trigger_hint}")
+ parts.append(f"Trigger hint (spoken phrase or schedule): {inp.trigger_hint}")
+ if inp.schedule_hint:
+ parts.append(f"Schedule hint: {inp.schedule_hint}")
+ if inp.language:
+ parts.append(
+ f"User's language: {inp.language} — write name, description, body and "
+ "voice trigger phrases in it."
+ )
if inp.extra_context:
parts.append(f"Extra context: {inp.extra_context}")
+ if context is not None:
+ if context.tools:
+ lines = "\n".join(
+ f"- {name} — {desc}" if desc else f"- {name}" for name, desc in context.tools
+ )
+ parts.append(
+ "AVAILABLE TOOLS (connected right now — use these names in the "
+ f"steps; nothing else exists):\n{lines}"
+ )
+ else:
+ parts.append(
+ "AVAILABLE TOOLS: none attached right now — write the steps as "
+ "'if a tool for X is connected' and keep them honest."
+ )
+ if context.skills:
+ lines = "\n".join(
+ f"- {name} — {desc}" if desc else f"- {name}" for name, desc in context.skills
+ )
+ parts.append(
+ "INSTALLED SKILLS (do not duplicate one; you may model the new "
+ f"skill on one):\n{lines}"
+ )
if refine and inp.existing_draft:
parts.append(
- "Revise this previous draft:\n"
- + json.dumps(inp.existing_draft, ensure_ascii=False)
+ "Revise this previous draft:\n" + json.dumps(inp.existing_draft, ensure_ascii=False)
)
if refine and inp.feedback:
parts.append(f"User feedback to apply: {inp.feedback}")
parts.append("Return only the JSON object.")
- return _SYSTEM_PROMPT, "\n".join(parts)
+ return _SYSTEM_PROMPT, "\n\n".join(parts)
__all__ = [
+ "AuthoredSkill",
+ "AuthoringContext",
"SkillCreatorInput",
"SkillCreatorResult",
"SkillCreatorService",
+ "SkillCreatorUnavailable",
+ "build_authoring_context",
"render_skill_md",
"validate_skill_md",
]
diff --git a/jarvis/skills/guards.py b/jarvis/skills/guards.py
index 40438c0a99..5ea5aba186 100644
--- a/jarvis/skills/guards.py
+++ b/jarvis/skills/guards.py
@@ -55,6 +55,12 @@ VETO_SHADOW_MODE = "shadow_mode"
# Applied by the brain's capture path (it needs the token store), never by the
# pure guard ladder, so the offline routing eval stays credential-free.
VETO_PLUGIN_NOT_CONNECTED = "plugin_not_connected"
+# The user asked to CREATE a skill ("erstell mir einen Skill, der …"), # i18n-allow: example
+# and every service named inside that request is the new skill's CONTENT, never a command
+# — so no domain skill may capture the turn. Applied by the brain's capture path
+# via :mod:`jarvis.skills.authoring_request` when the ``skill-creator`` builtin
+# is not available to take the turn itself.
+VETO_AUTHORING_REQUEST = "authoring_request"
VETO_REASONS: frozenset[str] = frozenset({
VETO_DEFINITIONAL,
@@ -70,6 +76,7 @@ VETO_REASONS: frozenset[str] = frozenset({
VETO_KILL_SWITCH,
VETO_SHADOW_MODE,
VETO_PLUGIN_NOT_CONNECTED,
+ VETO_AUTHORING_REQUEST,
})
#: Guard identifiers, in the order the ladder evaluates them. Exposed so the
@@ -342,6 +349,7 @@ __all__ = [
"GUARD_ORDER",
"LOCAL_ACTION_CLAIMING_MODES",
"MATCHABLE_STATES",
+ "VETO_AUTHORING_REQUEST",
"VETO_AUTO_FIRE_NEVER",
"VETO_BAND_BELOW_FLOOR",
"VETO_BLOCK_TIER",
diff --git a/jarvis/skills/prompt_injection.py b/jarvis/skills/prompt_injection.py
index 8be2b8faff..0756efc314 100644
--- a/jarvis/skills/prompt_injection.py
+++ b/jarvis/skills/prompt_injection.py
@@ -185,6 +185,10 @@ def render_available_skills_section(
body = "\n".join(bullets)
outro = (
"\n\nIf several skills could match, pick the most specific one. "
- "Draft/disabled skills are rejected by the tool automatically."
+ "Draft/disabled skills are rejected by the tool automatically. "
+ "When the user asks you to CREATE a new skill "
+ "(\"erstell mir einen Skill, der …\", " # i18n-allow: quoted phrase
+ "\"create a skill that …\"), call the `create-skill` tool with their "
+ "full description — never `run-skill`, and never a worker."
)
return f"{header}\n{intro}\n{body}{outro}"
diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.py
index 52e0252588..5934ad68b9 100644
--- a/jarvis/ui/web/skills_routes.py
+++ b/jarvis/ui/web/skills_routes.py
@@ -248,6 +248,17 @@ class SkillCreatorDraftBody(BaseModel):
category: str = Field(default="general", max_length=80)
trigger_hint: str = Field(default="", max_length=500)
extra_context: str = Field(default="", max_length=4000)
+ # A 5-field cron (local time) or a spoken recurrence the caller already
+ # extracted, and the user's language code so the skill is written in it.
+ schedule_hint: str = Field(default="", max_length=120)
+ language: str = Field(default="", max_length=8)
+
+
+class SkillCreatorAuthorBody(SkillCreatorDraftBody):
+ """Body for ``POST /api/skills/creator/author`` — draft AND commit in one
+ call, the way voice/chat (``create-skill`` tool) and ``jarvisctl skills
+ create`` do it. Brain-REQUIRED: without an authoring brain the call fails
+ with 503 and writes nothing (a skeleton is never committed unreviewed)."""
class SkillCreatorRefineBody(SkillCreatorDraftBody):
@@ -372,13 +383,23 @@ async def create_skill_draft(
) -> dict[str, Any]:
"""Generates an AI draft without writing any files."""
_require_optional_module("jarvis.skills.creator_service", "Skill Creator")
- from jarvis.skills.creator_service import SkillCreatorInput, SkillCreatorService
+ from jarvis.skills.creator_service import (
+ SkillCreatorInput,
+ SkillCreatorService,
+ build_authoring_context,
+ )
reg = _require_registry(request)
brain = getattr(request.app.state, "brain", None)
bus = getattr(request.app.state, "bus", None)
config = getattr(request.app.state, "config", None)
- service = SkillCreatorService(brain=brain, registry=reg, bus=bus, config=config)
+ service = SkillCreatorService(
+ brain=brain,
+ registry=reg,
+ bus=bus,
+ config=config,
+ context=build_authoring_context(brain_manager=brain, registry=reg),
+ )
result = await service.draft(
SkillCreatorInput(
intent=body.intent,
@@ -386,6 +407,8 @@ async def create_skill_draft(
category=body.category,
trigger_hint=body.trigger_hint,
extra_context=body.extra_context,
+ schedule_hint=body.schedule_hint,
+ language=body.language,
)
)
return {
@@ -393,6 +416,68 @@ async def create_skill_draft(
"skill_md": result.skill_md,
"validation": result.validation,
"brain_used": result.brain_used,
+ "brain_source": result.brain_source,
+ }
+
+
[email protected]("/creator/author")
+async def author_skill(
+ body: SkillCreatorAuthorBody,
+ request: Request,
+) -> dict[str, Any]:
+ """Author AND commit a new skill in one call (voice/CLI parity).
+
+ The brain writes the whole skill from ``intent`` — trigger phrase, schedule
+ cron, steps per connected tool, spoken answer format — and it lands as
+ ``state: draft`` (AP-15): activate it in the Skills view. 503 when no brain
+ could author it (nothing is written), 409/400 from the writer as usual.
+ """
+ _require_optional_module("jarvis.skills.creator_service", "Skill Creator")
+ from jarvis.skills.authoring import SkillAuthoringError
+ from jarvis.skills.creator_service import (
+ SkillCreatorInput,
+ SkillCreatorService,
+ SkillCreatorUnavailable,
+ build_authoring_context,
+ )
+
+ reg = _require_registry(request)
+ brain = getattr(request.app.state, "brain", None)
+ bus = getattr(request.app.state, "bus", None)
+ config = getattr(request.app.state, "config", None)
+ service = SkillCreatorService(
+ brain=brain,
+ registry=reg,
+ bus=bus,
+ config=config,
+ context=build_authoring_context(brain_manager=brain, registry=reg),
+ )
+ try:
+ authored = await service.author(
+ SkillCreatorInput(
+ intent=body.intent,
+ name_hint=body.name_hint,
+ category=body.category,
+ trigger_hint=body.trigger_hint,
+ extra_context=body.extra_context,
+ schedule_hint=body.schedule_hint,
+ language=body.language,
+ )
+ )
+ except SkillCreatorUnavailable as exc:
+ raise HTTPException(status_code=503, detail=str(exc)) from exc
+ except SkillAuthoringError as exc:
+ raise HTTPException(status_code=exc.status, detail=str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ detail = _skill_to_detail(authored.skill)
+ return {
+ "skill": detail,
+ "draft": authored.result.draft,
+ "skill_md": authored.result.skill_md,
+ "validation": authored.result.validation,
+ "brain_used": True,
+ "brain_source": authored.result.brain_source,
}
@@ -403,13 +488,23 @@ async def refine_skill_draft(
) -> dict[str, Any]:
"""Revises an AI draft based on feedback / follow-up questions."""
_require_optional_module("jarvis.skills.creator_service", "Skill Creator")
- from jarvis.skills.creator_service import SkillCreatorInput, SkillCreatorService
+ from jarvis.skills.creator_service import (
+ SkillCreatorInput,
+ SkillCreatorService,
+ build_authoring_context,
+ )
reg = _require_registry(request)
brain = getattr(request.app.state, "brain", None)
bus = getattr(request.app.state, "bus", None)
config = getattr(request.app.state, "config", None)
- service = SkillCreatorService(brain=brain, registry=reg, bus=bus, config=config)
+ service = SkillCreatorService(
+ brain=brain,
+ registry=reg,
+ bus=bus,
+ config=config,
+ context=build_authoring_context(brain_manager=brain, registry=reg),
+ )
result = await service.refine(
SkillCreatorInput(
intent=body.intent,
@@ -419,6 +514,8 @@ async def refine_skill_draft(
extra_context=body.extra_context,
existing_draft=body.draft,
feedback=body.feedback,
+ schedule_hint=body.schedule_hint,
+ language=body.language,
)
)
return {
@@ -426,6 +523,7 @@ async def refine_skill_draft(
"skill_md": result.skill_md,
"validation": result.validation,
"brain_used": result.brain_used,
+ "brain_source": result.brain_source,
}
diff --git a/pyproject.toml b/pyproject.toml
index ebea930e2d..913e8ca5b6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -773,13 +773,18 @@ update-profile = "jarvis.plugins.tool.profile_update:UpdateProfileTool"
# could never load. It is absent from ROUTER_TOOLS (the only allow-set, so
# factory.py filtered it out), and its __init__ requires a `runner=` argument
# the entry-point loader cannot supply, so the tempting one-line "just add it to
-# ROUTER_TOOLS" fix raises TypeError at tool load. The entry point is removed
-# rather than wired, because the capability is not missing: the `skill-creator`
-# builtin plus POST /api/skills/creator/{draft,refine,validate,commit} are the
-# live authoring path, already enforcing the AP-15 draft guard. A router tool
-# would be a third route to the same behaviour and a fourth place to forget that
-# guard. Enforced by
+# ROUTER_TOOLS" fix raises TypeError at tool load. Enforced by
# tests/unit/brain/test_router_tool_entrypoint_parity.py.
+# create-skill (2026-08-18) — the brain-reachable authoring path that note
+# said was unnecessary. It was: the voice turn "erstell mir einen neuen Skill
+# …" (2026-08-18 17:51) had no tool to write a skill and died on three
+# `jarvisctl --help` rounds. Unlike the phantom, this tool takes only what the
+# loader can give (bus, config) and resolves the registry + brain lazily. It
+# calls the SAME SkillCreatorService the UI dialog and `jarvisctl skills
+# create` use, so the AP-15 draft guard is enforced in ONE place (`commit`
+# forces state=draft). Router-tier, monitor, never a spawn (AP-5/AP-14). See
+# ADR-0011 amendment "create-skill router tool".
+create-skill = "jarvis.plugins.tool.create_skill:CreateSkillTool"
# App-Control (2026-05-31) — gives the brain a complete overview of the Desktop
# App and lets it change settings/providers/MCP by voice/chat. Router-tier;
# direct safe/ask-gated actions, never a spawn (AP-5/AP-14). describe is read-only
diff --git a/tests/fixtures/skill_routing/golden.yaml b/tests/fixtures/skill_routing/golden.yaml
index 38fc5a6ed8..9481dc062c 100644
--- a/tests/fixtures/skill_routing/golden.yaml
+++ b/tests/fixtures/skill_routing/golden.yaml
@@ -538,6 +538,16 @@ skills:
lang: de
min_band: fire
source: authored
+ # forensic 2026-08-18 17:51 (voice session): the conjugated verb AFTER
+ # the noun ("… einen neuen Skill erstellst") missed the infinitive-only
+ # trigger of the day, and the brand mentioned INSIDE the description
+ # handed the turn to plugin-youtube_music. Trigger channel: the authoring
+ # phrase must outrank the brand mention. Transcript shortened, wording kept.
+ - text: "ich möchte dass du mir bitte einen neuen skill erstellst und zwar morgenroutine, der soll jeden morgen um 6 uhr meine e-mails und kalendereinträge vorlesen und dann ein lied mit youtube music abspielen"
+ channel: trigger
+ lang: de
+ min_band: fire
+ source: forensic
# --- Known gaps -------------------------------------------------------
# This skill carries no voice trigger AND thin, English-only vocabulary, so
diff --git a/tests/unit/brain/test_routing.py b/tests/unit/brain/test_routing.py
index fe614f3268..bb1618147f 100644
--- a/tests/unit/brain/test_routing.py
+++ b/tests/unit/brain/test_routing.py
@@ -1866,6 +1866,11 @@ def test_router_tools_is_pure_dispatcher_set() -> None:
"awareness-recall",
# Skills-Brain-Integration (also in SUB_TOOLS — structural D9 protection)
"run-skill",
+ # Skill authoring by voice/chat (2026-08-18): the brain writes a NEW
+ # skill from the user's description in one bounded call, committed
+ # as state=draft (AP-15). Direct gated action (monitor), never a
+ # spawn (AP-5/AP-14). ADR-0011 amendment "create-skill router tool".
+ "create-skill",
# Phase B5 (recall-tool): read-only keyword search over the wiki vault.
"wiki-recall",
# Phase B5 follow-up (commit 825b1f94a): full-page reader (read-only)
diff --git a/tests/unit/brain/test_skill_authoring_turn.py b/tests/unit/brain/test_skill_authoring_turn.py
new file mode 100644
index 0000000000..b2f0f0b343
--- /dev/null
+++ b/tests/unit/brain/test_skill_authoring_turn.py
@@ -0,0 +1,182 @@
+"""A request to CREATE a skill is never captured by a skill it merely mentions.
+
+Live bug (voice session 2026-08-18 17:51): the German request for a new
+"morning routine" skill that ends "… and then a song on YouTube Music" was
+captured by ``plugin-youtube_music`` — its brand-only trigger matched the words
+INSIDE the description of the skill the user wanted built. The music skill's
+instructions were injected, the model burned the tool budget on
+``jarvisctl --help`` and the user heard the spoken "that did not work".
+
+The fix is a deterministic channel ahead of the trigger channel
+(``jarvis.skills.authoring_request``): an authoring request resolves to the
+``skill-creator`` builtin when it is active, and to NO skill otherwise —
+never to a connector named inside the request. Force-spawn and the evidence
+gate stand down on such a turn; the ``create-skill`` router tool owns it.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from jarvis.brain.manager import BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import JarvisConfig
+from jarvis.core.protocols import ToolResult
+from jarvis.skills.registry import SkillRegistry
+from jarvis.skills.skill_context import SkillContext, set_skill_context
+
+LIVE_UTTERANCE = (
+ "Ich möchte, dass du mich bitte einen neuen Skill erstellst und zwar morgen " # i18n-allow: transcript
+ "routine, der soll immer unter früh um 6 Uhr ähm ähm getriggert werden, " # i18n-allow: transcript
+ "gesetzt wird jeden Morgen um 6 Uhr, wo all meine E-Mails, Lenya Tickets und " # i18n-allow: transcript
+ "ähm alle wichtigen Kalendereinträge ähm abgespielt werden und dann ein " # i18n-allow: transcript
+ "schönes Lied abgespielt wird mit YouTube Music zum Aufstehen und zwar ein " # i18n-allow: transcript
+ "Klassiker aus den 80er, wie Country Road oder so ETC immer was neues." # i18n-allow: transcript
+)
+
+
+class _FakeTool:
+ def __init__(self, name: str) -> None:
+ self.name = name
+ self.schema: dict[str, Any] = {}
+
+
+class _RecordingExecutor:
+ def __init__(self) -> None:
+ self.calls: list[tuple[Any, dict[str, Any], str]] = []
+
+ async def execute(self, tool: Any, args: dict[str, Any], *, user_utterance: str = "", trace_id: Any = None, **_: Any) -> ToolResult:
+ self.calls.append((tool, args, user_utterance))
+ return ToolResult(success=True, output="ok")
+
+
+class _StubRunner:
+ def render_instructions(self, skill: Any, *, args: dict | None = None) -> str:
+ return f"# {skill.name}\nDo the thing."
+
+
+def _write_skill(root: Path, name: str, pattern: str, *, category: str = "general") -> None:
+ d = root / name
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "SKILL.md").write_text(
+ "---\n"
+ 'schema_version: "1"\n'
+ f"name: {name}\n"
+ f"description: Demo skill {name}.\n"
+ f"category: {category}\n"
+ "triggers:\n"
+ " - type: voice\n"
+ f" pattern: '{pattern}'\n"
+ " language: [de, en]\n"
+ "---\n"
+ "# Demo\nFollow the steps.\n",
+ encoding="utf-8",
+ )
+
+
+def _make_manager() -> BrainManager:
+ config = JarvisConfig()
+ config.brain.routing.force_spawn_mode = "permissive"
+ return BrainManager(
+ config=config,
+ bus=EventBus(),
+ tools={
+ "spawn_worker": _FakeTool("spawn_worker"),
+ "run-skill": _FakeTool("run-skill"),
+ "create-skill": _FakeTool("create-skill"),
+ "youtube_music": _FakeTool("youtube_music"),
+ },
+ tool_executor=_RecordingExecutor(), # type: ignore[arg-type]
+ )
+
+
+def _context(root: Path, *, with_creator: bool) -> None:
+ # The music connector's real trigger is brand-only and un-anchored, so it
+ # fires on ANY mention of the brand — that is what captured the live turn.
+ _write_skill(root, "plugin-youtube_music", "(youtube ?music|yt ?music|ytmusic)", category="media")
+ if with_creator:
+ # A stand-in for the builtin: name is what the resolver looks up.
+ _write_skill(root, "skill-creator", "(cre[a]te|b[u]ild)\\s+a\\s+skill", category="meta")
+ registry = SkillRegistry(root=root)
+ registry.reload_sync()
+ set_skill_context(SkillContext(registry=registry, runner=_StubRunner())) # type: ignore[arg-type]
+
+
[email protected](autouse=True)
+def _clean_ctx():
+ set_skill_context(None)
+ yield
+ set_skill_context(None)
+
+
+# ----------------------------------------------------------------------
+# Premise control: the brand trigger DOES capture a plain music command
+# ----------------------------------------------------------------------
+
+
+def test_control_music_command_is_captured_by_the_music_skill(tmp_path: Path) -> None:
+ _context(tmp_path, with_creator=True)
+ m = _make_manager()
+ matched = m._match_skill_for_turn("spiel country roads auf youtube music") # i18n-allow: test input
+ assert matched is not None
+ assert matched.name == "plugin-youtube_music"
+ assert m._skill_authoring_turn is False
+
+
+# ----------------------------------------------------------------------
+# The live turn: authoring beats the brand trigger
+# ----------------------------------------------------------------------
+
+
+def test_live_utterance_resolves_to_skill_creator_not_youtube_music(tmp_path: Path) -> None:
+ _context(tmp_path, with_creator=True)
+ m = _make_manager()
+ matched = m._match_skill_for_turn(LIVE_UTTERANCE)
+ assert matched is not None
+ assert matched.name == "skill-creator"
+ assert m._skill_authoring_turn is True
+
+
+def test_live_utterance_captures_nobody_when_skill_creator_is_disabled(tmp_path: Path) -> None:
+ """The protection does not hinge on the builtin being on: with it gone the
+ music skill still may not take the turn — the create-skill tool owns it."""
+ _context(tmp_path, with_creator=False)
+ m = _make_manager()
+ assert m._match_skill_for_turn(LIVE_UTTERANCE) is None
+ assert m._skill_authoring_turn is True
+
+
+def test_authoring_turn_is_flagged_even_without_a_skill_context() -> None:
+ m = _make_manager()
+ assert m._match_skill_for_turn(LIVE_UTTERANCE) is None
+ assert m._skill_authoring_turn is True
+
+
+# ----------------------------------------------------------------------
+# Stand-downs: force-spawn and the evidence gate
+# ----------------------------------------------------------------------
+
+
+def test_force_spawn_stands_down_on_an_authoring_turn(tmp_path: Path) -> None:
+ _context(tmp_path, with_creator=False)
+ m = _make_manager()
+ assert m._should_force_spawn(LIVE_UTTERANCE) is False
+
+
+def test_evidence_gate_passes_on_an_authoring_turn(tmp_path: Path) -> None:
+ _context(tmp_path, with_creator=False)
+ m = _make_manager()
+ m._skill_turn_match = m._match_skill_for_turn(LIVE_UTTERANCE)
+ verdict = m._run_evidence_gate(LIVE_UTTERANCE)
+ assert verdict.kind == "pass"
+
+
+def test_flag_resets_on_the_next_probe(tmp_path: Path) -> None:
+ _context(tmp_path, with_creator=True)
+ m = _make_manager()
+ m._match_skill_for_turn(LIVE_UTTERANCE)
+ assert m._skill_authoring_turn is True
+ m._match_skill_for_turn("spiel country roads auf youtube music") # i18n-allow: test input
+ assert m._skill_authoring_turn is False
diff --git a/tests/unit/cli_ctl/test_commands_wave23.py b/tests/unit/cli_ctl/test_commands_wave23.py
index b5f02a10e8..29e35a42a5 100644
--- a/tests/unit/cli_ctl/test_commands_wave23.py
+++ b/tests/unit/cli_ctl/test_commands_wave23.py
@@ -33,6 +33,22 @@ def test_skills_draft_sends_intent(capture_api):
assert call["body"]["intent"] == "do a thing"
+def test_skills_create_authors_and_writes_in_one_step(capture_api):
+ """The CLI twin of the voice path's create-skill tool: one call, one route."""
+ res = runner.invoke(
+ app,
+ ["skills", "create", "read my mail every morning", "--name", "Mail Morning",
+ "--schedule", "0 6 * * *", "--language", "en"],
+ )
+ assert res.exit_code == 0, res.output
+ call = _last(capture_api)
+ assert call["path"] == "/api/skills/creator/author"
+ assert call["body"]["intent"] == "read my mail every morning"
+ assert call["body"]["name_hint"] == "Mail Morning"
+ assert call["body"]["schedule_hint"] == "0 6 * * *"
+ assert call["body"]["language"] == "en"
+
+
# --- outputs --------------------------------------------------------------
def test_outputs_list(capture_api):
runner.invoke(app, ["outputs", "list"])
diff --git a/tests/unit/plugins/test_create_skill_tool.py b/tests/unit/plugins/test_create_skill_tool.py
new file mode 100644
index 0000000000..d7309e6137
--- /dev/null
+++ b/tests/unit/plugins/test_create_skill_tool.py
@@ -0,0 +1,208 @@
+"""The ``create-skill`` router tool — the brain writes a new skill by voice.
+
+Locks what the 2026-08-18 17:51 voice turn was missing: a registered,
+router-visible, loader-constructible tool that turns "erstell mir einen
+neuen Skill …" into a brain-authored SKILL.md draft in ONE call — and that
+refuses honestly, writing nothing, when no brain can author it.
+
+Fakes, no ``unittest.mock``: a fake brain manager whose active provider
+answers a fixed JSON draft, a real ``SkillRegistry`` on ``tmp_path``.
+"""
+from __future__ import annotations
+
+from importlib.metadata import entry_points
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.brain.factory import ROUTER_TOOLS
+from jarvis.core import runtime_refs
+from jarvis.core.protocols import BrainDelta, ExecutionContext
+from jarvis.plugins.tool.create_skill import CreateSkillTool
+from jarvis.skills import prefs
+from jarvis.skills.registry import SkillRegistry
+from jarvis.skills.schema import SkillLifecycleState
+from jarvis.skills.skill_context import SkillContext, set_skill_context
+
+_DRAFT_JSON = """{
+ "name": "Morgenroutine",
+ "description": "Reads mail, tickets and calendar in the morning, then plays a song on YouTube Music.",
+ "category": "productivity",
+ "tags": ["morning", "routine", "music"],
+ "triggers": [
+ {"type": "voice", "pattern": "(morgenroutine|morning routine)", "language": ["de", "en"]},
+ {"type": "schedule", "cron": "0 6 * * *"}
+ ],
+ "requires_tools": [],
+ "risk_policy": {"default_tier": "monitor"},
+ "body": "Short morning briefing, then music.\\n\\n## Steps\\n\\n1. gmail: unread mail, name at most three.\\n2. linear: summarise the open tickets.\\n3. google_calendar: the important events of the day.\\n4. youtube_music: play an 80s classic like Country Roads, a different one each time.\\n\\n## Answer format\\n\\nOne flowing spoken reply.\\n",
+ "assumptions": ["Lenya Tickets = Linear"],
+ "test_prompts": ["starte die morgenroutine"]
+}"""
+
+
+class _FakeBrain:
+ def __init__(self, text: str | None) -> None:
+ self._text = text
+ self.calls = 0
+
+ def complete(self, request): # noqa: ANN001
+ self.calls += 1
+ if self._text is None:
+ raise RuntimeError("No API key found")
+
+ async def _gen():
+ yield BrainDelta(content=self._text, finish_reason="stop")
+
+ return _gen()
+
+
+class _FakeManager:
+ """Looks like the live BrainManager to the tool: active provider + tools."""
+
+ def __init__(self, provider: Any) -> None:
+ self._provider = provider
+ self.active_provider = "vertex"
+ self._tools = {
+ "gmail": SimpleNamespace(description="Read Gmail."),
+ "youtube_music": SimpleNamespace(description="Play music on YouTube Music."),
+ }
+ self._config = None
+
+ def _get_or_create(self, name: str): # noqa: ANN202
+ return self._provider
+
+
+class _StubRunner:
+ def render_instructions(self, skill: Any, *, args: dict | None = None) -> str:
+ return skill.body
+
+
+def skills_root(tmp_path: Path) -> Path:
+ root = tmp_path / "skills"
+ root.mkdir()
+ return root
+
+
+def registry(skills_root: Path) -> SkillRegistry:
+ reg = SkillRegistry(skills_root, bus=None, state_prefs_loader=prefs.load_state_overrides)
+ reg.reload_sync()
+ set_skill_context(SkillContext(registry=reg, runner=_StubRunner())) # type: ignore[arg-type]
+ yield reg
+ set_skill_context(None)
+
+
[email protected](autouse=True)
+def _clean_refs():
+ runtime_refs._reset_for_tests()
+ set_skill_context(None)
+ yield
+ runtime_refs._reset_for_tests()
+ set_skill_context(None)
+
+
+def _ctx(language: str = "de") -> ExecutionContext:
+ from uuid import uuid4
+
+ return ExecutionContext(
+ trace_id=uuid4(),
+ user_utterance="erstell mir einen neuen skill", # i18n-allow: test input
+ config={"output_language": language},
+ memory_read=None,
+ )
+
+
+# ----------------------------------------------------------------------
+# Wiring: registered, router-visible, loader-constructible
+# ----------------------------------------------------------------------
+
+
+def test_registered_and_router_visible() -> None:
+ names = {e.name for e in entry_points(group="jarvis.tool")}
+ assert "create-skill" in names
+ assert "create-skill" in ROUTER_TOOLS
+
+
+def test_loader_can_construct_it_without_arguments() -> None:
+ """The phantom spawn-skill-author needed a runner the loader could not give;
+ this one takes only what factory.py passes (bus, config) — or nothing."""
+ tool = CreateSkillTool()
+ assert tool.name == "create-skill"
+ assert tool.risk_tier == "monitor"
+ assert set(tool.schema["required"]) == {"intent", "name", "trigger_phrase", "schedule"}
+
+
+def test_description_is_disjoint_from_run_skill() -> None:
+ desc = CreateSkillTool.description.lower()
+ assert "new skill" in desc
+ assert "run-skill" in desc # names the sibling so the model can tell them apart
+
+
+# ----------------------------------------------------------------------
+# The happy path: one call → a draft skill on disk
+# ----------------------------------------------------------------------
+
+
+async def test_writes_a_brain_authored_draft_skill(registry, skills_root) -> None:
+ provider = _FakeBrain(_DRAFT_JSON)
+ runtime_refs.set_brain_manager(_FakeManager(provider))
+ tool = CreateSkillTool()
+ result = await tool.execute(
+ {
+ "intent": "jeden morgen um 6 mails, tickets, kalender vorlesen und dann ein lied auf youtube music", # i18n-allow: test input
+ "name": "Morgenroutine",
+ "trigger_phrase": "",
+ "schedule": "0 6 * * *",
+ },
+ _ctx("de"),
+ )
+ assert result.success, result.error
+ out = result.output
+ assert out["skill_name"] == "Morgenroutine"
+ assert out["state"] == "draft"
+ assert out["schedule_crons"] == ["0 6 * * *"]
+ assert out["voice_triggers"] == ["(morgenroutine|morning routine)"]
+ assert out["ui_section"] == "skills"
+ assert any("youtube_music" in step for step in out["steps_preview"])
+ assert provider.calls == 1
+
+ skill = registry.get("Morgenroutine")
+ assert skill.state == SkillLifecycleState.DRAFT # AP-15: never auto-active
+ on_disk = (skills_root / "morgenroutine" / "SKILL.md").read_text(encoding="utf-8")
+ assert "state: draft" in on_disk
+ assert "cron: 0 6 * * *" in on_disk
+
+
+# ----------------------------------------------------------------------
+# Honest failures: nothing is written
+# ----------------------------------------------------------------------
+
+
+async def test_no_brain_means_no_skill_and_an_honest_error(registry, skills_root) -> None:
+ runtime_refs.set_brain_manager(_FakeManager(_FakeBrain(None)))
+ result = await CreateSkillTool().execute(
+ {"intent": "pause spotify when I talk", "name": "", "trigger_phrase": "", "schedule": ""},
+ _ctx(),
+ )
+ assert result.success is False
+ assert result.error is not None and result.error.startswith("author_unavailable")
+ assert not any(skills_root.iterdir())
+
+
+async def test_missing_intent_is_rejected(registry) -> None:
+ result = await CreateSkillTool().execute({"intent": " ", "name": "", "trigger_phrase": "", "schedule": ""}, _ctx())
+ assert result.success is False
+ assert result.error is not None and result.error.startswith("invalid_input")
+
+
+async def test_without_a_skill_context_it_reports_and_writes_nothing() -> None:
+ runtime_refs.set_brain_manager(_FakeManager(_FakeBrain(_DRAFT_JSON)))
+ result = await CreateSkillTool().execute(
+ {"intent": "something", "name": "", "trigger_phrase": "", "schedule": ""}, _ctx()
+ )
+ assert result.success is False
+ assert result.error is not None and result.error.startswith("skills_unavailable")
diff --git a/tests/unit/skills/test_authoring_request.py b/tests/unit/skills/test_authoring_request.py
new file mode 100644
index 0000000000..bdbd5be84f
--- /dev/null
+++ b/tests/unit/skills/test_authoring_request.py
@@ -0,0 +1,157 @@
+"""Unit tests for ``jarvis.skills.authoring_request``.
+
+The resolver states one rule: when the user asks to CREATE a skill, every
+service they name is the skill's CONTENT, never a command — so a brand
+mentioned inside the request must not capture the turn. Precision over
+recall: every entry in the "misses" section is a hard negative.
+
+Lightweight fakes, no ``unittest.mock`` (CLAUDE.md testing convention).
+"""
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+import pytest
+
+from jarvis.skills.authoring_request import (
+ AUTHORING_SKILL_NAME,
+ is_skill_authoring_request,
+ resolve_skill_authoring_request,
+)
+from jarvis.skills.match_eval import BAND_FIRE, BAND_NONE, SOURCE_TRIGGER
+
+
+@dataclass
+class _FakeSkill:
+ name: str
+ frontmatter: object | None = None
+ state: str = "validated"
+ body: str = ""
+ resources: dict = field(default_factory=dict)
+
+
+class _FakeRegistry:
+ def __init__(self, names: list[str]) -> None:
+ self._skills = [_FakeSkill(name=n) for n in names]
+
+ def list_active(self) -> list[_FakeSkill]:
+ return list(self._skills)
+
+
+#: The exact transcript of the 2026-08-18 17:51 voice turn that this module
+#: exists for — verbatim, filler words and misheard "Lenya Tickets" included.
+LIVE_UTTERANCE = (
+ "Ich möchte, dass du mich bitte einen neuen Skill erstellst und zwar morgen " # i18n-allow: transcript
+ "routine, der soll immer unter früh um 6 Uhr ähm ähm getriggert werden, " # i18n-allow: transcript
+ "gesetzt wird jeden Morgen um 6 Uhr, wo all meine E-Mails, Lenya Tickets und " # i18n-allow: transcript
+ "ähm alle wichtigen Kalendereinträge ähm abgespielt werden und dann ein " # i18n-allow: transcript
+ "schönes Lied abgespielt wird mit YouTube Music zum Aufstehen und zwar ein " # i18n-allow: transcript
+ "Klassiker aus den 80er, wie Country Road oder so ETC immer was neues." # i18n-allow: transcript
+)
+
+
+# ---------------------------------------------------------------------------
+# Hits — the request is an authoring request
+# ---------------------------------------------------------------------------
+
+
+ "utterance",
+ [
+ LIVE_UTTERANCE,
+ "erstell mir einen skill der abends das licht dimmt", # i18n-allow: test input
+ "bau mir bitte einen neuen skill für die morgenroutine", # i18n-allow: test input
+ "kannst du einen skill erstellen der jeden morgen meine mails vorliest", # i18n-allow: test input
+ "leg einen neuen skill an: fokusmodus", # i18n-allow: test input
+ "mach aus diesem workflow einen skill", # i18n-allow: test input
+ "erstell skill morgenroutine", # i18n-allow: test input
+ "Skill erstellen: Abendroutine mit Spotify", # i18n-allow: test input
+ "dass er einen skill erstellt der abends das licht dimmt", # i18n-allow: test input
+ "create a skill that reads my calendar every morning",
+ "turn this into a skill",
+ "make me a new skill for the evening",
+ "set up a skill for my monday review",
+ "crea un skill que lea mi correo", # i18n-allow: test input
+ ],
+)
+def test_authoring_requests_are_detected(utterance: str) -> None:
+ assert is_skill_authoring_request(utterance) is True
+
+
+# ---------------------------------------------------------------------------
+# Misses — hard negatives that must never resolve
+# ---------------------------------------------------------------------------
+
+
+ "utterance",
+ [
+ # run / use / toggle / delete an existing skill
+ "nutz den skill morning-routine bitte", # i18n-allow: test input
+ "starte den skill deep-work-mode", # i18n-allow: test input
+ "mach den skill deep-work-mode aus", # i18n-allow: test input
+ "lösch den skill abendroutine", # i18n-allow: test input
+ "starte den skill den du gestern erstellt hast", # i18n-allow: test input
+ "run the skill I created yesterday",
+ # questions about skills
+ "welche skills habe ich", # i18n-allow: test input
+ "wie erstelle ich einen skill", # i18n-allow: test input
+ "was ist ein skill", # i18n-allow: test input
+ "how do I create a skill?",
+ # the skills only in a genitive / "of my" — a request ABOUT skills
+ "erstell mir eine übersicht meiner skills", # i18n-allow: test input
+ "erstell mir eine liste aller skills", # i18n-allow: test input
+ "make a list of my skills",
+ # no skill word at all — ordinary domain requests stay with their skills
+ "erstell mir eine mail an das team", # i18n-allow: test input
+ "spiel musik auf youtube music", # i18n-allow: test input
+ "schreib eine mail an das team", # i18n-allow: test input
+ "",
+ ],
+)
+def test_non_authoring_requests_are_ignored(utterance: str) -> None:
+ assert is_skill_authoring_request(utterance) is False
+
+
+# ---------------------------------------------------------------------------
+# Resolution
+# ---------------------------------------------------------------------------
+
+
+def test_resolves_to_the_active_skill_creator_with_trigger_grade_rights() -> None:
+ registry = _FakeRegistry(["plugin-youtube_music", AUTHORING_SKILL_NAME, "morning-routine"])
+ resolution = resolve_skill_authoring_request(LIVE_UTTERANCE, registry)
+ assert resolution is not None
+ assert resolution.skill is not None
+ assert resolution.skill.name == AUTHORING_SKILL_NAME
+ assert resolution.decision.band == BAND_FIRE
+ assert resolution.decision.source == SOURCE_TRIGGER
+ assert resolution.decision.top is not None
+ assert resolution.decision.top.skill_name == AUTHORING_SKILL_NAME
+
+
+def test_resolves_to_nobody_when_skill_creator_is_not_active() -> None:
+ """The protection does not depend on the builtin: a disabled skill-creator
+ still means NO other skill may capture, and the create-skill tool owns it."""
+ registry = _FakeRegistry(["plugin-youtube_music", "morning-routine"])
+ resolution = resolve_skill_authoring_request(LIVE_UTTERANCE, registry)
+ assert resolution is not None
+ assert resolution.skill is None
+ assert resolution.decision.band == BAND_NONE
+ assert resolution.decision.top is None
+
+
+def test_returns_none_for_a_non_authoring_request() -> None:
+ registry = _FakeRegistry([AUTHORING_SKILL_NAME])
+ assert resolve_skill_authoring_request("spiel musik auf youtube music", registry) is None # i18n-allow: test input
+
+
+def test_never_raises_on_a_broken_registry() -> None:
+ class _Broken:
+ def list_active(self): # noqa: ANN202
+ raise RuntimeError("boom")
+
+ resolution = resolve_skill_authoring_request(LIVE_UTTERANCE, _Broken())
+ assert resolution is not None
+ assert resolution.skill is None
+ assert resolve_skill_authoring_request(LIVE_UTTERANCE, None) is not None
diff --git a/tests/unit/skills/test_creator_service.py b/tests/unit/skills/test_creator_service.py
index 625c261cb9..3640a20f57 100644
--- a/tests/unit/skills/test_creator_service.py
+++ b/tests/unit/skills/test_creator_service.py
@@ -255,3 +255,155 @@ async def test_commit_persists_draft_to_registry(registry, skills_root) -> None:
assert fetched.state == SkillLifecycleState.DRAFT
on_disk = (skills_root / "committed-skill" / "SKILL.md").read_text(encoding="utf-8")
assert "state: draft" in on_disk
+
+
+# ----------------------------------------------------------------------
+# 2026-08-18 — voice authoring: brain ladder, live inventory, author()
+# ----------------------------------------------------------------------
+
+
+class _RecordingBrain(_FakeBrain):
+ """A fake brain that also keeps the request it was asked with."""
+
+ def __init__(self, text: str) -> None:
+ super().__init__(text)
+ self.requests: list = []
+
+ def complete(self, request): # noqa: ANN001
+ self.requests.append(request)
+ return super().complete(request)
+
+
+class _DeadBrain:
+ """A provider that is configured but cannot answer (no key)."""
+
+ def complete(self, request): # noqa: ANN001, ARG002
+ raise RuntimeError("No API key found")
+
+
+_ROUTINE_BRAIN_JSON = """{
+ "name": "Morgenroutine",
+ "description": "Reads mail, tickets and calendar in the morning, then plays a song.",
+ "category": "productivity",
+ "tags": ["morning", "routine"],
+ "triggers": [
+ {"type": "voice", "pattern": "(morgenroutine|morning routine)", "language": ["de", "en"]},
+ {"type": "voice", "pattern": ".*"},
+ {"type": "voice", "pattern": "(unclosed"},
+ {"type": "schedule", "cron": "not a cron"}
+ ],
+ "requires_tools": ["gmail", "made_up_tool"],
+ "risk_policy": {"default_tier": "monitor"},
+ "body": "Short morning briefing.\\n\\n## Steps\\n\\n1. gmail: unread mail.\\n2. youtube_music: an 80s classic.\\n",
+ "assumptions": ["Lenya Tickets = Linear"]
+}"""
+
+
+async def test_brain_ladder_crosses_a_dead_active_provider(registry, monkeypatch) -> None:
+ """The user's active provider is tried first (AP-21) — and when it cannot
+ answer (no key), the ladder crosses to the Tool Model instead of handing
+ the user a skeleton (AP-22)."""
+ from types import SimpleNamespace
+
+ from jarvis.brain import resolver as resolver_mod
+
+ dead = _DeadBrain()
+ bm = _FakeBrainManager(dead, name="openrouter")
+ tool_model = _RecordingBrain(_GOOD_BRAIN_JSON)
+ tool_model.name = "vertex"
+ monkeypatch.setattr(resolver_mod, "resolve_tool_model_brain", lambda cfg, bus=None: tool_model)
+ monkeypatch.setattr(resolver_mod, "resolve_quality_brain", lambda cfg, bus=None: None)
+ monkeypatch.setattr(resolver_mod, "resolve_frontier_brain", lambda cfg, bus=None: None)
+
+ svc = SkillCreatorService(brain=bm, registry=registry, config=SimpleNamespace())
+ result = await svc.draft(SkillCreatorInput(intent="something"))
+ assert bm.requested == ["openrouter"] # the active provider was tried first
+ assert result.brain_used is True
+ assert result.brain_source.startswith("tool_model")
+ assert result.draft["name"] == "Brain Made Skill"
+
+
+async def test_prompt_carries_the_live_inventory_and_the_skill_contract(registry) -> None:
+ """What makes the draft a WORKING skill: the model sees which connectors
+ are attached (by name) and the trigger/schedule contract."""
+ from jarvis.skills.creator_service import AuthoringContext
+
+ brain = _RecordingBrain(_GOOD_BRAIN_JSON)
+ ctx = AuthoringContext(
+ tools=(("gmail", "Read and send Gmail."), ("youtube_music", "Play music.")),
+ skills=(("morning-routine", "Morning briefing."),),
+ )
+ svc = SkillCreatorService(brain=brain, registry=registry, context=ctx)
+ await svc.draft(
+ SkillCreatorInput(intent="jeden morgen um 6 mails vorlesen", schedule_hint="0 6 * * *", language="de") # i18n-allow: test input
+ )
+ request = brain.requests[0]
+ user = request.messages[0].content
+ assert "AVAILABLE TOOLS" in user
+ assert "gmail" in user and "youtube_music" in user
+ assert "INSTALLED SKILLS" in user and "morning-routine" in user
+ assert "Schedule hint: 0 6 * * *" in user
+ assert "language: de" in user
+ assert "cron" in request.system and "schedule" in request.system
+ assert "AVAILABLE TOOLS" in request.system
+
+
+async def test_brain_draft_is_normalised_triggers_and_tools(registry) -> None:
+ """Overbroad / invalid voice patterns and invalid crons are dropped, the
+ caller's cron hint is added when the model forgot it, and requires_tools is
+ filtered to connectors that exist."""
+ from jarvis.skills.creator_service import AuthoringContext
+
+ ctx = AuthoringContext(tools=(("gmail", ""), ("youtube_music", "")))
+ svc = SkillCreatorService(brain=_FakeBrain(_ROUTINE_BRAIN_JSON), registry=registry, context=ctx)
+ result = await svc.draft(SkillCreatorInput(intent="x", schedule_hint="0 6 * * *"))
+ assert result.brain_used is True
+ triggers = result.draft["triggers"]
+ voice = [t["pattern"] for t in triggers if t["type"] == "voice"]
+ crons = [t["cron"] for t in triggers if t["type"] == "schedule"]
+ assert voice == ["(morgenroutine|morning routine)"]
+ assert crons == ["0 6 * * *"]
+ assert result.draft["requires_tools"] == ["gmail"]
+ assert result.validation["ok"] is True
+
+
+async def test_author_commits_the_brain_draft_as_a_draft_skill(registry, skills_root) -> None:
+ svc = SkillCreatorService(
+ brain=_FakeBrain(_ROUTINE_BRAIN_JSON), registry=registry, user_skills_root=skills_root
+ )
+ authored = await svc.author(SkillCreatorInput(intent="morgenroutine", schedule_hint="0 6 * * *")) # i18n-allow: test input
+ assert authored.name == "Morgenroutine"
+ assert authored.slug == "morgenroutine"
+ assert authored.skill.state == SkillLifecycleState.DRAFT # AP-15
+ on_disk = (skills_root / "morgenroutine" / "SKILL.md").read_text(encoding="utf-8")
+ assert "state: draft" in on_disk
+ assert "cron: 0 6 * * *" in on_disk
+ assert "youtube_music" in on_disk
+
+
+async def test_author_refuses_to_commit_a_skeleton(registry, skills_root) -> None:
+ """No brain → no skill. The skeleton is the user's sentence pasted into a
+ template; on the voice path nobody edits it, so nothing must be written."""
+ from jarvis.skills.creator_service import SkillCreatorUnavailable
+
+ svc = SkillCreatorService(brain=None, registry=registry, user_skills_root=skills_root)
+ with pytest.raises(SkillCreatorUnavailable):
+ await svc.author(SkillCreatorInput(intent="pause spotify when I talk"))
+ assert not any(skills_root.iterdir())
+
+
+async def test_author_suffixes_the_name_on_a_collision(registry, skills_root) -> None:
+ svc = SkillCreatorService(
+ brain=_FakeBrain(_ROUTINE_BRAIN_JSON), registry=registry, user_skills_root=skills_root
+ )
+ first = await svc.author(SkillCreatorInput(intent="a"))
+ second = await svc.author(SkillCreatorInput(intent="a"))
+ assert first.name == "Morgenroutine"
+ assert second.name == "Morgenroutine 2"
+ assert (skills_root / "morgenroutine-2" / "SKILL.md").exists()
diff --git a/tests/unit/ui/web/test_skills_routes.py b/tests/unit/ui/web/test_skills_routes.py
index 158b5040e1..6c29b78725 100644
--- a/tests/unit/ui/web/test_skills_routes.py
+++ b/tests/unit/ui/web/test_skills_routes.py
@@ -308,6 +308,61 @@ def test_creator_commit_persists_reviewed_draft(skills_root: Path) -> None:
assert "Committed Via Route" in names
+def test_creator_author_refuses_without_brain_and_writes_nothing(skills_root: Path) -> None:
+ """One-shot authoring (voice / CLI parity) is brain-REQUIRED: with no brain
+ on app.state it answers 503 and no skeleton lands on disk — a template
+ with the sentence pasted in is not the skill the user asked for."""
+ client, _reg = _client(skills_root)
+ res = client.post(
+ "/api/skills/creator/author",
+ json={"intent": "jeden morgen um 6 meine mails vorlesen", "schedule_hint": "0 6 * * *"}, # i18n-allow: test input
+ )
+ assert res.status_code == 503, res.text
+ assert not any(skills_root.iterdir())
+
+
+def test_creator_author_writes_a_draft_skill_with_a_brain(skills_root: Path) -> None:
+ from jarvis.core.protocols import BrainDelta
+
+ class _Brain:
+ def complete(self, request): # noqa: ANN001, ANN202
+ async def _gen():
+ yield BrainDelta(
+ content=(
+ '{"name": "Mail Morgen", "description": "Liest morgens Mails vor.", '
+ '"category": "productivity", "tags": ["mail"], '
+ '"triggers": [{"type": "voice", "pattern": "(mail morgen)"}], '
+ '"requires_tools": [], "risk_policy": {"default_tier": "monitor"}, '
+ '"body": "Morgens Mails.\\n\\n## Schritte\\n\\n1. gmail: ungelesene Mails nennen.\\n"}'
+ ),
+ finish_reason="stop",
+ )
+
+ return _gen()
+
+ from jarvis.ui.web.skills_routes import router
+
+ reg = SkillRegistry(skills_root, bus=None, state_prefs_loader=prefs.load_state_overrides)
+ reg.reload_sync()
+ app = FastAPI()
+ app.state.skill_registry = reg
+ app.state.brain = _Brain()
+ app.include_router(router)
+ client = TestClient(app)
+ res = client.post(
+ "/api/skills/creator/author",
+ json={"intent": "jeden morgen mails vorlesen", "schedule_hint": "0 6 * * *"}, # i18n-allow: test input
+ )
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["brain_used"] is True
+ assert body["skill"]["name"] == "Mail Morgen"
+ assert body["skill"]["state"] == "draft" # AP-15
+ crons = [t["cron"] for t in body["draft"]["triggers"] if t["type"] == "schedule"]
+ assert crons == ["0 6 * * *"]
+ assert (skills_root / "mail-morgen" / "SKILL.md").exists()
+
+
def test_link_health_returns_clean_501_when_module_absent(skills_root: Path) -> None:
_make_skill(skills_root, "alpha")
client, _reg = _client(skills_root)