scheduler: new-skill creation is a tri-state allow/deny/ask mode

Replace the boolean creation_approval and the per-category boolean
locks.new_skill with a single tri-state new_skill_creation mode: a global
default (allow | deny | ask) with a per-category override in the category
config. allow authors immediately, deny blocks creation, ask gates on human
approval (the old approval path). housekeeping/response stay denied in code.

Surfaces updated: config.example.json, REPL /mode, dashboard
/api/new-skill-modes + /api/new-skill-mode, static UI. The retired booleans
creation_approval (true->ask) and locks.new_skill (true->deny) are still read
as fallbacks so an existing deployment keeps its behaviour.

Docs (AGENTS.md, docs/flow.md) and tests updated.
This commit is contained in:
gabby committed 2026-10-10 01:38:16 +00:00
1 parent 88700898be
commit c5ee87875f
11 files changed
+350 -160

No files matched your search

+7 -9
View File
@@ -452,8 +452,8 @@ def _print_repairs(scheduler: Scheduler) -> None:
def _answer_approvals(scheduler: Scheduler) -> None:
"""Ask any pending creation approvals at the REPL.
Only prompts when `creation_approval` is on (the scheduler posts nothing
otherwise). An empty answer denies.
Only prompts when a category (or the global default) uses the `ask` mode
(the scheduler posts nothing otherwise). An empty answer denies.
"""
while True:
pending = scheduler.pending_approvals()
@@ -539,7 +539,7 @@ def repl(scheduler: Scheduler, config: dict) -> int:
"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"
"/mode <category> allow|deny|ask"
)
while True:
_answer_questions(scheduler)
@@ -630,14 +630,12 @@ def repl(scheduler: Scheduler, config: dict) -> int:
status, detail = scheduler.cancel_skill_build(parts[1], parts[2])
print(f"[{status}] {detail}")
continue
if lower.startswith("/lock "):
if lower.startswith("/mode "):
parts = line.lstrip("/").split()
if len(parts) != 3 or parts[2].lower() not in ("on", "off"):
print("usage: /lock <category> on|off")
if len(parts) != 3 or parts[2].lower() not in ("allow", "deny", "ask"):
print("usage: /mode <category> allow|deny|ask")
continue
status, detail = scheduler.set_category_lock(
parts[1], parts[2].lower() == "on"
)
status, detail = scheduler.set_category_mode(parts[1], parts[2].lower())
print(f"[{status}] {detail}")
continue
if lower == "idle":
+6 -6
View File
@@ -151,7 +151,7 @@ def build_tree_payload(scheduler: Scheduler) -> dict:
]
for category, skills in sorted(snapshot.items())
},
"locks": scheduler.category_locks(),
"new_skill_modes": scheduler.category_modes(),
}
@@ -235,8 +235,8 @@ 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()})
if path == "/api/new-skill-modes":
self._send(200, {"modes": self.scheduler.category_modes()})
return
if path == "/api/timers":
self._send(
@@ -345,12 +345,12 @@ class DashboardHandler(BaseHTTPRequestHandler):
if path == "/api/cancel-build":
self._housekeeping("cancel_skill_build")
return
if path == "/api/lock":
if path == "/api/new-skill-mode":
with self.lock:
try:
body = self._read_json()
status, detail = self.scheduler.set_category_lock(
str(body.get("category", "")), bool(body.get("locked"))
status, detail = self.scheduler.set_category_mode(
str(body.get("category", "")), str(body.get("mode", ""))
)
except Exception as exc:
self._send_error(500, str(exc))
+145 -54
View File
@@ -69,6 +69,30 @@ from .skills import (
)
from .trace import TraceLog
#: The tri-state governing whether a new skill (or category) may be authored.
#: `allow` authors immediately, `deny` blocks creation outright, and `ask`
#: authors only after the human approves the proposal. Set globally with the
#: top-level `new_skill_creation` config value and overridden per category in
#: `data/skills/<category>/config.json` (same key).
NEW_SKILL_MODES = ("allow", "deny", "ask")
def normalize_new_skill_mode(value) -> str | None:
"""Coerce a configured new-skill mode to one of `NEW_SKILL_MODES`.
Accepts the mode strings and, for backward compatibility with the retired
`locks.new_skill` boolean, maps `True` -> "deny" and `False` -> "allow".
Returns None for anything unrecognized so the caller can fall back to the
next tier (category override, then the global default).
"""
if isinstance(value, bool):
return "deny" if value else "allow"
if isinstance(value, str):
mode = value.strip().lower()
if mode in NEW_SKILL_MODES:
return mode
return None
@dataclass
class Process:
@@ -173,10 +197,11 @@ class PendingApproval:
"""A proposed category/skill awaiting the human's yes/no.
Posted by the single-slot `llm` draft worker after the proposal is authored
and before anything is registered. `creation_approval` is off by default;
when on, a denial or timeout aborts creation (nothing registered, no body
written, the request is not re-dispatched). One prompt per creation request:
the category prompt covers its chained skill, so a new category asks once.
and before anything is registered. Only posted when the effective new-skill
mode is `ask` (the global default or a per-category override); a denial or
timeout aborts creation (nothing registered, no body written, the request is
not re-dispatched). One prompt per creation request: the category prompt
covers its chained skill, so a new category asks once.
"""
id: str
@@ -267,7 +292,14 @@ class Scheduler:
elicitation_cfg.get("answer_timeout", 30.0)
)
self.defer_questions = False
self.creation_approval = bool(config.get("creation_approval", False))
#: Global new-skill creation mode: "allow" (default), "deny", or "ask".
#: A category may override it in its category config. The retired
#: boolean `creation_approval` is still read as a fallback (True -> ask,
#: False -> allow) so an existing config keeps its behaviour.
self.new_skill_mode = (
normalize_new_skill_mode(config.get("new_skill_creation"))
or ("ask" if config.get("creation_approval") else "allow")
)
fidelity_cfg = codegen_cfg.get("fidelity", {}) or {}
self.fidelity_enabled = bool(fidelity_cfg.get("enabled", True))
self.fidelity_max_attempts = int(fidelity_cfg.get("max_attempts", 1))
@@ -487,6 +519,8 @@ class Scheduler:
bypass_tau=self.bypass_tau,
)
if isinstance(navigation, CreateCategory):
if self.new_skill_mode == "deny":
return self._blocked_create(request, None)
return self._dispatch_create_category(request)
if isinstance(navigation, CreateSkill):
return self._dispatch_skill(request, navigation.category)
@@ -568,36 +602,56 @@ class Scheduler:
),
)
# ---- new-skill locks (deterministic per-category create door) ----
# ---- new-skill creation modes (deterministic per-category create door) ----
def _category_locked(self, category: str) -> bool:
"""Is this category closed to new-skill creation?
def _category_mode(self, category: str) -> str:
"""Effective new-skill mode for a category: allow | deny | ask.
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
A deterministic gate, not a SemIf decision. The closed `response` tree
and the built-in `housekeeping` category are always `deny` (hard-locked
in code). Every other category reads `new_skill_creation` from its
category config (`data/skills/<category>/config.json`); when absent it
falls back to the global `new_skill_creation` mode. The retired boolean
`locks.new_skill` is still honored (True -> deny, False -> allow) so a
previously locked category never silently reopens. The mode 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
return "deny"
config = self.body_store.read_category_config(category) or {}
locks = config.get("locks") or {}
return bool(locks.get("new_skill", False))
mode = normalize_new_skill_mode(config.get("new_skill_creation"))
if mode is None:
mode = normalize_new_skill_mode(
(config.get("locks") or {}).get("new_skill")
)
return mode or self.new_skill_mode
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
)
def _category_locked(self, category: str) -> bool:
"""Is this category closed to new-skill creation (mode == deny)?"""
return self._category_mode(category) == "deny"
def _blocked_create(
self, request: Request, category: str | None
) -> DispatchResult:
"""Report that a denied category (or a denied category creation) will
not author."""
if category is None:
self.trace.append("category_create_blocked", request.id)
return DispatchResult(
kind="error",
summary=(
"cannot create a new category: new-skill creation is denied "
'(set new_skill_creation to "allow" or "ask" in config.json)'
),
)
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)"
f'is denied (set new_skill_creation to "allow" or "ask" in '
f"data/skills/{category}/config.json, or globally in config.json)"
),
)
@@ -1138,10 +1192,10 @@ class Scheduler:
def _author_category(self, job: DraftAuthor) -> None:
"""Author a top-level category, then chain into its skill leaf.
When `creation_approval` is on, the human approves the proposed category
first; the chained skill is covered by that approval. An `llm` failure is
graceful: only the user is told, the request is not re-dispatched — the
decision engine stays the single fatal dependency.
When the global new-skill mode is `ask`, the human approves the proposed
category first; the chained skill is covered by that approval. An `llm`
failure is graceful: only the user is told, the request is not
re-dispatched — the decision engine stays the single fatal dependency.
"""
draft = generate_category(self.llm, job.request, self._tree_snapshot())
if not self._request_approval(job, "category", draft.name, draft.description):
@@ -1157,10 +1211,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).
# Seed the category config so the new-skill mode is discoverable and
# editable from the start. It records the mode in effect at creation
# (the global default), which the operator can then override.
self.body_store.write_category_config(
draft.name, {"locks": {"new_skill": False}}
draft.name, {"new_skill_creation": self.new_skill_mode}
)
self.trace.append(
"category_created",
@@ -1173,8 +1228,9 @@ class Scheduler:
def _author_skill(self, job: DraftAuthor) -> None:
"""Author a skill leaf stub, then launch the codegen body write.
When `creation_approval` is on, the human approves the proposed skill
(a chained skill inside an already-approved category skips this).
When the category's effective new-skill mode is `ask`, the human
approves the proposed skill (a chained skill inside an already-approved
category skips this).
"""
draft = generate_skill(
self.llm, job.request, job.category, self._tree_snapshot()
@@ -1243,25 +1299,49 @@ class Scheduler:
"The request was not re-dispatched."
)
# ---- creation approval (opt-in human veto on new categories/skills) ----
# ---- new-skill creation gate (allow / deny / ask) ----
def _request_approval(
self, job: DraftAuthor, kind: str, name: str, description: str
) -> bool:
"""Ask the human to approve a proposed creation. Returns True to proceed.
"""Resolve the creation gate for a proposed category/skill. True = proceed.
Off by default (`creation_approval`). When on, the single-slot `llm`
worker blocks here after the proposal is authored and before anything is
registered; the main gate stays free. One prompt per creation request —
a chained skill job (`job.approved`) is already covered by the category
The effective mode is the global `new_skill_mode` for a new category and
the category's own mode for a new skill (global default unless the
category config overrides it). `allow` returns immediately, `deny`
aborts, and `ask` blocks the single-slot `llm` worker here — after the
proposal is authored and before anything is registered — until the human
answers; the main gate stays free. One prompt per creation request: a
chained skill job (`job.approved`) is already covered by the category
approval. Denial or timeout aborts creation: nothing is registered, no
body is written, and the request is not re-dispatched. Without a
deferring front end there is nobody to answer, so it denies immediately
rather than stalling the worker.
deferring front end there is nobody to answer, so `ask` denies
immediately rather than stalling the worker.
"""
if not self.creation_approval or job.approved:
if job.approved:
return True
mode = (
self.new_skill_mode
if kind == "category"
else self._category_mode(job.category)
)
target = name if kind == "category" else f"{job.category}.{name}"
if mode == "allow":
return True
if mode == "deny":
# Normally blocked synchronously in dispatch; guard here too so an
# in-flight draft never registers under a deny.
if kind == "category":
self.trace.append("category_create_blocked", job.request.id)
else:
self.trace.append(
"skill_create_blocked", job.request.id, category=job.category
)
print(
f"[creation] {kind} {target} denied by new-skill mode; "
"creation aborted."
)
return False
if not self.defer_questions:
self.trace.append(
"creation_approval_skipped",
@@ -2176,31 +2256,42 @@ class Scheduler:
)
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."""
def set_category_mode(self, category: str, mode: str) -> tuple[str, str]:
"""Set a category's new-skill mode (`allow` | `deny` | `ask`).
Written to the category config (`new_skill_creation`); passing an empty
value clears the override so the category inherits the global mode.
"""
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"
f"{category} is a built-in category and is always denied"
)
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
# Drop the retired boolean lock so it cannot shadow the new mode.
config.pop("locks", None)
if mode:
normalized = normalize_new_skill_mode(mode)
if normalized is None:
return "error", (
f"invalid mode {mode!r}: expected one of "
f"{', '.join(NEW_SKILL_MODES)}"
)
config["new_skill_creation"] = normalized
else:
config.pop("new_skill_creation", None)
self.body_store.write_category_config(category, config)
effective = self._category_mode(category)
self.trace.append(
"category_lock_set", "?", category=category, new_skill=bool(locked)
"category_mode_set", "?", category=category, mode=effective
)
return "ok", (
f"{category} new-skill creation "
f"{'locked' if locked else 'unlocked'}"
)
return "ok", f"{category} new-skill creation is now {effective}"
def category_locks(self) -> dict[str, bool]:
def category_modes(self) -> dict[str, str]:
with self._lock:
return {category: self._category_locked(category) for category in self.tree}
return {category: self._category_mode(category) for category in self.tree}
def status(self) -> str:
with self._lock:
+21 -17
View File
@@ -163,8 +163,10 @@ function eventRow(evt) {
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 === "category_create_blocked") {
div.textContent = "new-category creation blocked";
} else if (evt.kind === "category_mode_set") {
div.textContent = `${evt.category} new-skill creation: ${evt.mode}`;
} else if (evt.kind === "needs_input") {
div.textContent = "needs input";
div.title = evt.question || "";
@@ -517,8 +519,10 @@ function eventNode(evt) {
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 === "category_create_blocked") {
body.textContent = "new-category creation blocked";
} else if (evt.kind === "category_mode_set") {
body.textContent = `${evt.category} new-skill creation: ${evt.mode}`;
} else if (evt.kind === "needs_input") {
node.classList.add("needs-input");
body.textContent = `awaiting input: ${evt.question || ""}`;
@@ -606,16 +610,16 @@ async function housekeepingAction(path, category, name) {
await refreshAll();
}
async function toggleLock(category, locked) {
async function setSkillMode(category, mode) {
try {
const res = await getJSON("/api/lock", {
const res = await getJSON("/api/new-skill-mode", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ category, locked }),
body: JSON.stringify({ category, mode }),
});
flash(`[${res.status}] ${res.detail}`);
} catch (err) {
flash(`lock failed: ${err.message}`);
flash(`mode change failed: ${err.message}`);
}
await refreshAll();
}
@@ -699,15 +703,15 @@ 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)
);
const mode = (state.tree.new_skill_modes || {})[cat];
if (mode !== undefined) {
const next = { allow: "ask", ask: "deny", deny: "allow" }[mode] || "allow";
const hint = {
allow: "new skills are created without asking; click to ask first",
ask: "new skills ask for approval; click to deny creation",
deny: "new-skill creation is denied; click to allow",
}[mode];
const lock = actionBtn(mode, hint, () => setSkillMode(cat, next));
lock.classList.add("lock-btn");
name.appendChild(lock);
}