scheduler/gateway: carry skill identity structurally, not in action_log

Skill bodies prefixed their own `category.name` into `ActionResult.action_log`,
which duplicated the runner's deterministic summary prefix and leaked the name
into the text the gateways speak. Identity is not data for the output string.

- bodies (seeds, canned replies, housekeeping meta skills) write only the real
  result; the runner already owns the `category.name:` summary prefix
- `run_queue`/`submit_request`/`answer` now return a structured `SchedulerReply`
  (status, text, run_id, skill_ref, result); the gateway reads `skill_ref` and
  `result` from it instead of regex-parsing them back out of the summary
- drop the gateway's `_SKILL_REF`/`_LEADING_RUN_ID` parsing helpers
- fix a latent double-prefix when a failed run had an empty action_log
- CODEGEN.md: generated bodies must not prefix the skill name
This commit is contained in:
gabby committed 2026-10-07 00:30:37 +00:00
1 parent d0c1dccffd
commit e9a7fc73ee
22 files changed
+248 -200

No files matched your search

+20 -12
View File
@@ -435,6 +435,18 @@ def _print_approvals(scheduler: Scheduler) -> None:
print(f"[approval] {item['id']} new {item['kind']} {target}: {item['description']}")
def _print_reply(reply, show_run_id: bool = False) -> None:
"""Print a scheduler reply, optionally keeping its run id visible."""
label = f"[{reply.run_id}] " if (show_run_id and reply.run_id) else ""
print(f"[{reply.status}] {label}{reply.text}")
def _drain_queue(scheduler: Scheduler) -> None:
"""Run queued work, printing each outcome with its run id."""
for reply in scheduler.run_queue():
_print_reply(reply, show_run_id=True)
def _fatal_exit(scheduler: Scheduler) -> int | None:
"""If the scheduler hit a fatal engine failure, print it and return non-zero.
@@ -518,8 +530,7 @@ def repl(scheduler: Scheduler, config: dict) -> int:
print(f"[{status}] {detail}")
_answer_questions(scheduler)
_answer_approvals(scheduler)
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
continue
if lower.startswith("relabel "):
parts = line.split()
@@ -587,19 +598,16 @@ def repl(scheduler: Scheduler, config: dict) -> int:
scheduler.busy(line[5:].strip())
print("current process set (busy).")
continue
status, detail = scheduler.submit(line)
print(f"[{status}] {detail}")
_print_reply(scheduler.submit(line))
if _fatal_exit(scheduler) is not None:
return 1
while scheduler.pending is not None:
hint = "" if scheduler.pending.pre_act else " [leave empty to skip]"
answer = input(f"{scheduler.pending.question}{hint} ")
status, detail = scheduler.answer(answer)
print(f"[{status}] {detail}")
_print_reply(scheduler.answer(answer))
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
if _fatal_exit(scheduler) is not None:
return 1
_answer_questions(scheduler)
@@ -612,12 +620,12 @@ def scripted(scheduler: Scheduler, path: str) -> int:
print(try_warm(scheduler))
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
for row in rows:
status, detail = scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
print(f"[{status}] {detail}")
_print_reply(
scheduler.submit(str(row["text"]), source=row.get("source", "scripted"))
)
if _fatal_exit(scheduler) is not None:
return 1
for result_status, result_detail in scheduler.run_queue():
print(f"[{result_status}] {result_detail}")
_drain_queue(scheduler)
return _fatal_exit(scheduler) or 0
+4 -4
View File
@@ -255,13 +255,13 @@ class DashboardHandler(BaseHTTPRequestHandler):
with self.lock:
try:
body = self._read_json()
status, detail, request_id = self.scheduler.submit_request(
reply = self.scheduler.submit_request(
str(body.get("text", "")), source=str(body.get("source", "dashboard"))
)
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail, "request_id": request_id})
self._send(200, {"status": reply.status, "detail": reply.text, "request_id": reply.run_id})
return
if path == "/api/relabel":
with self.lock:
@@ -277,11 +277,11 @@ class DashboardHandler(BaseHTTPRequestHandler):
with self.lock:
try:
body = self._read_json()
status, detail = self.scheduler.answer(str(body.get("text", "")))
reply = self.scheduler.answer(str(body.get("text", "")))
except Exception as exc:
self._send_error(500, str(exc))
return
self._send(200, {"status": status, "detail": detail})
self._send(200, {"status": reply.status, "detail": reply.text})
return
if path == "/api/restart":
with self.lock:
+33 -45
View File
@@ -22,25 +22,16 @@ reaches the right chat.
from __future__ import annotations
import queue
import re
import threading
import time
from .base import InboundMessage, OutboundMessage
from .humanize import Humanizer
_LEADING_RUN_ID = re.compile(r"^\[[0-9a-f]{6,}\]\s*")
#: A result summary starts with the skill ref (`category.name:`), optionally
#: preceded by a `[resumed]` marker. Used to look up a skill's own config
#: (`data/skills/<cat>/<name>/config.json`) for a per-skill humanize override.
_SKILL_REF = re.compile(
r"^(?:\[resumed\]\s*)?([A-Za-z0-9_][A-Za-z0-9_-]*\.[A-Za-z0-9_][A-Za-z0-9_-]*):\s"
)
#: The scheduler's run summary wraps the real result as
#: `"<skill>: <ok|failed> — <detail>"`. A result-only platform (the voice
#: gateway) speaks just `<detail>`.
#: gateway) speaks just `<detail>`. Kept as a fallback for callers that hand
#: `_reply` a raw summary; the scheduler itself passes the unwrapped `result`.
_RESULT_SEP = " — "
_REPAIR_ACTIONS = {
@@ -69,21 +60,6 @@ _APPROVAL_ACTIONS = {
Target = tuple[str, str]
def _strip_run_id(text: str) -> str:
return _LEADING_RUN_ID.sub("", text or "")
def _skill_ref(text: str) -> str | None:
"""The `category.name` a result summary belongs to, or None."""
match = _SKILL_REF.match(text or "")
return match.group(1) if match else None
def _leading_run_id(text: str) -> str:
match = _LEADING_RUN_ID.match(text or "")
return match.group(0)[1:-2] if match else ""
def _result_detail(text: str) -> str:
"""Unwrap the scheduler's `"<skill>: <ok|failed> — <detail>"` summary.
@@ -311,10 +287,13 @@ class GatewayService:
if pending is not None and pending.request.source == self.source_for(
platform, msg.chat_id
):
status, detail = self.scheduler.answer(msg.text)
reply = self.scheduler.answer(msg.text)
if self.scheduler.pending is None:
self._pending_owner = None
self._reply(*reply_to, detail, kind=_reply_kind(status))
self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
elif pending is not None and self._pending_owner not in (None, reply_to):
self._reply(
*reply_to,
@@ -339,14 +318,17 @@ class GatewayService:
self._surfaced.add(approval_id)
self._reply(*reply_to, detail, kind="notice")
else:
status, detail, run_id = self.scheduler.submit_request(
reply = self.scheduler.submit_request(
msg.text, source=self.source_for(platform, msg.chat_id)
)
if run_id:
self._owners[run_id] = reply_to
if status == "needs_input":
if reply.run_id:
self._owners[reply.run_id] = reply_to
if reply.status == "needs_input":
self._pending_owner = reply_to
self._reply(*reply_to, detail, kind=_reply_kind(status))
self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
self.drain()
self.surface(origin=reply_to)
@@ -356,15 +338,16 @@ class GatewayService:
results = self.scheduler.run_queue()
if not results:
break
for status, detail in results:
run_id = _leading_run_id(detail)
owner = self._owner_of(run_id)
text = _strip_run_id(detail)
if status == "needs_input" and owner:
for reply in results:
owner = self._owner_of(reply.run_id)
if reply.status == "needs_input" and owner:
self._pending_owner = owner
target = owner or self._fallback_target()
if target:
self._reply(*target, text, kind=_reply_kind(status))
self._reply(
*target, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result,
)
def surface(self, origin: Target | None = None) -> None:
"""Send any newly posted authoring questions / repair offers."""
@@ -474,11 +457,15 @@ class GatewayService:
trace.append(kind, "?", **fields)
def _reply(
self, platform: str, chat_id: str, text: str, kind: str = "reply"
self,
platform: str,
chat_id: str,
text: str,
kind: str = "reply",
skill_ref: str | None = None,
result: str | None = None,
) -> None:
text = _strip_run_id(text)
result_only = self._result_only(platform)
skill_ref = _skill_ref(text) if kind == "result" else None
humanize = kind == "result" and self._humanize_enabled(platform, skill_ref)
if result_only:
# A spoken front end says the skill's result, not the scheduler's
@@ -486,9 +473,10 @@ class GatewayService:
if kind == "status":
return
if kind == "result" and (result_only or humanize):
# Unwrap `<skill>: <ok|failed> — <detail>` to the skill's own
# result before optionally cleaning it up.
text = _result_detail(text)
# The scheduler hands us the skill's own unwrapped detail; fall back
# to unwrapping `<skill>: <ok|failed> — <detail>` for raw-string
# callers.
text = result if result is not None else _result_detail(text)
if humanize:
started = time.time()
text = self.humanizer.humanize(text)
+72 -30
View File
@@ -196,6 +196,29 @@ class DispatchResult:
skill: str | None = None
decisions_logged: int = 0
needs_input: str | None = None
#: `category.name` when a skill produced the outcome, else None. Carried
#: structurally so front ends never parse it back out of `summary`.
skill_ref: str | None = None
#: The skill's own detail (its `action_log`, or `new_state` when empty) —
#: the unwrapped result a `result_only` front end speaks.
result: str | None = None
@dataclass
class SchedulerReply:
"""One scheduler outcome as a structured reply.
`text` is the human-facing summary (e.g. ``"time.now: ok — 12:00"``). The
machine-readable fields a front end needs — the run id, the skill ref, and
the skill's own unwrapped detail — ride alongside it instead of being
parsed back out of `text`.
"""
status: str
text: str
run_id: str = ""
skill_ref: str | None = None
result: str | None = None
class Scheduler:
@@ -320,15 +343,12 @@ class Scheduler:
# ---- intake ----
def submit(self, text: str, source: str = "typed") -> tuple[str, str]:
"""Feed one input. Returns (status, detail)."""
status, detail, _ = self.submit_request(text, source)
return status, detail
def submit(self, text: str, source: str = "typed") -> SchedulerReply:
"""Feed one input. Returns the structured reply."""
return self.submit_request(text, source)
def submit_request(
self, text: str, source: str = "typed"
) -> tuple[str, str, str]:
"""Feed one input, also returning the request id.
def submit_request(self, text: str, source: str = "typed") -> SchedulerReply:
"""Feed one input, returning the request id on the reply.
The id lets out-of-band interfaces (the messenger gateway) map a run
back to the chat that originated it. The decision engine is real, so an
@@ -337,13 +357,13 @@ class Scheduler:
try:
return self._submit(text, source)
except EngineUnavailable as exc:
return "fatal", self._mark_fatal(exc), ""
return SchedulerReply("fatal", self._mark_fatal(exc))
def _submit(self, text: str, source: str = "typed") -> tuple[str, str, str]:
def _submit(self, text: str, source: str = "typed") -> SchedulerReply:
with self._lock:
return self._submit_locked(text, source)
def _submit_locked(self, text: str, source: str = "typed") -> tuple[str, str, str]:
def _submit_locked(self, text: str, source: str = "typed") -> SchedulerReply:
request = Request(text, source=source)
self.trace.append("submit", request.id, text=text, source=source)
@@ -355,16 +375,22 @@ class Scheduler:
if self.pending is None:
self.current = None
if outcome.kind == "needs_input":
return "needs_input", outcome.summary, request.id
return SchedulerReply(
"needs_input", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary)
return "running", outcome.summary, request.id
return SchedulerReply(
"running", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
ok = self.queue.push(request)
if not ok:
self.trace.append("rejected", request.id, reason="queue is full")
return "rejected", "queue is full", request.id
return SchedulerReply("rejected", "queue is full", request.id)
self.trace.append("queued", request.id)
return "queued", "queued", request.id
return SchedulerReply("queued", "queued", request.id)
def busy(self, text: str, skill: str = "(driving)") -> None:
"""Set a fake in-progress process so the queue path is exercised."""
@@ -381,8 +407,8 @@ class Scheduler:
self.pending = None
self.current = None
def run_queue(self) -> list[tuple[str, str]]:
"""Process the queue while idle. Returns the outcomes.
def run_queue(self) -> list[SchedulerReply]:
"""Process the queue while idle. Returns the structured outcomes.
Safe to call from any thread: guarded by the scheduler lock (RLock, so
the async codegen worker can drain the queue from its completion path).
@@ -390,7 +416,7 @@ class Scheduler:
with self._lock:
return self._run_queue_locked()
def _run_queue_locked(self) -> list[tuple[str, str]]:
def _run_queue_locked(self) -> list[SchedulerReply]:
results = []
while self.current is None and len(self.queue) > 0:
if self._fatal is not None:
@@ -402,7 +428,7 @@ class Scheduler:
outcome = self._dispatch(request)
except EngineUnavailable as exc:
self._mark_fatal(exc)
results.append(("fatal", self._fatal))
results.append(SchedulerReply("fatal", self._fatal))
break
except Exception as exc:
self.trace.append("error", request.id, phase="dispatch", message=str(exc))
@@ -411,10 +437,20 @@ class Scheduler:
if self.pending is None:
self.current = None
if outcome.kind == "needs_input":
results.append(("needs_input", f"[{request.id}] {outcome.summary}"))
results.append(
SchedulerReply(
"needs_input", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
)
continue
self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary)
results.append(("ran", f"[{request.id}] {outcome.summary}"))
results.append(
SchedulerReply(
"ran", outcome.summary, request.id,
outcome.skill_ref, outcome.result,
)
)
return results
# ---- dispatch ----
@@ -595,7 +631,7 @@ class Scheduler:
outcome = self.runner.run(skill, request)
return self._finish_run(skill, request, outcome)
def answer(self, text: str) -> tuple[str, str]:
def answer(self, text: str) -> SchedulerReply:
"""Feed the human's answer to a run paused for input.
Routed directly to the pending run — no gate, score, or navigation —
@@ -606,7 +642,7 @@ class Scheduler:
"""
with self._lock:
if self.pending is None:
return "error", "no run is waiting for input"
return SchedulerReply("error", "no run is waiting for input")
pending = self.pending
self.pending = None
pending.request.user_input = text
@@ -621,10 +657,16 @@ class Scheduler:
)
result = self._finish_run(pending.skill, pending.request, outcome)
if result.kind == "needs_input":
return "needs_input", result.summary
return SchedulerReply(
"needs_input", result.summary, pending.request.id,
result.skill_ref, result.result,
)
self.current = None
self.trace.append("ran", pending.request.id, skill=result.skill, summary=result.summary)
return "ran", f"[resumed] {result.summary}"
return SchedulerReply(
"ran", f"[resumed] {result.summary}", pending.request.id,
result.skill_ref, result.result,
)
def _finish_run(self, skill: Skill, request: Request, outcome) -> DispatchResult:
if outcome.error:
@@ -649,6 +691,8 @@ class Scheduler:
summary=outcome.needs_input,
skill=skill.name,
needs_input=outcome.needs_input,
skill_ref=f"{skill.category}.{skill.name}",
result=outcome.action_log or outcome.new_state or None,
)
self.trace.append(
"assessed",
@@ -672,13 +716,11 @@ class Scheduler:
self._propose_repair(skill, request, outcome)
return DispatchResult(
kind="ran",
summary=(
f"{skill.category}.{skill.name}: "
f"{'ok' if outcome.success else 'failed'} — "
f"{outcome.action_log or outcome.summary}"
),
summary=outcome.summary,
skill=skill.name,
decisions_logged=outcome.decisions_logged,
skill_ref=f"{skill.category}.{skill.name}",
result=(outcome.action_log or outcome.new_state or None),
)
# ---- repair loop ----
+23 -23
View File
@@ -586,7 +586,7 @@ def _canned_response(name: str, message: str):
"""An act that returns a fixed line. No transport, no generation, no config."""
def act(ctx: ActionContext, request: Request) -> ActionResult:
return ActionResult(action_log=f"{name}: {message}", new_state=message)
return ActionResult(action_log=message, new_state=message)
return act
@@ -799,7 +799,7 @@ def _resolve_target(admin, request: Request):
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping: several skills match ({names}); "
f"several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
@@ -807,7 +807,7 @@ def _resolve_target(admin, request: Request):
answer = (request.user_input or "").strip()
if not answer:
return ActionResult(
action_log="housekeeping: awaiting skill name",
action_log="awaiting skill name",
new_state="awaiting target",
needs_input=_TARGET_QUESTION,
)
@@ -819,11 +819,11 @@ def _resolve_target(admin, request: Request):
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",
action_log=f"several skills match ({names}); be specific",
new_state="ambiguous",
)
return ActionResult(
action_log=f"housekeeping: no skill matches {answer!r}",
action_log=f"no skill matches {answer!r}",
new_state="not found",
)
@@ -831,7 +831,7 @@ def _resolve_target(admin, request: Request):
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")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
@@ -840,35 +840,35 @@ def _delete_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.delete_skill: awaiting confirmation for {ref}",
action_log=f"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}",
action_log=f"cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.delete_skill(category, name)
return ActionResult(f"housekeeping.delete_skill: {detail}", detail)
return ActionResult(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")
return ActionResult("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)
return ActionResult(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")
return ActionResult("no admin available", "error")
target = _resolve_target(admin, request)
if isinstance(target, ActionResult):
return target
@@ -877,19 +877,19 @@ def _regen_skill_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_regen") != ref:
request.meta["housekeeping_regen"] = ref
return ActionResult(
action_log=f"housekeeping.regen_skill: awaiting guidance for {ref}",
action_log=f"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)
return ActionResult(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")
return ActionResult("no admin available", "error")
writing = [
(category, skill.name)
for category, skills in admin.tree.items()
@@ -905,7 +905,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
names = ", ".join(f"{c}.{n}" for c, n in resolved)
return ActionResult(
action_log=(
f"housekeeping.cancel_build: several skills match ({names}); "
f"several skills match ({names}); "
"name one as category.skill"
),
new_state="ambiguous",
@@ -915,7 +915,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
category, name = resolved
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build is in progress for "
f"no build is in progress for "
f"{category}.{name}"
),
new_state="no build",
@@ -925,14 +925,14 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
category, name = writing[0]
elif not writing:
return ActionResult(
action_log="housekeeping.cancel_build: no skill build is in progress",
action_log="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",
action_log="awaiting skill name",
new_state="awaiting target",
needs_input="Which skill build should I cancel? Reply with its name.",
)
@@ -943,7 +943,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
else:
return ActionResult(
action_log=(
f"housekeeping.cancel_build: no build in progress matching "
f"no build in progress matching "
f"{answer!r}"
),
new_state="no build",
@@ -953,7 +953,7 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
if request.meta.get("housekeeping_confirm") != ref:
request.meta["housekeeping_confirm"] = ref
return ActionResult(
action_log=f"housekeeping.cancel_build: awaiting confirmation for {ref}",
action_log=f"awaiting confirmation for {ref}",
new_state="awaiting confirmation",
needs_input=(
f"Cancel the build for {ref} and delete its half-built leaf? "
@@ -962,11 +962,11 @@ def _cancel_build_act(ctx: ActionContext, request: Request) -> ActionResult:
)
if not _confirmed(request):
return ActionResult(
action_log=f"housekeeping.cancel_build: cancelled by user for {ref}",
action_log=f"cancelled by user for {ref}",
new_state="cancelled",
)
_status, detail = admin.cancel_skill_build(category, name)
return ActionResult(f"housekeeping.cancel_build: {detail}", detail)
return ActionResult(detail, detail)
def build_housekeeping_skills() -> list[Skill]: