add meta skills for housekeeping (delete skill, clear config, etc.)

This commit is contained in:
gabby committed 2026-10-06 08:40:50 +00:00
1 parent e8d1685177
commit 7ee200d921
12 files changed
+1771 -18

No files matched your search

+57 -1
View File
@@ -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 <id> <outcome> | restart <category> <skill> | "
"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:
_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 <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":
scheduler.idle()
print("current process cleared.")
+43 -1
View File
@@ -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
+383 -5
View File
@@ -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/<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:
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 = []
+8 -2
View File
@@ -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
)
+482 -1
View File
@@ -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"(?<![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]:
"""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",
+99
View File
@@ -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);
+7
View File
@@ -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; }