Compare commits

..
2 Commits
19 changed files with 1909 additions and 29 deletions

No files matched your search

+1
View File
@@ -7,6 +7,7 @@ __pycache__/
data/decisions.jsonl data/decisions.jsonl
data/runs.jsonl data/runs.jsonl
data/categories.json data/categories.json
data/deleted_skills.json
data/skills/ data/skills/
data/drafts/ data/drafts/
.pytest_cache/ .pytest_cache/
+61 -5
View File
@@ -88,10 +88,15 @@ scheduler.py no up-front gate: every input is dispatched
time (all front ends defer via the question queue, `answer_timeout` time (all front ends defer via the question queue, `answer_timeout`
per question); a per question); a
failed real run triggers a logged SemIf repair choice failed real run triggers a logged SemIf repair choice
(retry/repair_skill/ask_user/no_repair) surfaced to the user (retry/repair_skill/ask_user/no_repair) surfaced to the user;
housekeeping meta skills (delete/clear-config/regen/cancel-build)
operate on the tree via `ctx.admin`; per-category new-skill locks
(`locks.new_skill` in the category config) gate creation, with
`housekeeping`/`response` hard-locked in code
queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0 queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0
skills.py tree + registry (hardcoded built-ins: the closed `response` canned skills.py tree + registry (hardcoded built-ins: the closed `response` canned
tree only), navigation = SemIf choices per level (logged; tree plus the `housekeeping` meta skills), navigation = SemIf
choices per level (logged;
the actionability guard runs first, at the top of navigation, the actionability guard runs first, at the top of navigation,
to arbitrate the response/create boundary), create_category to arbitrate the response/create boundary), create_category
and create_skill author + register stubs via the small `llm` and create_skill author + register stubs via the small `llm`
@@ -108,7 +113,13 @@ skills.py tree + registry (hardcoded built-ins: the closed `response` canned
mirror); mirror);
resolve_skill_config / unresolved_variables drive the tiered resolve_skill_config / unresolved_variables drive the tiered
config merge (global -> category -> skill) + pre-act config merge (global -> category -> skill) + pre-act
contract collection contract collection; Skill.origin records builtin/seed/generated;
DeletedSkills (data/deleted_skills.json) tombstones a deleted
skill so a seed does not reappear on restart; resolve_skill_ref
parses a free-form request for a category.skill or bare name;
parse_meta_command recognizes explicit housekeeping commands and
the meta skills resolve or ask for their target as an input
variable
skill.py loop: observe -> act -> observe -> assess; the body is a single skill.py loop: observe -> act -> observe -> assess; the body is a single
act(ctx, request) phase that returns ActionResult (its own act(ctx, request) phase that returns ActionResult (its own
SemIf sub-decisions ride on ActionResult.decisions and are SemIf sub-decisions ride on ActionResult.decisions and are
@@ -117,7 +128,9 @@ skill.py loop: observe -> act -> observe -> assess; the body is a single
tau; on failure `assess:requeue` complete/retry) and the run tau; on failure `assess:requeue` complete/retry) and the run
summary is deterministic (no generation), built from summary is deterministic (no generation), built from
category.skill + ok/failed + action_log; the assess state carries category.skill + ok/failed + action_log; the assess state carries
the resolved inputs (secrets redacted); the resolved inputs (secrets redacted); a `DETERMINISTIC_CATEGORIES`
run (housekeeping) skips assessment/repair — it is an internal
mechanical action with a known result, not an external run;
a run paused for input is resumed by re-invoking act with the a run paused for input is resumed by re-invoking act with the
answer on request.user_input; a answer on request.user_input; a
contract variable the runner cannot satisfy pauses BEFORE contract variable the runner cannot satisfy pauses BEFORE
@@ -388,6 +401,40 @@ CLI, unit tests (24) + integration tests (2).
`creation_approval_requested` / `_approved` / `_denied` / `_timeout` / `creation_approval_requested` / `_approved` / `_denied` / `_timeout` /
`_skipped`; it is a human veto, not a decision row — the SemIf create doors `_skipped`; it is a human veto, not a decision row — the SemIf create doors
still make and log the routing decision. still make and log the routing decision.
- **Housekeeping meta skills + per-category new-skill locks** (Oct 2026): a
built-in `housekeeping` category of four meta skills that act on the agent's
own tree through `ctx.admin` (the scheduler): `delete_skill` (confirm, then
remove the leaf, registry entry, and folder; durable via a
`data/deleted_skills.json` tombstone so a deleted seed does not reappear),
`clear_config` (empty the skill's recorded config), `regen_skill` (ask
**"What needs to be fixed?"** then rewrite the body through the corrective
path with `reason_kind="manual"`), and `cancel_build` (confirm, then discard a
queued/in-flight write and delete the half-built leaf). The target skill is an
**input variable**: the skill resolves it from the request if named
("delete skill calendar.foo") and otherwise **asks** for it ("delete skill" →
"Which skill?"), so the routed request never has to carry a task-like skill
name. Explicit command forms ("delete skill", "clear config variables for X",
"regen skill X", "cancel skill build") are recognized deterministically by
`parse_meta_command` and routed straight to the housekeeping leaf (trace
`meta_command`): the pinned 4B decision model reads a task-like name
(`calendar.create_event`) as the task itself and misroutes the generic guards,
so the explicit command is deterministic while natural-language phrasings
still go through navigation (the actionability guard's `action` option now
names skill-management commands). They are built-ins
(`Skill.origin == "builtin"`) reachable by natural language and, for operators,
by slash-prefixed REPL commands (`/delete`, `/clear-config`, `/regen`,
`/cancel-build`, `/lock`) and dashboard endpoints/buttons. Their runs are
deterministic internal actions: `DETERMINISTIC_CATEGORIES` skips
`assess:outcome`/repair, and the category is hard-locked from authoring. Every
category carries a **new-skill lock** in its category config
(`data/skills/<category>/config.json` → `{"locks": {"new_skill": bool}}`); the
lock is a deterministic boolean gate (`Scheduler._category_locked`) checked in
`_dispatch`, `_dispatch_skill`, `_author_skill`, and `restart_skill`, and
toggled from the config file or `Scheduler.set_category_lock` (`/lock`,
`/api/lock`). `housekeeping` and the closed `response` tree are hard-locked in
code (`HARD_LOCKED_CATEGORIES`/`CANNED_CATEGORIES`) and can never be unlocked.
The lock is creation-only: existing skills still run and repair/regen of an
existing leaf is allowed.
- **Real integrations, implementation questions, fidelity + repair** (Sep 2026): - **Real integrations, implementation questions, fidelity + repair** (Sep 2026):
elicitation is on by default and asks implementation questions (which elicitation is on by default and asks implementation questions (which
service/account, how to connect, where the credential comes from, what success service/account, how to connect, where the credential comes from, what success
@@ -961,6 +1008,12 @@ CLI, unit tests (24) + integration tests (2).
wake word, so answering a question is conversational. `max_speak_chars` wake word, so answering a question is conversational. `max_speak_chars`
truncates long replies before speaking, and a short sine `cue` beep plays on truncates long replies before speaking, and a short sine `cue` beep plays on
wake (optionally again on transcription) so the user knows they were heard. wake (optionally again on transcription) so the user knows they were heard.
**Result-only output**: `VoiceAdapter.result_only` (default true; per-platform
config `result_only` overrides) makes `GatewayService` speak just the skill's
result line — queue/urgency chatter is dropped and the `<skill>: ok —` wrapper
is stripped — so the spoken output is the answer, not the scheduler's
internals. Questions, repair offers, approvals, and timer notifications are
still spoken.
Every heavy dep Every heavy dep
(`sounddevice`/`openwakeword`/`faster_whisper`/`piper`/`onnxruntime`) is (`sounddevice`/`openwakeword`/`faster_whisper`/`piper`/`onnxruntime`) is
**lazy-imported**; `check_requirements()` returns an install hint and the **lazy-imported**; `check_requirements()` returns an install hint and the
@@ -1176,7 +1229,10 @@ The bridge read path (`simplex.next_message`) and contact-link lookup
Includes the dashboard API tests (`tests/test_dashboard_api.py`), which spin Includes the dashboard API tests (`tests/test_dashboard_api.py`), which spin
up the stdlib HTTP server on an ephemeral port with the engine never loaded; up the stdlib HTTP server on an ephemeral port with the engine never loaded;
`tests/test_codegen.py` for prompt/parse/validate, integration `tests/test_codegen.py` for prompt/parse/validate, integration
extraction/findings, and body store round-trips; and `tests/test_llm.py` for extraction/findings, and body store round-trips; `tests/test_housekeeping.py`
for the housekeeping operations (name resolution, store/registry deletion,
tombstones, the lock gate, cancel/regen, and the meta-skill act flows); and
`tests/test_llm.py` for
the `_parse_json` helper and the LLMClient provider. `tests/conftest.py``s `ScriptedEngine` the `_parse_json` helper and the LLMClient provider. `tests/conftest.py``s `ScriptedEngine`
drives scheduling mechanics (assessment is now a SemIf decision) without a drives scheduling mechanics (assessment is now a SemIf decision) without a
GGUF. GGUF.
+6 -2
View File
@@ -667,8 +667,12 @@ python -m semif_agent.cli gateway --platform voice
transcribed. After a reply, the next transcribed. After a reply, the next
utterance is accepted **without** the wake word for `follow_up_window_s`, so utterance is accepted **without** the wake word for `follow_up_window_s`, so
answering a question is conversational. `max_speak_chars` truncates long answering a question is conversational. `max_speak_chars` truncates long
replies before speaking. There is no allowlist: the mic is local, so physical replies before speaking. `result_only` (default true for voice) speaks only the
access is the authorization. skill's result line — queue/urgency bookkeeping is dropped and the
`<skill>: ok —` wrapper is stripped — so the spoken output is the answer, not
the scheduler's internals; set it false to speak the full scheduler output.
There is no allowlist: the mic is local, so physical access is the
authorization.
- **Run mode.** Foreground, in the user's audio session — a headless systemd - **Run mode.** Foreground, in the user's audio session — a headless systemd
user service does not share the user's audio session, so voice is not rendered user service does not share the user's audio session, so voice is not rendered
as a unit. as a unit.
+2 -1
View File
@@ -160,12 +160,13 @@
"text_batch_delay": 0.8 "text_batch_delay": 0.8
}, },
"voice": { "voice": {
"_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.", "_comment": "Voice command adapter: a local microphone front end with wake word + speech-to-text + text-to-speech. Requires the optional voice stack (requirements/voice.txt; sounddevice + openwakeword + faster-whisper + piper-tts + onnxruntime; the system needs libportaudio2). Lazy-imported; the gateway refuses to start with an install hint. Runs best in the user's audio session (foreground `gateway --platform voice`), not a headless systemd user service. Audio is 16 kHz mono int16; capture/playback run at the device's native rate and are resampled to/from 16 kHz (capture_sample_rate/output_sample_rate override it; 0 = the device default). wake.model is an openWakeWord model name or path (bootstrap downloads models into the venv, where they resolve by name; model_dir is an optional local dir for a custom model file); stt.model is a faster-whisper size/path (cached under .runtime/hf); tts.voice is a Piper voice id or path (bootstrap downloads it under .runtime/voice/tts). After each reply the next utterance is accepted without the wake word for follow_up_window_s. result_only speaks just the skill's result line (dropping queue/urgency bookkeeping and the `<skill>: ok —` wrapper) instead of the full scheduler output; set false for the complete text. max_speak_chars truncates long replies before speaking. chat_id identifies the single local session; home_channel defaults to it so timers/repair offers are spoken too.",
"enabled": false, "enabled": false,
"chat_id": "voice", "chat_id": "voice",
"display_name": "voice", "display_name": "voice",
"home_channel": "voice", "home_channel": "voice",
"reply_prefix": "", "reply_prefix": "",
"result_only": true,
"max_speak_chars": 600, "max_speak_chars": 600,
"follow_up_window_s": 5.0, "follow_up_window_s": 5.0,
"cue": { "cue": {
+57 -1
View File
@@ -38,11 +38,19 @@ from .trace import TraceLog
REPO_ROOT = Path(__file__).resolve().parent.parent REPO_ROOT = Path(__file__).resolve().parent.parent
_PATH_KEYS = ("skill_seeds", "skill_bodies", "category_registry", "log", "trace") _PATH_KEYS = (
"skill_seeds",
"skill_bodies",
"category_registry",
"deleted_skills",
"log",
"trace",
)
_PATH_DEFAULTS = { _PATH_DEFAULTS = {
"skill_seeds": "seeds", "skill_seeds": "seeds",
"skill_bodies": "data/skills", "skill_bodies": "data/skills",
"category_registry": "data/categories.json", "category_registry": "data/categories.json",
"deleted_skills": "data/deleted_skills.json",
"log": "data/decisions.jsonl", "log": "data/decisions.jsonl",
"trace": "data/runs.jsonl", "trace": "data/runs.jsonl",
} }
@@ -446,6 +454,12 @@ def repl(scheduler: Scheduler, config: dict) -> int:
"relabel <id> <outcome> | restart <category> <skill> | " "relabel <id> <outcome> | restart <category> <skill> | "
"repairs | repair <offer-id> [action] | approvals | quit" "repairs | repair <offer-id> [action] | approvals | quit"
) )
print(
"housekeeping (slash-prefixed so plain requests still route by SemIf): "
"/delete <category> <skill> | /clear-config <category> <skill> | "
"/regen <category> <skill> | /cancel-build <category> <skill> | "
"/lock <category> on|off"
)
while True: while True:
_answer_questions(scheduler) _answer_questions(scheduler)
_answer_approvals(scheduler) _answer_approvals(scheduler)
@@ -504,6 +518,48 @@ def repl(scheduler: Scheduler, config: dict) -> int:
status, detail = scheduler.restart_skill(parts[1], parts[2]) status, detail = scheduler.restart_skill(parts[1], parts[2])
print(f"[{status}] {detail}") print(f"[{status}] {detail}")
continue continue
if lower.startswith("/delete "):
parts = line.lstrip("/").split()
if len(parts) != 3:
print("usage: /delete <category> <skill>")
continue
status, detail = scheduler.delete_skill(parts[1], parts[2])
print(f"[{status}] {detail}")
continue
if lower.startswith("/clear-config "):
parts = line.lstrip("/").split()
if len(parts) != 3:
print("usage: /clear-config <category> <skill>")
continue
status, detail = scheduler.clear_skill_config(parts[1], parts[2])
print(f"[{status}] {detail}")
continue
if lower.startswith("/regen "):
parts = line.lstrip("/").split()
if len(parts) != 3:
print("usage: /regen <category> <skill>")
continue
status, detail = scheduler.regen_skill(parts[1], parts[2])
print(f"[{status}] {detail}")
continue
if lower.startswith("/cancel-build "):
parts = line.lstrip("/").split()
if len(parts) != 3:
print("usage: /cancel-build <category> <skill>")
continue
status, detail = scheduler.cancel_skill_build(parts[1], parts[2])
print(f"[{status}] {detail}")
continue
if lower.startswith("/lock "):
parts = line.lstrip("/").split()
if len(parts) != 3 or parts[2].lower() not in ("on", "off"):
print("usage: /lock <category> on|off")
continue
status, detail = scheduler.set_category_lock(
parts[1], parts[2].lower() == "on"
)
print(f"[{status}] {detail}")
continue
if lower == "idle": if lower == "idle":
scheduler.idle() scheduler.idle()
print("current process cleared.") print("current process cleared.")
+43 -1
View File
@@ -143,13 +143,15 @@ def build_tree_payload(scheduler: Scheduler) -> dict:
"name": skill.name, "name": skill.name,
"description": skill.description, "description": skill.description,
"status": skill.status, "status": skill.status,
"origin": skill.origin,
"integration": skill.integration or None, "integration": skill.integration or None,
"integration_source": skill.integration_source, "integration_source": skill.integration_source,
} }
for skill in skills for skill in skills
] ]
for category, skills in sorted(snapshot.items()) for category, skills in sorted(snapshot.items())
} },
"locks": scheduler.category_locks(),
} }
@@ -233,6 +235,9 @@ class DashboardHandler(BaseHTTPRequestHandler):
if path == "/api/approvals": if path == "/api/approvals":
self._send(200, {"approvals": self.scheduler.pending_approvals()}) self._send(200, {"approvals": self.scheduler.pending_approvals()})
return return
if path == "/api/locks":
self._send(200, {"locks": self.scheduler.category_locks()})
return
if path == "/api/timers": if path == "/api/timers":
self._send( self._send(
200, 200,
@@ -328,8 +333,45 @@ class DashboardHandler(BaseHTTPRequestHandler):
return return
self._send(200, {"status": status, "detail": detail}) self._send(200, {"status": status, "detail": detail})
return return
if path == "/api/delete":
self._housekeeping("delete_skill")
return
if path == "/api/clear-config":
self._housekeeping("clear_skill_config")
return
if path == "/api/regen":
self._housekeeping("regen_skill")
return
if path == "/api/cancel-build":
self._housekeeping("cancel_skill_build")
return
if path == "/api/lock":
with self.lock:
try:
body = self._read_json()
status, detail = self.scheduler.set_category_lock(
str(body.get("category", "")), bool(body.get("locked"))
)
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail})
return
self._send_error(404, "no such endpoint") self._send_error(404, "no such endpoint")
def _housekeeping(self, method: str):
"""Run a housekeeping operation by category + skill (dashboard action)."""
with self.lock:
try:
body = self._read_json()
status, detail = getattr(self.scheduler, method)(
str(body.get("category", "")), str(body.get("skill", ""))
)
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail})
def log_message(self, format, *args): def log_message(self, format, *args):
pass pass
+6
View File
@@ -51,6 +51,12 @@ class GatewayAdapter(ABC):
#: short platform name used in request sources (`"simplex:<chat_id>"`) #: short platform name used in request sources (`"simplex:<chat_id>"`)
name: str = "gateway" name: str = "gateway"
#: Spoken front ends (the voice gateway) set this so the service speaks only
#: the skill's result line, not the scheduler's bookkeeping (queue/urgency
#: status) and not the `<skill>: ok —` wrapper. A per-platform config
#: `result_only` overrides it. Plain chat adapters leave it False.
result_only: bool = False
@abstractmethod @abstractmethod
def check_requirements(self) -> tuple[bool, str | None]: def check_requirements(self) -> tuple[bool, str | None]:
"""Return `(ok, install_hint)`. Must never raise on a missing dep.""" """Return `(ok, install_hint)`. Must never raise on a missing dep."""
+59 -8
View File
@@ -29,6 +29,11 @@ from .base import InboundMessage, OutboundMessage
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*") _LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
#: The scheduler's run summary wraps the real result as
#: `"<skill>: <ok|failed> — <detail>"`. A result-only platform (the voice
#: gateway) speaks just `<detail>`.
_RESULT_SEP = " — "
_REPAIR_ACTIONS = { _REPAIR_ACTIONS = {
"retry": "retry", "retry": "retry",
"repair": "repair_skill", "repair": "repair_skill",
@@ -64,6 +69,28 @@ def _leading_run_id(text: str) -> str:
return match.group(0)[1:-2] if match else "" return match.group(0)[1:-2] if match else ""
def _result_detail(text: str) -> str:
"""Unwrap the scheduler's `"<skill>: <ok|failed> — <detail>"` summary.
Returns the detail the skill actually produced. A line with no wrapper is
returned unchanged.
"""
if _RESULT_SEP in text:
return text.split(_RESULT_SEP, 1)[1].strip()
return text
def _reply_kind(status: str) -> str:
"""Classify a scheduler outcome for a result-only front end."""
if status in ("running", "preempted", "ran"):
return "result"
if status == "needs_input":
return "question"
if status == "queued":
return "status"
return "notice"
def _normalize_adapters(adapters) -> dict: def _normalize_adapters(adapters) -> dict:
"""Accept a single adapter or a list/dict of them, keyed by platform name.""" """Accept a single adapter or a list/dict of them, keyed by platform name."""
if isinstance(adapters, dict): if isinstance(adapters, dict):
@@ -127,6 +154,17 @@ class GatewayService:
def _home_channel(self, platform: str) -> str: def _home_channel(self, platform: str) -> str:
return str(self._platform_cfg.get(platform, {}).get("home_channel", "") or "") return str(self._platform_cfg.get(platform, {}).get("home_channel", "") or "")
def _result_only(self, platform: str) -> bool:
"""Whether this platform speaks only the skill result line.
The adapter declares the default (the voice adapter sets `result_only`);
a per-platform config `result_only` overrides it either way.
"""
cfg = self._platform_cfg.get(platform, {})
if "result_only" in cfg:
return bool(cfg["result_only"])
return bool(getattr(self.adapters.get(platform), "result_only", False))
def _fallback_target(self) -> Target | None: def _fallback_target(self) -> Target | None:
for platform in self.platforms: for platform in self.platforms:
home = self._home_channel(platform) home = self._home_channel(platform)
@@ -184,29 +222,30 @@ class GatewayService:
status, detail = self.scheduler.answer(msg.text) status, detail = self.scheduler.answer(msg.text)
if self.scheduler.pending is None: if self.scheduler.pending is None:
self._pending_owner = None self._pending_owner = None
self._reply(*reply_to, detail) self._reply(*reply_to, detail, kind=_reply_kind(status))
elif pending is not None and self._pending_owner not in (None, reply_to): elif pending is not None and self._pending_owner not in (None, reply_to):
self._reply( self._reply(
*reply_to, *reply_to,
"I'm waiting for a reply in another conversation; please resend in a moment.", "I'm waiting for a reply in another conversation; please resend in a moment.",
kind="notice",
) )
elif reply_to in self._question_for_chat: elif reply_to in self._question_for_chat:
question_id = self._question_for_chat.pop(reply_to) question_id = self._question_for_chat.pop(reply_to)
status, detail = self.scheduler.answer_question(question_id, msg.text) status, detail = self.scheduler.answer_question(question_id, msg.text)
self._surfaced.add(question_id) self._surfaced.add(question_id)
self._reply(*reply_to, detail) self._reply(*reply_to, detail, kind="notice")
elif reply_to in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS: elif reply_to in self._repair_for_chat and msg.text.strip().lower() in _REPAIR_ACTIONS:
offer_id = self._repair_for_chat.pop(reply_to) offer_id = self._repair_for_chat.pop(reply_to)
action = _REPAIR_ACTIONS[msg.text.strip().lower()] action = _REPAIR_ACTIONS[msg.text.strip().lower()]
status, detail = self.scheduler.resolve_repair(offer_id, action) status, detail = self.scheduler.resolve_repair(offer_id, action)
self._surfaced.add(offer_id) self._surfaced.add(offer_id)
self._reply(*reply_to, detail) self._reply(*reply_to, detail, kind="notice")
elif reply_to in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS: elif reply_to in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS:
approval_id = self._approval_for_chat.pop(reply_to) approval_id = self._approval_for_chat.pop(reply_to)
approved = _APPROVAL_ACTIONS[msg.text.strip().lower()] approved = _APPROVAL_ACTIONS[msg.text.strip().lower()]
status, detail = self.scheduler.answer_approval(approval_id, approved) status, detail = self.scheduler.answer_approval(approval_id, approved)
self._surfaced.add(approval_id) self._surfaced.add(approval_id)
self._reply(*reply_to, detail) self._reply(*reply_to, detail, kind="notice")
else: else:
status, detail, run_id = self.scheduler.submit_request( status, detail, run_id = self.scheduler.submit_request(
msg.text, source=self.source_for(platform, msg.chat_id) msg.text, source=self.source_for(platform, msg.chat_id)
@@ -215,7 +254,7 @@ class GatewayService:
self._owners[run_id] = reply_to self._owners[run_id] = reply_to
if status == "needs_input": if status == "needs_input":
self._pending_owner = reply_to self._pending_owner = reply_to
self._reply(*reply_to, detail) self._reply(*reply_to, detail, kind=_reply_kind(status))
self.drain() self.drain()
self.surface(origin=reply_to) self.surface(origin=reply_to)
@@ -233,7 +272,7 @@ class GatewayService:
self._pending_owner = owner self._pending_owner = owner
target = owner or self._fallback_target() target = owner or self._fallback_target()
if target: if target:
self._reply(*target, text) self._reply(*target, text, kind=_reply_kind(status))
def surface(self, origin: Target | None = None) -> None: def surface(self, origin: Target | None = None) -> None:
"""Send any newly posted authoring questions / repair offers.""" """Send any newly posted authoring questions / repair offers."""
@@ -252,6 +291,7 @@ class GatewayService:
self._reply( self._reply(
*target, *target,
f"(authoring {item['category']}.{item['skill']}) {item['question']}", f"(authoring {item['category']}.{item['skill']}) {item['question']}",
kind="question",
) )
repairs = self.scheduler.pending_repairs() repairs = self.scheduler.pending_repairs()
@@ -272,6 +312,7 @@ class GatewayService:
f"{offer['category']}.{offer['skill']} failed: " f"{offer['category']}.{offer['skill']} failed: "
f"{offer['failure'][:200]}\nReply retry / repair / ask / no." f"{offer['failure'][:200]}\nReply retry / repair / ask / no."
), ),
kind="notice",
) )
approvals = self.scheduler.pending_approvals() approvals = self.scheduler.pending_approvals()
@@ -297,12 +338,13 @@ class GatewayService:
f"Approve creating new {item['kind']} {label}: " f"Approve creating new {item['kind']} {label}: "
f"{item['description']}\nReply yes / no." f"{item['description']}\nReply yes / no."
), ),
kind="notice",
) )
for fired in self.scheduler.timers.drain(): for fired in self.scheduler.timers.drain():
target = self._resolve_target(fired.run_id, origin) target = self._resolve_target(fired.run_id, origin)
if target: if target:
self._reply(*target, fired.message) self._reply(*target, fired.message, kind="notice")
# ---- scheduler requeue hook (called under the scheduler lock) ---- # ---- scheduler requeue hook (called under the scheduler lock) ----
@@ -333,8 +375,17 @@ class GatewayService:
# ---- outbound ---- # ---- outbound ----
def _reply(self, platform: str, chat_id: str, text: str) -> None: def _reply(
self, platform: str, chat_id: str, text: str, kind: str = "reply"
) -> None:
text = _strip_run_id(text) text = _strip_run_id(text)
if self._result_only(platform):
# A spoken front end says the skill's result, not the scheduler's
# bookkeeping: drop queue/urgency chatter and unwrap the result line.
if kind == "status":
return
if kind == "result":
text = _result_detail(text)
prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "") prefix = str(self._platform_cfg.get(platform, {}).get("reply_prefix", "") or "")
if prefix: if prefix:
text = f"{prefix}{text}" text = f"{prefix}{text}"
+4
View File
@@ -30,6 +30,10 @@ from .base import GatewayAdapter, InboundMessage, OutboundMessage
class VoiceAdapter(GatewayAdapter): class VoiceAdapter(GatewayAdapter):
name = "voice" name = "voice"
#: Speak the skill's result line only — the spoken front end should not read
#: out queue/urgency bookkeeping or the `<skill>: ok —` wrapper. Override
#: with `gateway.voice.result_only: false` for the full scheduler output.
result_only = True
def __init__(self, cfg: dict | None = None, trace=None): def __init__(self, cfg: dict | None = None, trace=None):
cfg = cfg or {} cfg = cfg or {}
+383 -5
View File
@@ -15,6 +15,7 @@ import time
import uuid import uuid
from collections import deque from collections import deque
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable from typing import Callable
from .codegen import ( from .codegen import (
@@ -40,13 +41,19 @@ from .skill import SkillRunner
from .timers import TimerService from .timers import TimerService
from .skills import ( from .skills import (
CANNED_CATEGORIES, CANNED_CATEGORIES,
DETERMINISTIC_CATEGORIES,
HARD_LOCKED_CATEGORIES,
HOUSEKEEPING_CATEGORY,
ActionContext, ActionContext,
CategoryRegistry, CategoryRegistry,
CreateCategory, CreateCategory,
CreateSkill, CreateSkill,
DeletedSkills,
Skill, Skill,
SkillDraft, SkillDraft,
SkillStore, SkillStore,
apply_tombstones,
build_housekeeping_skills,
build_skills, build_skills,
build_tree, build_tree,
confirm_skill_fit, confirm_skill_fit,
@@ -57,6 +64,7 @@ from .skills import (
merge_seed_store, merge_seed_store,
merge_skill_store, merge_skill_store,
navigate, navigate,
parse_meta_command,
) )
from .trace import TraceLog from .trace import TraceLog
@@ -101,6 +109,9 @@ class SkillWrite:
draft: SkillDraft draft: SkillDraft
weight: float weight: float
repair_evidence: dict | None = None repair_evidence: dict | None = None
# Label for a corrective rewrite: "run_failure" (repair loop), "fidelity",
# "test", or "manual" (a user-requested regen).
reason_kind: str = "run_failure"
@dataclass @dataclass
@@ -255,16 +266,27 @@ class Scheduler:
max_size=int(config.get("queue", {}).get("max_size", 100)), max_size=int(config.get("queue", {}).get("max_size", 100)),
age_rate=float(config.get("queue", {}).get("age_rate", 0.0)), age_rate=float(config.get("queue", {}).get("age_rate", 0.0)),
) )
self.skills = build_skills(config) self.skills = build_skills(config) + build_housekeeping_skills()
self.tree = build_tree(self.skills) self.tree = build_tree(self.skills)
self.registry = CategoryRegistry(config.get("category_registry", "data/categories.json")) registry_path = config.get("category_registry", "data/categories.json")
self.registry = CategoryRegistry(registry_path)
self.body_store = SkillStore(config.get("skill_bodies", "data/skills")) self.body_store = SkillStore(config.get("skill_bodies", "data/skills"))
self.seed_store = SkillStore(config.get("skill_seeds", "seeds")) self.seed_store = SkillStore(config.get("skill_seeds", "seeds"))
# Deletions are durable: a tombstone suppresses a seed (or a generated
# body of the same name) on every future load. Derived from the registry
# path when not configured, so a test store is self-contained.
deleted_path = config.get("deleted_skills") or str(
Path(registry_path).parent / "deleted_skills.json"
)
self.deleted = DeletedSkills(deleted_path)
merge_registry(self.tree, self.registry.read()) merge_registry(self.tree, self.registry.read())
merge_seed_store(self.tree, self.seed_store, self.body_store) merge_seed_store(self.tree, self.seed_store, self.body_store)
merge_skill_store(self.tree, self.body_store, self.registry.read()) merge_skill_store(self.tree, self.body_store, self.registry.read())
apply_tombstones(self.tree, self.deleted)
self.timers = TimerService(trace=self.trace) self.timers = TimerService(trace=self.trace)
self.ctx = ActionContext(engine=self.engine, config=config, timers=self.timers) self.ctx = ActionContext(
engine=self.engine, config=config, timers=self.timers, admin=self
)
self.runner = SkillRunner( self.runner = SkillRunner(
self.ctx, self.log, store=self.body_store, tau=self.tau self.ctx, self.log, store=self.body_store, tau=self.tau
) )
@@ -276,6 +298,9 @@ class Scheduler:
self._draft_notify = threading.Condition(self._lock) self._draft_notify = threading.Condition(self._lock)
self._draft_thread: threading.Thread | None = None self._draft_thread: threading.Thread | None = None
self._writes: deque[SkillWrite] = deque() self._writes: deque[SkillWrite] = deque()
# Body writes cancelled while queued or in flight: the worker discards
# their output instead of materializing the leaf.
self._cancelled: set[tuple[str, str]] = set()
self._write_notify = threading.Condition(self._lock) self._write_notify = threading.Condition(self._lock)
self._write_thread: threading.Thread | None = None self._write_thread: threading.Thread | None = None
self._question_notify = threading.Condition(self._lock) self._question_notify = threading.Condition(self._lock)
@@ -454,6 +479,25 @@ class Scheduler:
# ---- dispatch ---- # ---- dispatch ----
def _dispatch(self, request: Request, weight: float = 0.0) -> DispatchResult: def _dispatch(self, request: Request, weight: float = 0.0) -> DispatchResult:
# Explicit housekeeping commands are deterministic: they route straight
# to the meta skill, bypassing the generic guards (which misread a
# task-like skill name as the task). Natural-language phrasings still go
# through navigation below.
meta = parse_meta_command(request.text)
if meta is not None:
leaf = next(
(
s
for s in self.tree.get(HOUSEKEEPING_CATEGORY, [])
if s.name == meta
),
None,
)
if leaf is not None:
self.trace.append(
"meta_command", request.id, action=meta, text=request.text
)
return self._run_skill(leaf, request)
navigation = navigate( navigation = navigate(
self.engine, self.engine,
self.log, self.log,
@@ -469,6 +513,12 @@ class Scheduler:
return self._dispatch_skill(request, navigation.category, weight) return self._dispatch_skill(request, navigation.category, weight)
if navigation.category in CANNED_CATEGORIES: if navigation.category in CANNED_CATEGORIES:
return self._run_skill(navigation, request) return self._run_skill(navigation, request)
if navigation.category in HARD_LOCKED_CATEGORIES:
# A hard-locked built-in category can never author a leaf, so the
# reuse-vs-create intent guard has nothing to decide: run the
# navigation's pick directly (the meta skill asks for any missing
# target as an input variable).
return self._run_skill(navigation, request)
if not confirm_skill_fit( if not confirm_skill_fit(
self.engine, self.log, self.trace, request, navigation, self.intent_tau self.engine, self.log, self.trace, request, navigation, self.intent_tau
): ):
@@ -478,6 +528,8 @@ class Scheduler:
selected_skill=f"{navigation.category}.{navigation.name}", selected_skill=f"{navigation.category}.{navigation.name}",
chosen="create_skill", chosen="create_skill",
) )
if self._category_locked(navigation.category):
return self._blocked_create(request, navigation.category)
return self._dispatch_skill(request, navigation.category, weight) return self._dispatch_skill(request, navigation.category, weight)
return self._run_skill(navigation, request) return self._run_skill(navigation, request)
@@ -511,6 +563,8 @@ class Scheduler:
A re-dispatched request whose skill is still unwritten must not author a A re-dispatched request whose skill is still unwritten must not author a
second skill — it reports the pending write instead. second skill — it reports the pending write instead.
""" """
if self._category_locked(category):
return self._blocked_create(request, category)
pending = request.meta.get("awaiting_skill_body") pending = request.meta.get("awaiting_skill_body")
if pending is not None: if pending is not None:
category_pending, name = pending category_pending, name = pending
@@ -531,6 +585,39 @@ class Scheduler:
), ),
) )
# ---- new-skill locks (deterministic per-category create door) ----
def _category_locked(self, category: str) -> bool:
"""Is this category closed to new-skill creation?
A plain boolean gate, not a SemIf decision: the closed `response` tree
and the built-in `housekeeping` category are locked in code
(HARD_LOCKED_CATEGORIES); every other category is locked when its
category config (`data/skills/<category>/config.json`) sets
`locks.new_skill` true. Absent config means unlocked. The lock is
creation-only: existing skills still run, and repair/regen of an
existing leaf is allowed.
"""
if category in CANNED_CATEGORIES or category in HARD_LOCKED_CATEGORIES:
return True
config = self.body_store.read_category_config(category) or {}
locks = config.get("locks") or {}
return bool(locks.get("new_skill", False))
def _blocked_create(self, request: Request, category: str) -> DispatchResult:
"""Report that a locked category will not accept a new skill."""
self.trace.append(
"skill_create_blocked", request.id, category=category
)
return DispatchResult(
kind="error",
summary=(
f"cannot create a new skill in {category}: new-skill creation "
f"is locked (set locks.new_skill=false in "
f"data/skills/{category}/config.json to allow it)"
),
)
def _run_skill(self, skill: Skill, request: Request) -> DispatchResult: def _run_skill(self, skill: Skill, request: Request) -> DispatchResult:
if skill.writing: if skill.writing:
return DispatchResult( return DispatchResult(
@@ -651,7 +738,11 @@ class Scheduler:
model the observed failure verbatim, never a paraphrase and never model the observed failure verbatim, never a paraphrase and never
credentials. credentials.
""" """
if not self.repair_enabled or skill.is_noop(): if (
not self.repair_enabled
or skill.is_noop()
or skill.category in DETERMINISTIC_CATEGORIES
):
return return
evidence = { evidence = {
"error": outcome.error, "error": outcome.error,
@@ -1033,6 +1124,11 @@ class Scheduler:
return return
self.registry.register(draft.name, draft.description) self.registry.register(draft.name, draft.description)
self.tree[draft.name] = [] self.tree[draft.name] = []
# Seed the category config so the new-skill lock is discoverable and
# editable from the start (default: unlocked).
self.body_store.write_category_config(
draft.name, {"locks": {"new_skill": False}}
)
self.trace.append( self.trace.append(
"category_created", "category_created",
job.request.id, job.request.id,
@@ -1053,6 +1149,14 @@ class Scheduler:
if not self._request_approval(job, "skill", draft.name, draft.description): if not self._request_approval(job, "skill", draft.name, draft.description):
return return
with self._lock: with self._lock:
if self._category_locked(job.category):
self.trace.append(
"skill_create_blocked",
job.request.id,
category=job.category,
phase="create_skill",
)
return
existing = {s.name for s in self.tree.get(job.category, [])} existing = {s.name for s in self.tree.get(job.category, [])}
if draft.name in existing: if draft.name in existing:
self.trace.append( self.trace.append(
@@ -1212,6 +1316,7 @@ class Scheduler:
draft: SkillDraft, draft: SkillDraft,
weight: float, weight: float,
repair_evidence: dict | None = None, repair_evidence: dict | None = None,
reason_kind: str = "run_failure",
) -> None: ) -> None:
"""Mark the leaf in-progress and queue the body write for the worker. """Mark the leaf in-progress and queue the body write for the worker.
@@ -1230,6 +1335,8 @@ class Scheduler:
) )
if leaf is None: if leaf is None:
return return
# A fresh write clears any stale cancellation for this name.
self._cancelled.discard((category, draft.name))
leaf.writing = True leaf.writing = True
contract = skill_contract_ref() contract = skill_contract_ref()
self.trace.append( self.trace.append(
@@ -1250,6 +1357,7 @@ class Scheduler:
draft=draft, draft=draft,
weight=weight, weight=weight,
repair_evidence=repair_evidence, repair_evidence=repair_evidence,
reason_kind=reason_kind,
) )
) )
if self._write_thread is None or not self._write_thread.is_alive(): if self._write_thread is None or not self._write_thread.is_alive():
@@ -1276,8 +1384,28 @@ class Scheduler:
if self._fatal is not None: if self._fatal is not None:
return return
job = self._writes.popleft() job = self._writes.popleft()
if self._consume_cancelled(job):
continue
self._write_skill_body(job) self._write_skill_body(job)
def _is_cancelled(self, category: str, name: str) -> bool:
with self._lock:
return (category, name) in self._cancelled
def _consume_cancelled(self, job: SkillWrite) -> bool:
"""Discard a queued write that was cancelled before it started."""
if not self._is_cancelled(job.category, job.draft.name):
return False
with self._lock:
self._cancelled.discard((job.category, job.draft.name))
self.trace.append(
"skill_write_cancelled",
job.request.id,
category=job.category,
skill=job.draft.name,
)
return True
def _write_skill_body(self, job: SkillWrite) -> None: def _write_skill_body(self, job: SkillWrite) -> None:
"""Run the full authoring pipeline for one queued write (no scheduler """Run the full authoring pipeline for one queued write (no scheduler
lock held here): deferred elicitation -> codegen body (or repair lock held here): deferred elicitation -> codegen body (or repair
@@ -1287,6 +1415,8 @@ class Scheduler:
The tree is snapshotted under the lock so the prompt build reads a The tree is snapshotted under the lock so the prompt build reads a
stable view even if the main thread merges another skill meanwhile. stable view even if the main thread merges another skill meanwhile.
""" """
if self._is_cancelled(job.category, job.draft.name):
return
with self._lock: with self._lock:
tree_snapshot = {category: list(skills) for category, skills in self.tree.items()} tree_snapshot = {category: list(skills) for category, skills in self.tree.items()}
if job.repair_evidence is None and not job.draft.requirements: if job.repair_evidence is None and not job.draft.requirements:
@@ -1306,7 +1436,7 @@ class Scheduler:
job.draft, job.draft,
self._read_body(job.category, job.draft.name), self._read_body(job.category, job.draft.name),
evidence, evidence,
reason_kind="run_failure", reason_kind=job.reason_kind,
) )
else: else:
code = generate_skill_body( code = generate_skill_body(
@@ -1331,6 +1461,8 @@ class Scheduler:
except (CodegenError, ValueError) as exc: except (CodegenError, ValueError) as exc:
self._fail_skill_write(job, exc) self._fail_skill_write(job, exc)
return return
if self._is_cancelled(job.category, job.draft.name):
return
self.body_store.write_body(job.category, job.draft.name, code) self.body_store.write_body(job.category, job.draft.name, code)
self.body_store.write_contract(job.category, job.draft.name, contract) self.body_store.write_contract(job.category, job.draft.name, contract)
try: try:
@@ -1690,6 +1822,9 @@ class Scheduler:
def _complete_skill_write(self, job: SkillWrite, code: str) -> None: def _complete_skill_write(self, job: SkillWrite, code: str) -> None:
"""Materialize the body, hot-merge it into the tree, and re-dispatch the """Materialize the body, hot-merge it into the tree, and re-dispatch the
original request so it is answered by the new leaf.""" original request so it is answered by the new leaf."""
if self._is_cancelled(job.category, job.draft.name):
self._discard_cancelled_write(job)
return
job.draft.code = code job.draft.code = code
try: try:
skill = materialize_skill(job.draft, job.category, self.body_store) skill = materialize_skill(job.draft, job.category, self.body_store)
@@ -1738,8 +1873,31 @@ class Scheduler:
) )
self.run_queue() self.run_queue()
def _discard_cancelled_write(self, job: SkillWrite) -> None:
"""Clean up a write that was cancelled mid-flight.
The cancel path already removed the leaf and folder; the generation may
have rewritten files after that, so delete the folder again and clear
the in-progress flag. The cancellation marker is consumed.
"""
with self._lock:
self._cancelled.discard((job.category, job.draft.name))
leaf = next(
(s for s in self.tree.get(job.category, []) if s.name == job.draft.name),
None,
)
if leaf is not None:
leaf.writing = False
try:
self.body_store.delete(job.category, job.draft.name)
except (OSError, ValueError):
pass
def _fail_skill_write(self, job: SkillWrite, exc: Exception) -> None: def _fail_skill_write(self, job: SkillWrite, exc: Exception) -> None:
"""Clear the in-progress flag and notify; the leaf stays a restartable stub.""" """Clear the in-progress flag and notify; the leaf stays a restartable stub."""
if self._is_cancelled(job.category, job.draft.name):
self._discard_cancelled_write(job)
return
with self._lock: with self._lock:
leaf = next( leaf = next(
(s for s in self.tree.get(job.category, []) if s.name == job.draft.name), (s for s in self.tree.get(job.category, []) if s.name == job.draft.name),
@@ -1770,6 +1928,10 @@ class Scheduler:
return "error", f"no skill {category}.{name}" return "error", f"no skill {category}.{name}"
if category in CANNED_CATEGORIES: if category in CANNED_CATEGORIES:
return "error", f"{category} is a closed canned tree; there is no body to write" return "error", f"{category} is a closed canned tree; there is no body to write"
if leaf.origin == "builtin":
return "error", f"{category}.{name} is a built-in skill; there is no body to write"
if self._category_locked(category):
return "error", f"{category} is locked to new skills"
if leaf.writing: if leaf.writing:
return "error", f"skill {category}.{name} is already being written" return "error", f"skill {category}.{name} is already being written"
if self.codegen is None: if self.codegen is None:
@@ -1795,6 +1957,222 @@ class Scheduler:
self.trace.append("skill_restarted", origin.id, category=category, skill=name) self.trace.append("skill_restarted", origin.id, category=category, skill=name)
return "running", f"restarting body write for {category}.{name}" return "running", f"restarting body write for {category}.{name}"
# ---- housekeeping (the meta skills' operations) ----
def _cancel_pending_write(self, category: str, name: str) -> bool:
"""Cancel any queued/in-flight body write for a leaf.
Removes a still-queued write and marks the name cancelled so an
in-flight generation discards its output. Returns whether a write was
in progress.
"""
with self._lock:
leaf = next(
(s for s in self.tree.get(category, []) if s.name == name), None
)
was_writing = bool(leaf and leaf.writing)
self._cancelled.add((category, name))
self._writes = deque(
w
for w in self._writes
if not (w.category == category and w.draft.name == name)
)
if leaf is not None:
leaf.writing = False
return was_writing
def delete_skill(self, category: str, name: str) -> tuple[str, str]:
"""Delete a skill: tree leaf, registry entry, folder, and tombstone.
Durable: the tombstone suppresses a seed (or a same-named generated
body) on every future load. Built-in skills cannot be deleted.
"""
with self._lock:
leaf = next(
(s for s in self.tree.get(category, []) if s.name == name), None
)
if leaf is None:
return "error", f"no skill {category}.{name}"
if leaf.origin == "builtin" or category in CANNED_CATEGORIES:
return "error", (
f"{category}.{name} is a built-in skill and cannot be deleted"
)
self._cancel_pending_write(category, name)
self.tree[category] = [
s for s in self.tree.get(category, []) if s.name != name
]
self.registry.unregister_skill(category, name)
self.deleted.add(category, name)
self.trace.append("skill_deleted", "?", category=category, skill=name)
try:
self.body_store.delete(category, name)
except (OSError, ValueError) as exc:
self.trace.append(
"skill_delete_failed",
"?",
category=category,
skill=name,
message=str(exc),
)
return "ok", f"deleted {category}.{name}"
def clear_skill_config(self, category: str, name: str) -> tuple[str, str]:
"""Clear a skill's recorded config so it is asked for again next fire."""
with self._lock:
leaf = next(
(s for s in self.tree.get(category, []) if s.name == name), None
)
if leaf is None:
return "error", f"no skill {category}.{name}"
current = self.body_store.read_config(category, name) or {}
cleared = sorted(set(current) | set(leaf.config or {}))
if not cleared:
return "ok", f"{category}.{name} has no recorded config"
self.body_store.write_config(category, name, {})
leaf.config = {}
self.trace.append(
"config_cleared",
"?",
category=category,
skill=name,
variables=cleared,
)
return "ok", (
f"cleared {len(cleared)} config variable(s) for {category}.{name}: "
+ ", ".join(cleared)
)
def regen_skill(
self, category: str, name: str, guidance: str = ""
) -> tuple[str, str]:
"""Regenerate a skill body from the user's guidance.
A stub with no body is simply (re)written; an existing body is rewritten
through the corrective path with the guidance as evidence. Built-in
skills cannot be regenerated; a locked category may still regenerate an
existing leaf (the lock is creation-only).
"""
with self._lock:
leaf = next(
(s for s in self.tree.get(category, []) if s.name == name), None
)
if leaf is None:
return "error", f"no skill {category}.{name}"
if category in CANNED_CATEGORIES or leaf.origin == "builtin":
return "error", (
f"{category}.{name} is a built-in skill and cannot be regenerated"
)
if self.codegen is None:
return "error", "no codegen configured"
if leaf.writing:
return "error", f"skill {category}.{name} is already being written"
draft = self._stub_draft(category, name)
if leaf.description:
draft.description = leaf.description
row = next(
(
s
for s in self.registry.read().get(category, {}).get("skills", [])
if s.get("name") == name
),
{},
)
request_text = row.get("request_text")
origin = (
Request(request_text, source="regen")
if request_text
else Request(
f"regenerate the body for {category}.{name}: {draft.description}",
source="regen",
)
)
previous = self._read_body(category, name)
evidence = {"guidance": guidance or "(none given)"} if previous else None
self._start_skill_write(
origin,
category,
draft,
0.5,
repair_evidence=evidence,
reason_kind="manual",
)
self.trace.append(
"skill_regen_started",
origin.id,
category=category,
skill=name,
guidance=guidance or None,
)
return "running", f"regenerating body for {category}.{name}"
def cancel_skill_build(self, category: str, name: str) -> tuple[str, str]:
"""Cancel a skill body build and delete its half-built leaf."""
with self._lock:
leaf = next(
(s for s in self.tree.get(category, []) if s.name == name), None
)
if leaf is None:
return "error", f"no skill {category}.{name}"
if leaf.origin == "builtin" or category in CANNED_CATEGORIES:
return "error", (
f"{category}.{name} is a built-in skill and cannot be cancelled"
)
was_writing = self._cancel_pending_write(category, name)
self.tree[category] = [
s for s in self.tree.get(category, []) if s.name != name
]
self.registry.unregister_skill(category, name)
self.deleted.add(category, name)
self.trace.append(
"skill_build_cancelled",
"?",
category=category,
skill=name,
was_writing=was_writing,
)
try:
self.body_store.delete(category, name)
except (OSError, ValueError) as exc:
self.trace.append(
"skill_delete_failed",
"?",
category=category,
skill=name,
message=str(exc),
)
detail = (
f"cancelled the build for {category}.{name} and deleted the leaf"
if was_writing
else f"deleted {category}.{name} (no build was in progress)"
)
return "ok", detail
def set_category_lock(self, category: str, locked: bool) -> tuple[str, str]:
"""Toggle a category's new-skill lock in its category config."""
with self._lock:
if category in CANNED_CATEGORIES or category in HARD_LOCKED_CATEGORIES:
return "error", (
f"{category} is a built-in category and is always locked"
)
if category not in self.tree:
return "error", f"no category {category}"
config = self.body_store.read_category_config(category) or {}
locks = dict(config.get("locks") or {})
locks["new_skill"] = bool(locked)
config["locks"] = locks
self.body_store.write_category_config(category, config)
self.trace.append(
"category_lock_set", "?", category=category, new_skill=bool(locked)
)
return "ok", (
f"{category} new-skill creation "
f"{'locked' if locked else 'unlocked'}"
)
def category_locks(self) -> dict[str, bool]:
with self._lock:
return {category: self._category_locked(category) for category in self.tree}
def status(self) -> str: def status(self) -> str:
with self._lock: with self._lock:
lines = [] lines = []
+8 -2
View File
@@ -31,6 +31,7 @@ from .decisions import DecisionRequest, Option, Request
from .log import DecisionLog from .log import DecisionLog
from .skills import ( from .skills import (
CANNED_CATEGORIES, CANNED_CATEGORIES,
DETERMINISTIC_CATEGORIES,
ActionContext, ActionContext,
Skill, Skill,
SkillStore, SkillStore,
@@ -118,7 +119,12 @@ class SkillRunner:
merged = {**self.ctx.config} merged = {**self.ctx.config}
merged.update(skill.config or {}) merged.update(skill.config or {})
merged.update(answered) merged.update(answered)
return ActionContext(engine=self.ctx.engine, config=merged, timers=self.ctx.timers) return ActionContext(
engine=self.ctx.engine,
config=merged,
timers=self.ctx.timers,
admin=self.ctx.admin,
)
def _unresolved(self, skill: Skill, request: Request) -> list[str]: def _unresolved(self, skill: Skill, request: Request) -> list[str]:
if not skill.contract: if not skill.contract:
@@ -345,7 +351,7 @@ class SkillRunner:
self, skill: Skill, request: Request, ctx: ActionContext, action self, skill: Skill, request: Request, ctx: ActionContext, action
) -> RunResult: ) -> RunResult:
observed = action.new_state observed = action.new_state
if skill.category in CANNED_CATEGORIES: if skill.category in CANNED_CATEGORIES or skill.category in DETERMINISTIC_CATEGORIES:
summary = deterministic_summary( summary = deterministic_summary(
skill.category, skill.name, True, action.action_log, observed skill.category, skill.name, True, action.action_log, observed
) )
+482 -1
View File
@@ -16,6 +16,7 @@ import importlib.util
import json import json
import os import os
import re import re
import shutil
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Callable from typing import Callable
@@ -43,6 +44,10 @@ class ActionContext:
engine: SemIfEngine engine: SemIfEngine
config: dict config: dict
timers: TimerService | None = None timers: TimerService | None = None
# The scheduler, exposed to built-in meta skills (housekeeping) so they can
# act on the agent's own tree/registry/store. None for ordinary bodies, which
# must never reach into the agent.
admin: object | None = None
def _noop_act(ctx: ActionContext, request: Request) -> ActionResult: def _noop_act(ctx: ActionContext, request: Request) -> ActionResult:
@@ -62,6 +67,11 @@ class Skill:
integration: dict = field(default_factory=dict) integration: dict = field(default_factory=dict)
integration_source: str = "unknown" integration_source: str = "unknown"
category_description: str = "" category_description: str = ""
# Where the leaf came from: "builtin" (hardcoded), "seed" (committed starter
# package), or "generated" (codegen-authored). Built-ins are protected from
# delete/restart/regen; seeds and generated leaves are deletable (durably,
# via a tombstone).
origin: str = "generated"
def is_noop(self) -> bool: def is_noop(self) -> bool:
"""A stub leaf: authored (title + description) but no runnable body yet.""" """A stub leaf: authored (title + description) but no runnable body yet."""
@@ -173,6 +183,23 @@ class CategoryRegistry:
self.path.parent.mkdir(parents=True, exist_ok=True) self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(categories, indent=2) + "\n") self.path.write_text(json.dumps(categories, indent=2) + "\n")
def unregister_skill(self, category: str, name: str) -> None:
"""Remove a skill entry from its category (the category itself stays).
The category bucket is kept even when it becomes empty: removing it would
make the category vanish from the navigation softmax until something
re-registers it.
"""
categories = self.read()
entry = categories.get(category)
if entry is None:
return
entry["skills"] = [
s for s in entry.get("skills", []) if s.get("name") != name
]
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(categories, indent=2) + "\n")
class SkillStore: class SkillStore:
"""Persists one skill leaf as a folder of deliverables. """Persists one skill leaf as a folder of deliverables.
@@ -264,6 +291,78 @@ class SkillStore:
skills.append((category_dir.name, entry.name)) skills.append((category_dir.name, entry.name))
return skills return skills
def delete(self, category: str, name: str) -> bool:
"""Remove a skill folder. Returns True when something was removed.
Path-guarded: the resolved folder must sit directly under this store's
root, so a crafted category/name can never escape it.
"""
target = (self.path / category / name).resolve()
root = self.path.resolve()
if target != root and root not in target.parents:
raise ValueError(f"refusing to delete outside the skill store: {target}")
if not target.is_dir():
return False
shutil.rmtree(target)
return True
class DeletedSkills:
"""A persisted set of deleted skill refs (`category.name`).
Seeds reload from the committed `seeds/` tree on every startup, so deleting
one from the running tree would be undone on the next boot. Recording the
ref here suppresses it (and any generated body of the same name) at load
time, making deletion durable. Restoring a skill means removing its ref.
"""
def __init__(self, path: str = "data/deleted_skills.json"):
self.path = Path(path)
def read(self) -> set[str]:
if not self.path.is_file():
return set()
try:
data = json.loads(self.path.read_text())
except ValueError:
return set()
if isinstance(data, dict):
data = data.get("skills", [])
return {str(ref) for ref in data or []}
def add(self, category: str, name: str) -> None:
refs = self.read()
refs.add(f"{category}.{name}")
self._write(refs)
def remove(self, category: str, name: str) -> None:
refs = self.read()
refs.discard(f"{category}.{name}")
self._write(refs)
def contains(self, category: str, name: str) -> bool:
return f"{category}.{name}" in self.read()
def _write(self, refs: set[str]) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(json.dumps(sorted(refs), indent=2) + "\n")
def apply_tombstones(tree: dict[str, list[Skill]], deleted: DeletedSkills) -> int:
"""Drop tombstoned leaves from the tree. Returns the number removed."""
removed = 0
for ref in deleted.read():
category, _, name = ref.partition(".")
if not name:
continue
skills = tree.get(category)
if not skills:
continue
kept = [s for s in skills if s.name != name]
removed += len(skills) - len(kept)
tree[category] = kept
return removed
def load_skill_module(category: str, name: str, base: str = "data/skills"): def load_skill_module(category: str, name: str, base: str = "data/skills"):
"""Import a persisted skill body and return its module.""" """Import a persisted skill body and return its module."""
@@ -333,6 +432,7 @@ def materialize_skill(
contract=contract, contract=contract,
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
origin="generated",
) )
@@ -378,6 +478,7 @@ def merge_skill_store(
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
category_description=category_description, category_description=category_description,
origin="generated",
) )
skills = tree.setdefault(category, []) skills = tree.setdefault(category, [])
for index, existing in enumerate(skills): for index, existing in enumerate(skills):
@@ -433,6 +534,7 @@ def merge_seed_store(
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
category_description=CATEGORY_DESCRIPTIONS.get(category, ""), category_description=CATEGORY_DESCRIPTIONS.get(category, ""),
origin="seed",
) )
skills = tree.setdefault(category, []) skills = tree.setdefault(category, [])
for index, existing in enumerate(skills): for index, existing in enumerate(skills):
@@ -495,6 +597,19 @@ def _canned_response(name: str, message: str):
CANNED_CATEGORIES = frozenset({"response"}) CANNED_CATEGORIES = frozenset({"response"})
RESPONSE_FALLBACK = "response.clarify" RESPONSE_FALLBACK = "response.clarify"
# The housekeeping category holds the agent's own maintenance skills (delete a
# skill, clear its config, regenerate it, cancel a build). It is a built-in
# category that is **deterministically locked** from new-skill creation — the
# lock is a code constant, not a config value, so it can never be unlocked by
# editing a file and navigation can never author into it.
HOUSEKEEPING_CATEGORY = "housekeeping"
HARD_LOCKED_CATEGORIES = frozenset({HOUSEKEEPING_CATEGORY})
# Categories whose runs are deterministic internal actions (a known found/not-
# found result, no external service): no SemIf assessment and no repair loop, so
# a "skill not found" can never offer to codegen-repair the meta skill.
DETERMINISTIC_CATEGORIES = frozenset({HOUSEKEEPING_CATEGORY})
_CANNED_RESPONSES = [ _CANNED_RESPONSES = [
( (
"greeting", "greeting",
@@ -553,6 +668,10 @@ CATEGORY_DESCRIPTIONS: dict[str, str] = {
"Time and date utilities: telling the current time or date, setting " "Time and date utilities: telling the current time or date, setting "
"countdown timers, and setting alarms." "countdown timers, and setting alarms."
), ),
"housekeeping": (
"Agent self-maintenance: deleting, reconfiguring, regenerating, and "
"cancelling the agent's own skills."
),
} }
@@ -576,11 +695,372 @@ def build_skills(config: dict) -> list[Skill]:
description=description, description=description,
act=_canned_response(f"response.{name}", message), act=_canned_response(f"response.{name}", message),
category_description=CATEGORY_DESCRIPTIONS["response"], category_description=CATEGORY_DESCRIPTIONS["response"],
origin="builtin",
) )
for name, description, message in _CANNED_RESPONSES for name, description, message in _CANNED_RESPONSES
] ]
def _confirmed(request: Request) -> bool:
"""Whether the human's answer to a confirmation prompt was affirmative."""
return str(request.user_input or "").strip().lower() in (
"y",
"yes",
"confirm",
"confirmed",
"ok",
"okay",
)
_TARGET_QUESTION = (
"Which skill? Reply with its name as category.skill (or a unique skill name)."
)
# Explicit housekeeping command forms. They are routed deterministically to the
# housekeeping skill (see parse_meta_command) because the generic SemIf guards
# read a task-like skill name in the request as the task itself (e.g.
# "regen skill calendar.create_event" scores as a calendar task). The skill name
# is just a variable the skill resolves — or asks for.
_META_PATTERNS: list[tuple[str, "re.Pattern[str]"]] = [
(
"delete_skill",
re.compile(
r"^\s*(?:please\s+)?(?:delete|remove|drop)\s+(?:the\s+|a\s+)?skill\b",
re.IGNORECASE,
),
),
(
"clear_config",
re.compile(
r"^\s*(?:please\s+)?(?:clear|reset|erase|wipe)\s+(?:the\s+|a\s+)?"
r"(?:skill'?s?\s+)?(?:config(?:uration)?|settings?|variables?)\b",
re.IGNORECASE,
),
),
(
"regen_skill",
re.compile(
r"^\s*(?:please\s+)?(?:regen|regenerate|rewrite|rebuild|fix|repair)\b"
r".*\b(?:skill|code)\b",
re.IGNORECASE,
),
),
(
"cancel_build",
re.compile(
r"^\s*(?:please\s+)?(?:"
r"(?:cancel|abort|stop)\s+(?:the\s+)?skill\s+build(?:ing)?\b"
r"|(?:cancel|abort)\s+(?:the\s+)?build\b"
r"|stop\s+building\b.*\bskill\b"
r")",
re.IGNORECASE,
),
),
]
def parse_meta_command(text: str) -> str | None:
"""Recognize an explicit housekeeping command, returning its skill name.
The command forms ("delete skill [name]", "clear config variables for
[name]", "regen skill [name]", "cancel skill build") are routed
deterministically, because the generic SemIf navigation misreads a
task-like skill name in the request as the task itself. Anything else
returns None and goes through normal navigation. The target skill name, when
present, is left in the request for the skill to resolve as an input
variable.
"""
stripped = (text or "").strip()
for name, pattern in _META_PATTERNS:
if pattern.match(stripped):
return name
return None
def _resolve_target(admin, request: Request):
"""Resolve the skill a housekeeping request targets.
The target may be named in the request ("delete skill calendar.foo") or
supplied as an input variable when the request is name-free ("delete
skill") — in which case the skill asks for it. Keeping the name out of the
routed request is deliberate: a skill name like `calendar.create_event`
reads as a task and pulls navigation to the wrong category. Returns a
`(category, name)` tuple, or an `ActionResult` (needs_input / not-found /
ambiguous) to return as-is.
"""
target = request.meta.get("housekeeping_target")
if target:
return tuple(target)
resolved = resolve_skill_ref(admin.tree, request.text)
if isinstance(resolved, tuple):
return resolved
if isinstance(resolved, list):
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping: several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
)
answer = (request.user_input or "").strip()
if not answer:
return ActionResult(
action_log="housekeeping: awaiting skill name",
new_state="awaiting target",
needs_input=_TARGET_QUESTION,
)
request.user_input = None
ref = resolve_skill_ref(admin.tree, answer)
if isinstance(ref, tuple):
request.meta["housekeeping_target"] = ref
return ref
if isinstance(ref, list):
names = ", ".join(f"{c}.{n}" for c, n in ref)
return ActionResult(
action_log=f"housekeeping: several skills match ({names}); be specific",
new_state="ambiguous",
)
return ActionResult(
action_log=f"housekeeping: no skill matches {answer!r}",
new_state="not found",
)
def _delete_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.delete_skill: no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
category, name = target
ref = f"{category}.{name}"
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.delete_skill: awaiting confirmation for {ref}",
new_state="awaiting confirmation",
needs_input=f"Delete {ref} and all its files? Reply yes to confirm.",
)
if not _confirmed(request):
return ActionResult(
action_log=f"housekeeping.delete_skill: cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.delete_skill(category, name)
return ActionResult(f"housekeeping.delete_skill: {detail}", detail)
def _clear_config_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.clear_config: no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
category, name = target
_status, detail = admin.clear_skill_config(category, name)
return ActionResult(f"housekeeping.clear_config: {detail}", detail)
def _regen_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.regen_skill: no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
category, name = target
ref = f"{category}.{name}"
if request.meta.get("housekeeping_regen") != ref:
request.meta["housekeeping_regen"] = ref
return ActionResult(
action_log=f"housekeeping.regen_skill: awaiting guidance for {ref}",
new_state="awaiting guidance",
needs_input="What needs to be fixed?",
)
guidance = (request.user_input or "").strip()
_status, detail = admin.regen_skill(category, name, guidance)
return ActionResult(f"housekeeping.regen_skill: {detail}", detail)
def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
admin = ctx.admin
if admin is None:
return ActionResult("housekeeping.cancel_build: no admin available", "error")
writing = [
(category, skill.name)
for category, skills in admin.tree.items()
for skill in skills
if skill.writing
]
target = request.meta.get("housekeeping_target")
if target:
category, name = tuple(target)
else:
resolved = resolve_skill_ref(admin.tree, request.text)
if isinstance(resolved, list):
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping.cancel_build: several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
)
if isinstance(resolved, tuple):
if resolved not in writing:
category, name = resolved
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build is in progress for "
f"{category}.{name}"
),
new_state="no build",
)
category, name = resolved
elif len(writing) == 1:
category, name = writing[0]
elif not writing:
return ActionResult(
action_log="housekeeping.cancel_build: no skill build is in progress",
new_state="no build",
)
else:
answer = (request.user_input or "").strip()
if not answer:
return ActionResult(
action_log="housekeeping.cancel_build: awaiting skill name",
new_state="awaiting target",
needs_input="Which skill build should I cancel? Reply with its name.",
)
request.user_input = None
ref = resolve_skill_ref(admin.tree, answer)
if isinstance(ref, tuple) and ref in writing:
category, name = ref
else:
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build in progress matching "
f"{answer!r}"
),
new_state="no build",
)
request.meta["housekeeping_target"] = (category, name)
ref = f"{category}.{name}"
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.cancel_build: awaiting confirmation for {ref}",
new_state="awaiting confirmation",
needs_input=(
f"Cancel the build for {ref} and delete its half-built leaf? "
"Reply yes to confirm."
),
)
if not _confirmed(request):
return ActionResult(
action_log=f"housekeeping.cancel_build: cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.cancel_skill_build(category, name)
return ActionResult(f"housekeeping.cancel_build: {detail}", detail)
def build_housekeeping_skills() -> list[Skill]:
"""The built-in meta skills that maintain the agent's own skill tree.
They act on the scheduler (reached through `ctx.admin`) rather than an
external service, so they live here beside the canned `response` tree, not
in the codegen/seed pipeline. Their runs are deterministic internal actions
(see DETERMINISTIC_CATEGORIES) and the category is deterministically locked
from new-skill creation (HARD_LOCKED_CATEGORIES).
"""
description = CATEGORY_DESCRIPTIONS[HOUSEKEEPING_CATEGORY]
return [
Skill(
name="delete_skill",
category=HOUSEKEEPING_CATEGORY,
description=(
"Delete an existing skill: remove it from the tree, delete its "
"code body and files, and forget its recorded config."
),
act=_delete_skill_act,
category_description=description,
origin="builtin",
),
Skill(
name="clear_config",
category=HOUSEKEEPING_CATEGORY,
description=(
"Clear the saved configuration variables recorded for an "
"existing skill, so they are asked for again next time it runs."
),
act=_clear_config_act,
category_description=description,
origin="builtin",
),
Skill(
name="regen_skill",
category=HOUSEKEEPING_CATEGORY,
description=(
"Regenerate (rewrite) an existing skill's code body from "
"guidance about what needs to be fixed."
),
act=_regen_skill_act,
category_description=description,
origin="builtin",
),
Skill(
name="cancel_build",
category=HOUSEKEEPING_CATEGORY,
description=(
"Cancel a skill body that is still being generated and delete "
"its half-built skill leaf."
),
act=_cancel_build_act,
category_description=description,
origin="builtin",
),
]
def resolve_skill_ref(
tree: dict[str, list[Skill]], text: str
) -> tuple[str, str] | list[tuple[str, str]] | None:
"""Find the skill(s) named in a free-form request.
Matches `category.name` or a bare unique `name`, case-insensitively, on a
token boundary (so `time` does not match inside `sometimes`). The longest
match wins; a tie across different skills returns the list of candidates so
the caller can ask the human to be specific. Returns None when nothing
matches.
"""
lowered = text.lower()
matches: list[tuple[str, str, int]] = []
for category, skills in tree.items():
for skill in skills:
for candidate in (f"{category}.{skill.name}", skill.name):
if _mentions(lowered, candidate.lower()):
matches.append((category, skill.name, len(candidate)))
if not matches:
return None
longest = max(match[2] for match in matches)
top = {(category, name) for category, name, length in matches if length == longest}
if len(top) == 1:
return next(iter(top))
return sorted(top)
def _mentions(haystack: str, needle: str) -> bool:
if not needle:
return False
pattern = r"(?<![a-z0-9_.])" + re.escape(needle) + r"(?![a-z0-9_.])"
return re.search(pattern, haystack) is not None
def category_descriptions(tree: dict[str, list[Skill]]) -> dict[str, str]: def category_descriptions(tree: dict[str, list[Skill]]) -> dict[str, str]:
"""The description to offer for each category, best-effort. """The description to offer for each category, best-effort.
@@ -934,7 +1414,8 @@ def confirm_non_action(
"action", "action",
"It is a request: the user asks the agent for a specific answer, a " "It is a request: the user asks the agent for a specific answer, a "
"result, or an action (including one the agent has no skill for " "result, or an action (including one the agent has no skill for "
"yet).", "yet), or gives a command to manage a skill (delete, clear config, "
"regenerate, cancel a build).",
), ),
Option( Option(
"non_action", "non_action",
+99
View File
@@ -155,6 +155,18 @@ function eventRow(evt) {
div.title = evt.message || ""; div.title = evt.message || "";
} else if (evt.kind === "skill_restarted") { } else if (evt.kind === "skill_restarted") {
div.textContent = `restarted body write: ${evt.skill}`; div.textContent = `restarted body write: ${evt.skill}`;
} else if (evt.kind === "skill_deleted") {
div.textContent = `deleted skill: ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_build_cancelled") {
div.textContent = `cancelled build: ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_regen_started") {
div.textContent = `regenerating skill: ${evt.category}.${evt.skill}`;
} else if (evt.kind === "config_cleared") {
div.textContent = `cleared config: ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_create_blocked") {
div.textContent = `new-skill creation blocked: ${evt.category}`;
} else if (evt.kind === "category_lock_set") {
div.textContent = `${evt.category} new-skill lock ${evt.new_skill ? "on" : "off"}`;
} else if (evt.kind === "needs_input") { } else if (evt.kind === "needs_input") {
div.textContent = "needs input"; div.textContent = "needs input";
div.title = evt.question || ""; div.title = evt.question || "";
@@ -497,6 +509,20 @@ function eventNode(evt) {
node.appendChild(btn); node.appendChild(btn);
} else if (evt.kind === "skill_restarted") { } else if (evt.kind === "skill_restarted") {
body.textContent = `restarted body write for ${evt.skill}`; body.textContent = `restarted body write for ${evt.skill}`;
} else if (evt.kind === "skill_deleted") {
node.classList.add("stub");
body.textContent = `deleted ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_build_cancelled") {
node.classList.add("stub");
body.textContent = `cancelled build for ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_regen_started") {
body.textContent = `regenerating ${evt.category}.${evt.skill}`;
} else if (evt.kind === "config_cleared") {
body.textContent = `cleared config for ${evt.category}.${evt.skill}`;
} else if (evt.kind === "skill_create_blocked") {
body.textContent = `new-skill creation blocked in ${evt.category}`;
} else if (evt.kind === "category_lock_set") {
body.textContent = `${evt.category} new-skill lock ${evt.new_skill ? "on" : "off"}`;
} else if (evt.kind === "needs_input") { } else if (evt.kind === "needs_input") {
node.classList.add("needs-input"); node.classList.add("needs-input");
body.textContent = `awaiting input: ${evt.question || ""}`; body.textContent = `awaiting input: ${evt.question || ""}`;
@@ -570,6 +596,43 @@ async function restartSkill(category, name) {
await refreshAll(); await refreshAll();
} }
async function housekeepingAction(path, category, name) {
try {
const res = await getJSON(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category, skill: name }),
});
flash(`[${res.status}] ${res.detail}`);
} catch (err) {
flash(`${path} failed: ${err.message}`);
}
await refreshAll();
}
async function toggleLock(category, locked) {
try {
const res = await getJSON("/api/lock", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category, locked }),
});
flash(`[${res.status}] ${res.detail}`);
} catch (err) {
flash(`lock failed: ${err.message}`);
}
await refreshAll();
}
function actionBtn(label, title, onClick) {
const btn = document.createElement("button");
btn.className = "restart-btn";
btn.textContent = label;
btn.title = title;
btn.addEventListener("click", onClick);
return btn;
}
async function answerQuestion(id, text) { async function answerQuestion(id, text) {
try { try {
const res = await getJSON("/api/questions", { const res = await getJSON("/api/questions", {
@@ -640,6 +703,18 @@ function renderTree() {
const name = document.createElement("div"); const name = document.createElement("div");
name.className = "cat-name"; name.className = "cat-name";
name.textContent = cat; name.textContent = cat;
const locked = (state.tree.locks || {})[cat];
if (locked !== undefined) {
const lock = actionBtn(
locked ? "locked" : "open",
locked
? "new-skill creation is locked; click to allow"
: "new-skill creation is allowed; click to lock",
() => toggleLock(cat, !locked)
);
lock.classList.add("lock-btn");
name.appendChild(lock);
}
div.appendChild(name); div.appendChild(name);
for (const skill of skills) { for (const skill of skills) {
const row = document.createElement("div"); const row = document.createElement("div");
@@ -665,6 +740,30 @@ function renderTree() {
row.appendChild(un); row.appendChild(un);
} }
row.appendChild(skillStatusBadge(skill.status, cat, skill.name)); row.appendChild(skillStatusBadge(skill.status, cat, skill.name));
if (skill.origin !== "builtin") {
row.appendChild(
actionBtn("delete", `delete ${cat}.${skill.name}`, () =>
housekeepingAction("/api/delete", cat, skill.name)
)
);
row.appendChild(
actionBtn("regen", `regenerate ${cat}.${skill.name}`, () =>
housekeepingAction("/api/regen", cat, skill.name)
)
);
row.appendChild(
actionBtn("clear config", `clear recorded config for ${cat}.${skill.name}`, () =>
housekeepingAction("/api/clear-config", cat, skill.name)
)
);
}
if (skill.status === "writing") {
row.appendChild(
actionBtn("cancel", `cancel the build for ${cat}.${skill.name}`, () =>
housekeepingAction("/api/cancel-build", cat, skill.name)
)
);
}
div.appendChild(row); div.appendChild(row);
} }
el.appendChild(div); el.appendChild(div);
+7
View File
@@ -381,6 +381,13 @@ pre.json {
color: var(--accent); color: var(--accent);
} }
.lock-btn {
margin-left: 6px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
}
.stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; } .stat-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
.stat-grid .stat { background: var(--panel-2); border-radius: 4px; padding: 4px 6px; } .stat-grid .stat { background: var(--panel-2); border-radius: 4px; padding: 4px 6px; }
.stat-grid .stat .v { font-weight: 700; } .stat-grid .stat .v { font-weight: 700; }
+134 -1
View File
@@ -32,12 +32,36 @@ def build_scheduler(tmp_path, engine=None):
engine=engine, engine=engine,
llm=llm, llm=llm,
log=log, log=log,
config={"skills": {}, "skill_seeds": str(tmp_path / "seeds")}, config={
"skills": {},
"skill_seeds": str(tmp_path / "seeds"),
"skill_bodies": str(tmp_path / "skills"),
"category_registry": str(tmp_path / "categories.json"),
"deleted_skills": str(tmp_path / "deleted_skills.json"),
},
trace=trace, trace=trace,
) )
return scheduler return scheduler
def _generated_skill(scheduler, category, name):
def act(ctx, request):
return ActionResult(action_log="ok", new_state="ok")
skill = Skill(
name=name,
category=category,
description="A generated skill.",
act=act,
origin="generated",
)
scheduler.tree.setdefault(category, []).append(skill)
scheduler.body_store.write_body(
category, name, "def act(ctx, request):\n return None\n"
)
return skill
def seed_decision(log, decision_id="abc123"): def seed_decision(log, decision_id="abc123"):
request = DecisionRequest( request = DecisionRequest(
id=decision_id, id=decision_id,
@@ -131,6 +155,115 @@ def test_restart_without_codegen_returns_error_json(tmp_path):
server.close() server.close()
def test_tree_endpoint_carries_origin_and_locks(tmp_path):
scheduler = build_scheduler(tmp_path)
_generated_skill(scheduler, "tracking", "track_live")
server = Server(scheduler)
try:
status, payload = server.get("/api/tree")
assert status == 200
by_name = {s["name"]: s for s in payload["categories"]["tracking"]}
assert by_name["track_live"]["origin"] == "generated"
assert any(
s["origin"] == "builtin"
for s in payload["categories"]["housekeeping"]
)
assert payload["locks"]["housekeeping"] is True
assert payload["locks"]["response"] is True
assert payload["locks"]["tracking"] is False
finally:
server.close()
def test_delete_endpoint_removes_skill(tmp_path):
scheduler = build_scheduler(tmp_path)
_generated_skill(scheduler, "tracking", "track_live")
server = Server(scheduler)
try:
status, payload = server.post(
"/api/delete", {"category": "tracking", "skill": "track_live"}
)
assert status == 200
assert payload["status"] == "ok"
assert all(s.name != "track_live" for s in scheduler.tree["tracking"])
assert not scheduler.body_store.dir("tracking", "track_live").exists()
finally:
server.close()
def test_clear_config_endpoint(tmp_path):
scheduler = build_scheduler(tmp_path)
skill = _generated_skill(scheduler, "tracking", "track_live")
skill.config = {"api_key": "x"}
scheduler.body_store.write_config("tracking", "track_live", {"api_key": "x"})
server = Server(scheduler)
try:
status, payload = server.post(
"/api/clear-config", {"category": "tracking", "skill": "track_live"}
)
assert status == 200
assert payload["status"] == "ok"
assert scheduler.body_store.read_config("tracking", "track_live") == {}
finally:
server.close()
def test_cancel_build_endpoint(tmp_path):
scheduler = build_scheduler(tmp_path)
skill = _generated_skill(scheduler, "tracking", "track_live")
skill.writing = True
server = Server(scheduler)
try:
status, payload = server.post(
"/api/cancel-build", {"category": "tracking", "skill": "track_live"}
)
assert status == 200
assert payload["status"] == "ok"
assert all(s.name != "track_live" for s in scheduler.tree["tracking"])
finally:
server.close()
def test_regen_endpoint_without_codegen_errors(tmp_path):
scheduler = build_scheduler(tmp_path)
_generated_skill(scheduler, "tracking", "track_live")
server = Server(scheduler)
try:
status, payload = server.post(
"/api/regen", {"category": "tracking", "skill": "track_live"}
)
assert status == 200
assert payload["status"] == "error"
assert "codegen" in payload["detail"]
finally:
server.close()
def test_lock_endpoint_roundtrip(tmp_path):
scheduler = build_scheduler(tmp_path)
scheduler.tree["tracking"] = []
server = Server(scheduler)
try:
status, payload = server.get("/api/locks")
assert status == 200
assert payload["locks"]["tracking"] is False
status, payload = server.post(
"/api/lock", {"category": "tracking", "locked": True}
)
assert payload["status"] == "ok"
status, payload = server.get("/api/tree")
assert payload["locks"]["tracking"] is True
status, payload = server.post(
"/api/lock", {"category": "housekeeping", "locked": False}
)
assert payload["status"] == "error"
finally:
server.close()
def test_trace_endpoint_empty(tmp_path): def test_trace_endpoint_empty(tmp_path):
server = Server(build_scheduler(tmp_path)) server = Server(build_scheduler(tmp_path))
try: try:
+49
View File
@@ -281,6 +281,55 @@ def test_service_surfaces_and_resolves_approval(tmp_path):
assert any("approved" in text for text in drain_outbound(service)) assert any("approved" in text for text in drain_outbound(service))
# ---- service: result-only front end (voice) ----
class FakeResultOnlyAdapter:
name = "voice"
result_only = True
def build_result_only_service(scheduler, config=None):
return GatewayService(scheduler, FakeResultOnlyAdapter(), config=config or {})
def test_result_detail_unwraps_scheduler_summary():
from semif_agent.gateway.service import _result_detail
assert _result_detail("time.now: ok — 2026-10-06 12:00") == "2026-10-06 12:00"
assert _result_detail("interrupted x; time.now: ok — 12:00") == "12:00"
assert _result_detail("a plain reply") == "a plain reply"
def test_result_only_speaks_detail_and_drops_status(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_result_only_service(scheduler)
service._reply("voice", "c", "[high] time.now: ok — 12:00", kind="result")
service._reply("voice", "c", "urgency low (weight 0.20)", kind="status")
service._reply("voice", "c", "Which account?", kind="question")
assert drain_outbound(service) == ["12:00", "Which account?"]
def test_plain_adapter_keeps_full_scheduler_output(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_service(scheduler) # FakeAdapter (simplex), not result_only
service._reply("simplex", "4", "[high] time.now: ok — 12:00", kind="result")
service._reply("simplex", "4", "urgency low (weight 0.20)", kind="status")
assert drain_outbound(service) == [
"[high] time.now: ok — 12:00",
"urgency low (weight 0.20)",
]
def test_config_can_turn_result_only_off(tmp_path):
scheduler = build_scheduler(tmp_path)
service = build_result_only_service(
scheduler, config={"voice": {"result_only": False}}
)
service._reply("voice", "c", "[high] time.now: ok — 12:00", kind="result")
service._reply("voice", "c", "urgency low", kind="status")
assert drain_outbound(service) == ["[high] time.now: ok — 12:00", "urgency low"]
# ---- LXMF adapter ---- # ---- LXMF adapter ----
def test_lxmf_default_deny_and_allowlist(): def test_lxmf_default_deny_and_allowlist():
+498
View File
@@ -0,0 +1,498 @@
"""Pure-stdlib tests for the housekeeping meta skills and per-category locks.
These cover the deterministic mechanics: name resolution, registry/store
deletion, tombstones, the lock gate, and the scheduler operations the meta
skills call. The SemIf routing of a natural-language housekeeping request is a
real-engine concern, verified by the integration tests on a provisioned host.
"""
import json
from pathlib import Path
import pytest
from semif_agent.decisions import Request
from semif_agent.llm import LLMClient
from semif_agent.log import DecisionLog
from semif_agent.scheduler import Scheduler, SkillWrite
from semif_agent.skills import (
ActionContext,
CategoryRegistry,
DeletedSkills,
Skill,
SkillDraft,
SkillStore,
apply_tombstones,
build_housekeeping_skills,
parse_meta_command,
resolve_skill_ref,
_cancel_build_act,
_delete_skill_act,
)
from semif_agent.trace import TraceLog
from tests.conftest import ScriptedEngine
SEED_BODY = """\
from semif_agent.skills import ActionResult
INTEGRATION = {"service": "probe", "transport": "compute", "config_vars": []}
CONTRACT = {}
def act(ctx, request):
return ActionResult(action_log="probe ran", new_state="ok")
"""
def _scheduler(tmp_path, choices=None, default="success"):
return Scheduler(
engine=ScriptedEngine(choices=choices, default=default),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={
"skills": {},
"category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(tmp_path / "seeds"),
"deleted_skills": str(tmp_path / "deleted_skills.json"),
},
trace=TraceLog(str(tmp_path / "runs.jsonl")),
)
def _add_skill(scheduler, category, name, origin="generated"):
def act(ctx, request):
return None
skill = Skill(
name=name,
category=category,
description=f"{name} description",
act=act,
origin=origin,
)
scheduler.tree.setdefault(category, []).append(skill)
scheduler.registry.register_skill(category, name, skill.description)
scheduler.body_store.write_body(
category, name, "def act(ctx, request):\n return None\n"
)
return skill
def _write_seed(root: Path, category, name):
directory = root / category / name
directory.mkdir(parents=True, exist_ok=True)
(directory / "skill.py").write_text(SEED_BODY)
(directory / "contract.json").write_text("{}")
# ---- built-ins ----
def test_build_housekeeping_skills():
skills = build_housekeeping_skills()
assert {s.name for s in skills} == {
"delete_skill",
"clear_config",
"regen_skill",
"cancel_build",
}
assert all(s.category == "housekeeping" for s in skills)
assert all(s.origin == "builtin" for s in skills)
assert all(not s.is_noop() for s in skills)
assert all(s.category_description for s in skills)
# ---- deterministic meta-command recognition ----
def test_parse_meta_command_forms():
assert parse_meta_command("delete skill") == "delete_skill"
assert parse_meta_command("delete skill calendar.foo") == "delete_skill"
assert parse_meta_command("remove skill simplex.next_message") == "delete_skill"
assert parse_meta_command("clear config variables") == "clear_config"
assert parse_meta_command("clear the config variables for calendar.foo") == "clear_config"
assert parse_meta_command("clear the settings for simplex.next_message") == "clear_config"
assert parse_meta_command("reset a skill's settings") == "clear_config"
assert parse_meta_command("regen skill") == "regen_skill"
assert parse_meta_command("regenerate the simplex skill") == "regen_skill"
assert parse_meta_command("rewrite the code for calendar.foo") == "regen_skill"
assert parse_meta_command("cancel skill build") == "cancel_build"
assert parse_meta_command("cancel the skill build") == "cancel_build"
assert parse_meta_command("abort the build") == "cancel_build"
assert parse_meta_command("stop building the new skill") == "cancel_build"
def test_parse_meta_command_leaves_normal_requests_alone():
for text in (
"what is on my calendar",
"read my next simplex message",
"hello there",
"set a timer for 5 minutes",
"send a message to pepper",
"what is 255 * 12?",
"stop building the deck",
"fix my bike",
):
assert parse_meta_command(text) is None, text
def test_dispatch_routes_meta_command_deterministically(tmp_path):
scheduler = _scheduler(tmp_path)
_add_skill(scheduler, "calendar", "foo")
# clear config runs immediately (no confirmation).
result = scheduler._dispatch(Request("clear config variables for calendar.foo"))
assert result.kind == "ran"
assert result.skill == "clear_config"
# delete routes to the meta skill and pauses for confirmation.
delete = scheduler._dispatch(Request("delete skill calendar.foo"))
assert delete.kind == "needs_input"
assert delete.skill == "delete_skill"
assert any(e["kind"] == "meta_command" for e in scheduler.trace.read())
assert any(s.name == "foo" for s in scheduler.tree["calendar"])
# ---- name resolution ----
def _tree():
return {
"calendar": [
Skill(name="next_event", category="calendar", description="d"),
],
"simplex": [
Skill(name="next_message", category="simplex", description="d"),
],
}
def test_resolve_skill_ref_dotted_and_bare():
tree = _tree()
assert resolve_skill_ref(tree, "delete skill calendar.next_event") == (
"calendar",
"next_event",
)
assert resolve_skill_ref(tree, "delete skill next_message") == (
"simplex",
"next_message",
)
def test_resolve_skill_ref_none_and_boundary():
tree = {"time": [Skill(name="time", category="time", description="d")]}
assert resolve_skill_ref(tree, "delete skill nothing") is None
assert resolve_skill_ref(tree, "sometimes I wonder") is None
def test_resolve_skill_ref_ambiguous():
tree = {
"a": [Skill(name="ping", category="a", description="d")],
"b": [Skill(name="ping", category="b", description="d")],
}
assert resolve_skill_ref(tree, "delete skill ping") == [("a", "ping"), ("b", "ping")]
# ---- registry / store / tombstones ----
def test_registry_unregister_skill(tmp_path):
registry = CategoryRegistry(str(tmp_path / "categories.json"))
registry.register_skill("delivery", "track", "Track.")
registry.unregister_skill("delivery", "track")
assert registry.read()["delivery"]["skills"] == []
def test_skill_store_delete_and_path_guard(tmp_path):
store = SkillStore(str(tmp_path / "skills"))
store.write_body("calendar", "foo", "x = 1\n")
assert store.delete("calendar", "foo") is True
assert not store.dir("calendar", "foo").exists()
with pytest.raises(ValueError):
store.delete("..", "escape")
def test_deleted_skills_roundtrip(tmp_path):
deleted = DeletedSkills(str(tmp_path / "deleted.json"))
assert deleted.read() == set()
deleted.add("calendar", "foo")
assert deleted.contains("calendar", "foo")
deleted.remove("calendar", "foo")
assert deleted.read() == set()
def test_apply_tombstones():
tree = {
"calendar": [Skill(name="foo", category="calendar", description="d")],
"simplex": [Skill(name="bar", category="simplex", description="d")],
}
deleted = DeletedSkills("/nonexistent/deleted.json")
deleted.read = lambda: {"calendar.foo"} # type: ignore[assignment]
removed = apply_tombstones(tree, deleted)
assert removed == 1
assert tree["calendar"] == []
assert [s.name for s in tree["simplex"]] == ["bar"]
def test_delete_seed_is_durable(tmp_path):
_write_seed(tmp_path / "seeds", "calendar", "probe")
scheduler = _scheduler(tmp_path)
assert any(s.name == "probe" for s in scheduler.tree["calendar"])
assert scheduler.tree["calendar"][0].origin == "seed"
status, _ = scheduler.delete_skill("calendar", "probe")
assert status == "ok"
reloaded = _scheduler(tmp_path)
assert all(s.name != "probe" for s in reloaded.tree.get("calendar", []))
# ---- locks ----
def test_housekeeping_and_response_are_hard_locked(tmp_path):
scheduler = _scheduler(tmp_path)
assert scheduler._category_locked("housekeeping") is True
assert scheduler._category_locked("response") is True
status, _ = scheduler.set_category_lock("housekeeping", False)
assert status == "error"
def test_category_lock_config_roundtrip(tmp_path):
scheduler = _scheduler(tmp_path)
scheduler.tree["notes"] = []
assert scheduler._category_locked("notes") is False
status, _ = scheduler.set_category_lock("notes", True)
assert status == "ok"
assert scheduler._category_locked("notes") is True
config = scheduler.body_store.read_category_config("notes")
assert config["locks"]["new_skill"] is True
scheduler.set_category_lock("notes", False)
assert scheduler._category_locked("notes") is False
assert any(
e["kind"] == "category_lock_set" for e in scheduler.trace.read()
)
def test_dispatch_skill_blocked_when_locked(tmp_path):
scheduler = _scheduler(tmp_path)
scheduler.tree["notes"] = []
scheduler.set_category_lock("notes", True)
result = scheduler._dispatch_skill(Request("make a note"), "notes")
assert result.kind == "error"
assert "locked" in result.summary
assert any(e["kind"] == "skill_create_blocked" for e in scheduler.trace.read())
def test_restart_skill_blocked_when_locked(tmp_path):
scheduler = _scheduler(tmp_path)
scheduler.tree["notes"] = [
Skill(name="stub", category="notes", description="d")
]
scheduler.set_category_lock("notes", True)
status, _ = scheduler.restart_skill("notes", "stub")
assert status == "error"
# ---- operations ----
def test_delete_skill_removes_tree_registry_and_folder(tmp_path):
scheduler = _scheduler(tmp_path)
_add_skill(scheduler, "calendar", "foo")
status, detail = scheduler.delete_skill("calendar", "foo")
assert status == "ok"
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
assert scheduler.body_store.read_contract("calendar", "foo") == {}
assert not scheduler.body_store.dir("calendar", "foo").exists()
assert all(
s.get("name") != "foo"
for s in scheduler.registry.read()["calendar"]["skills"]
)
assert scheduler.deleted.contains("calendar", "foo")
assert any(e["kind"] == "skill_deleted" for e in scheduler.trace.read())
def test_delete_refuses_builtin(tmp_path):
scheduler = _scheduler(tmp_path)
status, _ = scheduler.delete_skill("housekeeping", "delete_skill")
assert status == "error"
status, _ = scheduler.delete_skill("response", "response.clarify")
assert status == "error"
def test_clear_skill_config(tmp_path):
scheduler = _scheduler(tmp_path)
skill = _add_skill(scheduler, "calendar", "foo")
skill.config = {"api_key": "x"}
scheduler.body_store.write_config("calendar", "foo", {"api_key": "x"})
status, detail = scheduler.clear_skill_config("calendar", "foo")
assert status == "ok"
assert "api_key" in detail
assert scheduler.body_store.read_config("calendar", "foo") == {}
assert skill.config == {}
assert any(e["kind"] == "config_cleared" for e in scheduler.trace.read())
def test_regen_skill_rewrites_existing_body(tmp_path, monkeypatch):
scheduler = _scheduler(tmp_path)
scheduler.codegen = object()
_add_skill(scheduler, "calendar", "foo")
captured = {}
def fake_start(request, category, draft, weight, repair_evidence=None, reason_kind="run_failure"):
captured.update(
category=category,
repair_evidence=repair_evidence,
reason_kind=reason_kind,
)
monkeypatch.setattr(scheduler, "_start_skill_write", fake_start)
status, _ = scheduler.regen_skill("calendar", "foo", "it crashes")
assert status == "running"
assert captured["reason_kind"] == "manual"
assert captured["repair_evidence"]["guidance"] == "it crashes"
assert any(
e["kind"] == "skill_regen_started" for e in scheduler.trace.read()
)
def test_regen_skill_stub_has_no_evidence(tmp_path, monkeypatch):
scheduler = _scheduler(tmp_path)
scheduler.codegen = object()
scheduler.tree["calendar"] = [
Skill(name="stub", category="calendar", description="d")
]
captured = {}
def fake_start(request, category, draft, weight, repair_evidence=None, reason_kind="run_failure"):
captured.update(repair_evidence=repair_evidence, reason_kind=reason_kind)
monkeypatch.setattr(scheduler, "_start_skill_write", fake_start)
status, _ = scheduler.regen_skill("calendar", "stub", "make it work")
assert status == "running"
assert captured["repair_evidence"] is None
def test_cancel_skill_build_discards_and_deletes(tmp_path):
scheduler = _scheduler(tmp_path)
skill = _add_skill(scheduler, "calendar", "foo")
skill.writing = True
scheduler._writes.append(
SkillWrite(
request=Request("build foo"),
category="calendar",
draft=SkillDraft(name="foo", description="d"),
weight=0.5,
)
)
status, detail = scheduler.cancel_skill_build("calendar", "foo")
assert status == "ok"
assert "cancelled" in detail
assert ("calendar", "foo") in scheduler._cancelled
assert not any(w.draft.name == "foo" for w in scheduler._writes)
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
assert not scheduler.body_store.dir("calendar", "foo").exists()
assert any(
e["kind"] == "skill_build_cancelled" for e in scheduler.trace.read()
)
def test_consume_cancelled_discards_queued_write(tmp_path):
scheduler = _scheduler(tmp_path)
job = SkillWrite(
request=Request("build foo"),
category="calendar",
draft=SkillDraft(name="foo", description="d"),
weight=0.5,
)
scheduler._cancelled.add(("calendar", "foo"))
assert scheduler._consume_cancelled(job) is True
assert ("calendar", "foo") not in scheduler._cancelled
assert any(
e["kind"] == "skill_write_cancelled" for e in scheduler.trace.read()
)
# ---- meta-skill act flows ----
def test_delete_skill_act_confirms_then_deletes(tmp_path):
scheduler = _scheduler(tmp_path)
_add_skill(scheduler, "calendar", "foo")
ctx = ActionContext(engine=None, config={}, admin=scheduler)
request = Request("delete skill calendar.foo")
first = _delete_skill_act(ctx, request)
assert first.needs_input and "confirm" in first.needs_input.lower()
assert any(s.name == "foo" for s in scheduler.tree["calendar"])
request.user_input = "yes"
second = _delete_skill_act(ctx, request)
assert second.needs_input is None
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
def test_delete_skill_act_asks_for_target_when_absent(tmp_path):
"""A name-free request ("delete skill") asks for the target as an input
variable, then confirms, then deletes."""
scheduler = _scheduler(tmp_path)
_add_skill(scheduler, "calendar", "foo")
ctx = ActionContext(engine=None, config={}, admin=scheduler)
request = Request("delete skill")
first = _delete_skill_act(ctx, request)
assert first.needs_input and "which skill" in first.needs_input.lower()
request.user_input = "calendar.foo"
second = _delete_skill_act(ctx, request)
assert second.needs_input and "confirm" in second.needs_input.lower()
request.user_input = "yes"
third = _delete_skill_act(ctx, request)
assert third.needs_input is None
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
def test_delete_skill_act_declined_keeps_skill(tmp_path):
scheduler = _scheduler(tmp_path)
_add_skill(scheduler, "calendar", "foo")
ctx = ActionContext(engine=None, config={}, admin=scheduler)
request = Request("delete skill calendar.foo")
_delete_skill_act(ctx, request)
request.user_input = "no"
result = _delete_skill_act(ctx, request)
assert result.needs_input is None
assert "cancelled" in result.action_log
assert any(s.name == "foo" for s in scheduler.tree["calendar"])
def test_cancel_build_act_targets_writing_skill(tmp_path):
scheduler = _scheduler(tmp_path)
skill = _add_skill(scheduler, "calendar", "foo")
skill.writing = True
ctx = ActionContext(engine=None, config={}, admin=scheduler)
request = Request("cancel the skill build")
first = _cancel_build_act(ctx, request)
assert first.needs_input and "cancel" in first.needs_input.lower()
request.user_input = "yes"
second = _cancel_build_act(ctx, request)
assert second.needs_input is None
assert all(s.name != "foo" for s in scheduler.tree["calendar"])
def test_cancel_build_act_reports_when_nothing_writing(tmp_path):
scheduler = _scheduler(tmp_path)
_add_skill(scheduler, "calendar", "foo")
ctx = ActionContext(engine=None, config={}, admin=scheduler)
result = _cancel_build_act(ctx, Request("cancel the skill build"))
assert result.needs_input is None
assert "no skill build" in result.action_log
+4 -2
View File
@@ -1064,7 +1064,7 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
guard sends dispatch to create_skill in the same category instead.""" guard sends dispatch to create_skill in the same category instead."""
scheduler = _scheduler( scheduler = _scheduler(
tmp_path, tmp_path,
choices={"same action": "different"}, choices={"top-level category": "simplex", "same action": "different"},
) )
scheduler.tree.pop("response", None) scheduler.tree.pop("response", None)
scheduler.tree["simplex"] = [ scheduler.tree["simplex"] = [
@@ -1083,7 +1083,9 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
def test_dispatch_intent_match_runs_skill(tmp_path): def test_dispatch_intent_match_runs_skill(tmp_path):
scheduler = _scheduler(tmp_path, choices={"same action": "same"}) scheduler = _scheduler(
tmp_path, choices={"top-level category": "simplex", "same action": "same"}
)
def act(ctx, request): def act(ctx, request):
return ActionResult(action_log="read the next message", new_state="read") return ActionResult(action_log="read the next message", new_state="read")
+6
View File
@@ -247,6 +247,12 @@ def test_adapter_ignores_empty_utterance():
assert seen == [] assert seen == []
def test_adapter_is_result_only():
# The spoken front end speaks only the skill's result line, not the
# scheduler's bookkeeping (overridable via gateway.voice.result_only).
assert VoiceAdapter({}).result_only is True
# ---- CLI wiring ------------------------------------------------------------ # ---- CLI wiring ------------------------------------------------------------