diff --git a/.gitignore b/.gitignore index 936d65f..2a56077 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ __pycache__/ data/decisions.jsonl data/runs.jsonl data/categories.json +data/deleted_skills.json data/skills/ data/drafts/ .pytest_cache/ diff --git a/AGENTS.md b/AGENTS.md index 3a74153..2794e3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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` per question); a 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 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, to arbitrate the response/create boundary), create_category 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); resolve_skill_config / unresolved_variables drive the tiered 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 act(ctx, request) phase that returns ActionResult (its own 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 summary is deterministic (no generation), built from 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 answer on request.user_input; a 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` / `_skipped`; it is a human veto, not a decision row — the SemIf create doors 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//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): elicitation is on by default and asks implementation questions (which service/account, how to connect, where the credential comes from, what success @@ -1182,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 up the stdlib HTTP server on an ephemeral port with the engine never loaded; `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` drives scheduling mechanics (assessment is now a SemIf decision) without a GGUF. diff --git a/semif_agent/cli.py b/semif_agent/cli.py index bcd3a6d..3d13f7f 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -38,11 +38,19 @@ from .trace import TraceLog 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 = { "skill_seeds": "seeds", "skill_bodies": "data/skills", "category_registry": "data/categories.json", + "deleted_skills": "data/deleted_skills.json", "log": "data/decisions.jsonl", "trace": "data/runs.jsonl", } @@ -446,6 +454,12 @@ def repl(scheduler: Scheduler, config: dict) -> int: "relabel | restart | " "repairs | repair [action] | approvals | quit" ) + print( + "housekeeping (slash-prefixed so plain requests still route by SemIf): " + "/delete | /clear-config | " + "/regen | /cancel-build | " + "/lock on|off" + ) while True: _answer_questions(scheduler) _answer_approvals(scheduler) @@ -504,6 +518,48 @@ def repl(scheduler: Scheduler, config: dict) -> int: status, detail = scheduler.restart_skill(parts[1], parts[2]) print(f"[{status}] {detail}") continue + if lower.startswith("/delete "): + parts = line.lstrip("/").split() + if len(parts) != 3: + print("usage: /delete ") + 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 ") + 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 ") + 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 ") + 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 on|off") + continue + status, detail = scheduler.set_category_lock( + parts[1], parts[2].lower() == "on" + ) + print(f"[{status}] {detail}") + continue if lower == "idle": scheduler.idle() print("current process cleared.") diff --git a/semif_agent/dashboard.py b/semif_agent/dashboard.py index 1536055..0c17950 100644 --- a/semif_agent/dashboard.py +++ b/semif_agent/dashboard.py @@ -143,13 +143,15 @@ def build_tree_payload(scheduler: Scheduler) -> dict: "name": skill.name, "description": skill.description, "status": skill.status, + "origin": skill.origin, "integration": skill.integration or None, "integration_source": skill.integration_source, } for skill in skills ] for category, skills in sorted(snapshot.items()) - } + }, + "locks": scheduler.category_locks(), } @@ -233,6 +235,9 @@ class DashboardHandler(BaseHTTPRequestHandler): if path == "/api/approvals": self._send(200, {"approvals": self.scheduler.pending_approvals()}) return + if path == "/api/locks": + self._send(200, {"locks": self.scheduler.category_locks()}) + return if path == "/api/timers": self._send( 200, @@ -328,8 +333,45 @@ class DashboardHandler(BaseHTTPRequestHandler): return self._send(200, {"status": status, "detail": detail}) 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") + 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): pass diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 494c5ab..4070fb8 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -15,6 +15,7 @@ import time import uuid from collections import deque from dataclasses import dataclass, field +from pathlib import Path from typing import Callable from .codegen import ( @@ -40,13 +41,19 @@ from .skill import SkillRunner from .timers import TimerService from .skills import ( CANNED_CATEGORIES, + DETERMINISTIC_CATEGORIES, + HARD_LOCKED_CATEGORIES, + HOUSEKEEPING_CATEGORY, ActionContext, CategoryRegistry, CreateCategory, CreateSkill, + DeletedSkills, Skill, SkillDraft, SkillStore, + apply_tombstones, + build_housekeeping_skills, build_skills, build_tree, confirm_skill_fit, @@ -57,6 +64,7 @@ from .skills import ( merge_seed_store, merge_skill_store, navigate, + parse_meta_command, ) from .trace import TraceLog @@ -101,6 +109,9 @@ class SkillWrite: draft: SkillDraft weight: float 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 @@ -255,16 +266,27 @@ class Scheduler: max_size=int(config.get("queue", {}).get("max_size", 100)), 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.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.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_seed_store(self.tree, self.seed_store, self.body_store) merge_skill_store(self.tree, self.body_store, self.registry.read()) + apply_tombstones(self.tree, self.deleted) 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.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_thread: threading.Thread | None = None 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_thread: threading.Thread | None = None self._question_notify = threading.Condition(self._lock) @@ -454,6 +479,25 @@ class Scheduler: # ---- dispatch ---- 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( self.engine, self.log, @@ -469,6 +513,12 @@ class Scheduler: return self._dispatch_skill(request, navigation.category, weight) if navigation.category in CANNED_CATEGORIES: 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( self.engine, self.log, self.trace, request, navigation, self.intent_tau ): @@ -478,6 +528,8 @@ class Scheduler: selected_skill=f"{navigation.category}.{navigation.name}", 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._run_skill(navigation, request) @@ -511,6 +563,8 @@ class Scheduler: A re-dispatched request whose skill is still unwritten must not author a 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") if pending is not None: 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//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: if skill.writing: return DispatchResult( @@ -651,7 +738,11 @@ class Scheduler: model the observed failure verbatim, never a paraphrase and never 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 evidence = { "error": outcome.error, @@ -1033,6 +1124,11 @@ class Scheduler: return self.registry.register(draft.name, draft.description) 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( "category_created", job.request.id, @@ -1053,6 +1149,14 @@ class Scheduler: if not self._request_approval(job, "skill", draft.name, draft.description): return 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, [])} if draft.name in existing: self.trace.append( @@ -1212,6 +1316,7 @@ class Scheduler: draft: SkillDraft, weight: float, repair_evidence: dict | None = None, + reason_kind: str = "run_failure", ) -> None: """Mark the leaf in-progress and queue the body write for the worker. @@ -1230,6 +1335,8 @@ class Scheduler: ) if leaf is None: return + # A fresh write clears any stale cancellation for this name. + self._cancelled.discard((category, draft.name)) leaf.writing = True contract = skill_contract_ref() self.trace.append( @@ -1250,6 +1357,7 @@ class Scheduler: draft=draft, weight=weight, repair_evidence=repair_evidence, + reason_kind=reason_kind, ) ) 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: return job = self._writes.popleft() + if self._consume_cancelled(job): + continue 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: """Run the full authoring pipeline for one queued write (no scheduler 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 stable view even if the main thread merges another skill meanwhile. """ + if self._is_cancelled(job.category, job.draft.name): + return with self._lock: tree_snapshot = {category: list(skills) for category, skills in self.tree.items()} if job.repair_evidence is None and not job.draft.requirements: @@ -1306,7 +1436,7 @@ class Scheduler: job.draft, self._read_body(job.category, job.draft.name), evidence, - reason_kind="run_failure", + reason_kind=job.reason_kind, ) else: code = generate_skill_body( @@ -1331,6 +1461,8 @@ class Scheduler: except (CodegenError, ValueError) as exc: self._fail_skill_write(job, exc) 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_contract(job.category, job.draft.name, contract) try: @@ -1690,6 +1822,9 @@ class Scheduler: def _complete_skill_write(self, job: SkillWrite, code: str) -> None: """Materialize the body, hot-merge it into the tree, and re-dispatch the 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 try: skill = materialize_skill(job.draft, job.category, self.body_store) @@ -1738,8 +1873,31 @@ class Scheduler: ) 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: """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: leaf = next( (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}" if category in CANNED_CATEGORIES: 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: return "error", f"skill {category}.{name} is already being written" if self.codegen is None: @@ -1795,6 +1957,222 @@ class Scheduler: self.trace.append("skill_restarted", origin.id, category=category, skill=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: with self._lock: lines = [] diff --git a/semif_agent/skill.py b/semif_agent/skill.py index c7e8911..5cbdfa2 100644 --- a/semif_agent/skill.py +++ b/semif_agent/skill.py @@ -31,6 +31,7 @@ from .decisions import DecisionRequest, Option, Request from .log import DecisionLog from .skills import ( CANNED_CATEGORIES, + DETERMINISTIC_CATEGORIES, ActionContext, Skill, SkillStore, @@ -118,7 +119,12 @@ class SkillRunner: merged = {**self.ctx.config} merged.update(skill.config or {}) 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]: if not skill.contract: @@ -345,7 +351,7 @@ class SkillRunner: self, skill: Skill, request: Request, ctx: ActionContext, action ) -> RunResult: 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( skill.category, skill.name, True, action.action_log, observed ) diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 05e3fb2..7e314ca 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -16,6 +16,7 @@ import importlib.util import json import os import re +import shutil from dataclasses import dataclass, field from pathlib import Path from typing import Callable @@ -43,6 +44,10 @@ class ActionContext: engine: SemIfEngine config: dict 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: @@ -62,6 +67,11 @@ class Skill: integration: dict = field(default_factory=dict) integration_source: str = "unknown" 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: """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.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: """Persists one skill leaf as a folder of deliverables. @@ -264,6 +291,78 @@ class SkillStore: skills.append((category_dir.name, entry.name)) 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"): """Import a persisted skill body and return its module.""" @@ -333,6 +432,7 @@ def materialize_skill( contract=contract, integration=integration, integration_source=integration_source, + origin="generated", ) @@ -378,6 +478,7 @@ def merge_skill_store( integration=integration, integration_source=integration_source, category_description=category_description, + origin="generated", ) skills = tree.setdefault(category, []) for index, existing in enumerate(skills): @@ -433,6 +534,7 @@ def merge_seed_store( integration=integration, integration_source=integration_source, category_description=CATEGORY_DESCRIPTIONS.get(category, ""), + origin="seed", ) skills = tree.setdefault(category, []) for index, existing in enumerate(skills): @@ -495,6 +597,19 @@ def _canned_response(name: str, message: str): CANNED_CATEGORIES = frozenset({"response"}) 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 = [ ( "greeting", @@ -553,6 +668,10 @@ CATEGORY_DESCRIPTIONS: dict[str, str] = { "Time and date utilities: telling the current time or date, setting " "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, act=_canned_response(f"response.{name}", message), category_description=CATEGORY_DESCRIPTIONS["response"], + origin="builtin", ) 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"(? dict[str, str]: """The description to offer for each category, best-effort. @@ -934,7 +1414,8 @@ def confirm_non_action( "action", "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 " - "yet).", + "yet), or gives a command to manage a skill (delete, clear config, " + "regenerate, cancel a build).", ), Option( "non_action", diff --git a/semif_agent/static/app.js b/semif_agent/static/app.js index 1412fc6..dd8f6d1 100644 --- a/semif_agent/static/app.js +++ b/semif_agent/static/app.js @@ -155,6 +155,18 @@ function eventRow(evt) { div.title = evt.message || ""; } else if (evt.kind === "skill_restarted") { 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") { div.textContent = "needs input"; div.title = evt.question || ""; @@ -497,6 +509,20 @@ function eventNode(evt) { node.appendChild(btn); } else if (evt.kind === "skill_restarted") { 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") { node.classList.add("needs-input"); body.textContent = `awaiting input: ${evt.question || ""}`; @@ -570,6 +596,43 @@ async function restartSkill(category, name) { 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) { try { const res = await getJSON("/api/questions", { @@ -640,6 +703,18 @@ function renderTree() { const name = document.createElement("div"); name.className = "cat-name"; 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); for (const skill of skills) { const row = document.createElement("div"); @@ -665,6 +740,30 @@ function renderTree() { row.appendChild(un); } 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); } el.appendChild(div); diff --git a/semif_agent/static/style.css b/semif_agent/static/style.css index 6860b5d..cb5ec0f 100644 --- a/semif_agent/static/style.css +++ b/semif_agent/static/style.css @@ -381,6 +381,13 @@ pre.json { 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 .stat { background: var(--panel-2); border-radius: 4px; padding: 4px 6px; } .stat-grid .stat .v { font-weight: 700; } diff --git a/tests/test_dashboard_api.py b/tests/test_dashboard_api.py index 47ea873..b2751f2 100644 --- a/tests/test_dashboard_api.py +++ b/tests/test_dashboard_api.py @@ -32,12 +32,36 @@ def build_scheduler(tmp_path, engine=None): engine=engine, llm=llm, 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, ) 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"): request = DecisionRequest( id=decision_id, @@ -131,6 +155,115 @@ def test_restart_without_codegen_returns_error_json(tmp_path): 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): server = Server(build_scheduler(tmp_path)) try: diff --git a/tests/test_housekeeping.py b/tests/test_housekeeping.py new file mode 100644 index 0000000..a0477ce --- /dev/null +++ b/tests/test_housekeeping.py @@ -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 diff --git a/tests/test_skills.py b/tests/test_skills.py index adbbd90..25a2762 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -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.""" scheduler = _scheduler( tmp_path, - choices={"same action": "different"}, + choices={"top-level category": "simplex", "same action": "different"}, ) scheduler.tree.pop("response", None) 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): - scheduler = _scheduler(tmp_path, choices={"same action": "same"}) + scheduler = _scheduler( + tmp_path, choices={"top-level category": "simplex", "same action": "same"} + ) def act(ctx, request): return ActionResult(action_log="read the next message", new_state="read")