async skill-body authoring: single-slot codegen worker, restart, re-dispatch
create_skill now authors the stub synchronously and returns immediately; the runnable body is written by a single-slot background worker (the gate stays free for new input). On success the body is materialized and hot-merged, the leaf's writing flag clears, and the original request is re-queued at its scored weight and re-runs navigation onto the new leaf. On failure the leaf stays a restartable stub and the user is notified. - scheduler: _dispatch_skill launches the async write instead of blocking; _run_skill guards writing/stub leaves (no silent no-op); restart_skill re-kicks a write for an empty not-in-progress leaf (reuses the stored request_text); RLock guards tree/queue/current across worker and main thread; awaiting_skill_body meta guard stops a re-dispatched request from authoring a second skill. - skills: Skill.writing + status/is_noop via module-level no-op sentinels; registry entries persist the originating request_text. - engine: call/generate serialized with a Lock so the worker's degeneration checks never race main-thread navigation/scoring on one llama.cpp context. - cli: restart <category> <skill> command; REPL drains the queue after input. - dashboard: POST /api/restart; /api/tree carries per-skill status; tree rows + skill_write_failed flow nodes get restart buttons; reads snapshotted. - tests: async end-to-end (real CodegenClient vs fake SSE endpoint), restart, loop guard, status derivation, dashboard endpoint/status; integration chain test rewritten to poll for async completion + assessed.
This commit is contained in:
1 parent
db35cb66dc
commit
87438c881a
11 files changed
+722
-108
No files matched your search
@@ -22,7 +22,10 @@ cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
|
||||
scheduler.py gate -> choice(tau) -> score -> queue; preempt + requeue;
|
||||
a skill run paused for input (needs_input) keeps `current`
|
||||
busy; `answer` routes straight to the pending run, bypassing
|
||||
gate/score/navigation
|
||||
gate/score/navigation; skill-body codegen is an ASYNC single-slot
|
||||
worker (stub authored sync, write queued, gate stays free, the
|
||||
original request is re-queued and re-runs the new leaf when the
|
||||
body lands)
|
||||
queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0
|
||||
skills.py tree + registry (email.compose, response.reject, tracking.check),
|
||||
navigation = SemIf choices per level (logged), create_category
|
||||
@@ -133,11 +136,15 @@ unit tests (24) + box integration tests (2).
|
||||
merged into the running tree as a leaf. Since Sep 2026 the leaf also gets a
|
||||
real runnable body: a larger OpenAI-compatible model (`codegen`, default
|
||||
`qwen38-iq3s`) writes `predict`/`act` code against `SKILL.md`, persisted to
|
||||
`data/skills/` and hot-loaded, then the newly created leaf is executed
|
||||
directly so the request that prompted creation is answered. A request that
|
||||
prompted a whole new category runs the same chain deterministically:
|
||||
`create_category` → `create_skill` → run. Authoring is still a single pass —
|
||||
validating/reusing written bodies across runs is future work.
|
||||
`data/skills/` and hot-loaded. Authoring is **asynchronous**: the stub is
|
||||
created and the gate freed immediately, the body write runs on a single-slot
|
||||
background worker, and once the body lands the request that prompted creation
|
||||
is re-queued and re-runs navigation onto the new leaf (an empty/in-progress
|
||||
leaf can be restarted via `restart <category> <skill>` or the dashboard). A
|
||||
request that prompted a whole new category runs the same chain
|
||||
deterministically: `create_category` → `create_skill` → async body →
|
||||
re-dispatch. Authoring is still a single pass — validating/reusing written
|
||||
bodies across runs is future work.
|
||||
- Queue persistence (durable across restarts).
|
||||
- Event/timer intake sources beyond typed input.
|
||||
- Concurrency: SemIf shared-state mode (`score_shared` / `SerialPrefixScorer`)
|
||||
@@ -278,17 +285,30 @@ unit tests (24) + box integration tests (2).
|
||||
as a module and its `predict`/`act` run in-process). The box is the intended
|
||||
target; treat the endpoint as trusted.
|
||||
- Flow in `scheduler._dispatch_skill`: small model authors title+description →
|
||||
trace `skill_writing` (dashboard shows title/description + a "writing skill
|
||||
body…" badge) → sync codegen write → `materialize_skill` → hot-merge into the
|
||||
tree → the new leaf runs directly so the request is answered. `create_category`
|
||||
stub registered + hot-merged into the tree (navigable immediately) → trace
|
||||
`skill_writing` (dashboard shows title/description + a "writing skill body…"
|
||||
badge) → the body write is queued to a **single-slot background worker** (the
|
||||
12G codegen model can't run twice), the gate stays free for new input → on
|
||||
success the body is materialized (`materialize_skill`), hot-merged, the
|
||||
leaf's `writing` flag clears, and the **original request is re-queued** at its
|
||||
scored weight and re-runs navigation onto the new leaf (`skill_requeued`). On
|
||||
failure (`CodegenError`/`ValueError`) the user is notified, the leaf stays a
|
||||
restartable stub, and the request is NOT re-dispatched. A re-dispatched
|
||||
request whose skill is still unwritten reports the pending write instead of
|
||||
authoring a second skill (`awaiting_skill_body` meta guard). `create_category`
|
||||
runs the same chain after authoring the category (`create_category` →
|
||||
`create_skill` → run). Codegen failure — including a request timeout — leaves
|
||||
a navigable stub and returns a graceful `create_skill` result; a timeout is
|
||||
raised as `CodegenError` by the client, never a raw `TimeoutError`. The
|
||||
default codegen timeout is 1200s (`cli.build_scheduler`); the box
|
||||
`config.json` sets `codegen.timeout: 3600` because qwen38-iq3s's card
|
||||
sampler writes routinely run 25–45 min. Raise `codegen.timeout` in config
|
||||
for harder prompts.
|
||||
`create_skill` → async body → re-dispatch). An empty (stub) or in-progress
|
||||
leaf picked by navigation is reported gracefully — no silent no-op; restart it
|
||||
with the `restart <category> <skill>` REPL command or the dashboard button on
|
||||
the skill row / `skill_write_failed` flow node. Codegen failure — including a
|
||||
request timeout — is raised as `CodegenError` by the client, never a raw
|
||||
`TimeoutError`. The default codegen timeout is 1200s
|
||||
(`cli.build_scheduler`); the box `config.json` sets `codegen.timeout: 3600`
|
||||
because qwen38-iq3s's card sampler writes routinely run 25–45 min. Raise
|
||||
`codegen.timeout` in config for harder prompts.
|
||||
- Engine calls are serialized with a `threading.Lock` inside `SemIfEngine` so
|
||||
the codegen worker's degeneration SemIf checks never race main-thread
|
||||
navigation/scoring on one llama.cpp context.
|
||||
- Set `codegen.stream: true` to echo the codegen output as an SSE token stream
|
||||
to stdout during body writes — including the chain-of-thought, so a long
|
||||
(~30 min) write shows live progress. The client reads reasoning from either
|
||||
|
||||
+11
-1
@@ -142,7 +142,7 @@ def try_warm(scheduler: Scheduler) -> str:
|
||||
|
||||
def repl(scheduler: Scheduler, config: dict) -> None:
|
||||
print(try_warm(scheduler))
|
||||
print("type a request, or one of: busy <text> | idle | status | skills | dream | relabel <id> <outcome> | quit")
|
||||
print("type a request, or one of: busy <text> | idle | status | skills | dream | relabel <id> <outcome> | restart <category> <skill> | quit")
|
||||
while True:
|
||||
try:
|
||||
line = input("> ").strip()
|
||||
@@ -171,6 +171,14 @@ def repl(scheduler: Scheduler, config: dict) -> None:
|
||||
ok = scheduler.log.relabel(parts[1], parts[2])
|
||||
print("relabeled." if ok else f"no row with id {parts[1]}")
|
||||
continue
|
||||
if lower.startswith(("restart ", "/restart ")):
|
||||
parts = line.lstrip("/").split()
|
||||
if len(parts) != 3:
|
||||
print("usage: restart <category> <skill>")
|
||||
continue
|
||||
status, detail = scheduler.restart_skill(parts[1], parts[2])
|
||||
print(f"[{status}] {detail}")
|
||||
continue
|
||||
if lower == "idle":
|
||||
scheduler.idle()
|
||||
print("current process cleared.")
|
||||
@@ -185,6 +193,8 @@ def repl(scheduler: Scheduler, config: dict) -> None:
|
||||
answer = input(f"{scheduler.pending.question} ")
|
||||
status, detail = scheduler.answer(answer)
|
||||
print(f"[{status}] {detail}")
|
||||
for result_status, result_detail in scheduler.run_queue():
|
||||
print(f"[{result_status}] {result_detail}")
|
||||
|
||||
|
||||
def scripted(scheduler: Scheduler, path: str) -> None:
|
||||
|
||||
@@ -93,6 +93,7 @@ def build_dream_report(scheduler: Scheduler) -> dict:
|
||||
|
||||
|
||||
def build_status(scheduler: Scheduler) -> dict:
|
||||
with scheduler._lock:
|
||||
current = (
|
||||
{"skill": scheduler.current.skill, "request_id": scheduler.current.request.id}
|
||||
if scheduler.current
|
||||
@@ -107,21 +108,33 @@ def build_status(scheduler: Scheduler) -> dict:
|
||||
{"id": request.id, "weight": weight, "text": request.text[:80]}
|
||||
for weight, request in scheduler.queue.items()
|
||||
]
|
||||
tau = scheduler.tau
|
||||
queue_max = scheduler.queue.max_size
|
||||
return {
|
||||
"current": current,
|
||||
"pending": pending,
|
||||
"queue": queue,
|
||||
"tau": scheduler.tau,
|
||||
"queue_max": scheduler.queue.max_size,
|
||||
"tau": tau,
|
||||
"queue_max": queue_max,
|
||||
}
|
||||
|
||||
|
||||
def build_tree_payload(scheduler: Scheduler) -> dict:
|
||||
tree = scheduler.tree
|
||||
with scheduler._lock:
|
||||
snapshot = {
|
||||
category: list(skills) for category, skills in scheduler.tree.items()
|
||||
}
|
||||
return {
|
||||
"categories": {
|
||||
category: [{"name": skill.name, "description": skill.description} for skill in skills]
|
||||
for category, skills in sorted(tree.items())
|
||||
category: [
|
||||
{
|
||||
"name": skill.name,
|
||||
"description": skill.description,
|
||||
"status": skill.status,
|
||||
}
|
||||
for skill in skills
|
||||
]
|
||||
for category, skills in sorted(snapshot.items())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -233,6 +246,18 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
||||
return
|
||||
self._send(200, {"status": status, "detail": detail})
|
||||
return
|
||||
if path == "/api/restart":
|
||||
with self.lock:
|
||||
try:
|
||||
body = self._read_json()
|
||||
status, detail = self.scheduler.restart_skill(
|
||||
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})
|
||||
return
|
||||
self._send_error(404, "no such endpoint")
|
||||
|
||||
def log_message(self, format, *args):
|
||||
|
||||
@@ -10,6 +10,7 @@ pinned GGUF available; elsewhere calls raise EngineUnavailable.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@@ -38,6 +39,7 @@ class SemIfEngine:
|
||||
self._model = None
|
||||
self._tokenizer = None
|
||||
self._metadata = None
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def _ensure_loaded(self) -> tuple:
|
||||
if self._model is not None:
|
||||
@@ -75,6 +77,7 @@ class SemIfEngine:
|
||||
return self._model is not None
|
||||
|
||||
def call(self, request: DecisionRequest) -> DecisionResult:
|
||||
with self._lock:
|
||||
model, tokenizer, metadata = self._ensure_loaded()
|
||||
from semif_phase1 import llamacpp_backend as backend
|
||||
|
||||
@@ -107,6 +110,7 @@ class SemIfEngine:
|
||||
backend), stopping at the tokenizer's eos token. The KV cache is cleared
|
||||
at the start, so interleaving scoring and generation on one model is safe.
|
||||
"""
|
||||
with self._lock:
|
||||
model, tokenizer, metadata = self._ensure_loaded()
|
||||
try:
|
||||
import numpy
|
||||
|
||||
+257
-68
@@ -7,6 +7,8 @@ state preserved; a deferred input is scored and queued by urgency.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from collections import deque
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
@@ -30,6 +32,7 @@ from .skills import (
|
||||
Prediction,
|
||||
Skill,
|
||||
SkillBodyStore,
|
||||
SkillDraft,
|
||||
build_skills,
|
||||
build_tree,
|
||||
compose_state,
|
||||
@@ -75,6 +78,16 @@ class PendingRun:
|
||||
question: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class SkillWrite:
|
||||
"""One queued async skill-body write (single-slot codegen worker)."""
|
||||
|
||||
request: Request
|
||||
category: str
|
||||
draft: SkillDraft
|
||||
weight: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class DispatchResult:
|
||||
kind: str # ran | create_category | create_skill | needs_input | error
|
||||
@@ -83,6 +96,7 @@ class DispatchResult:
|
||||
decisions_logged: int = 0
|
||||
body_written: bool = False
|
||||
needs_input: str | None = None
|
||||
draft: SkillDraft | None = None
|
||||
|
||||
|
||||
class Scheduler:
|
||||
@@ -122,6 +136,10 @@ class Scheduler:
|
||||
self.runner = SkillRunner(self.ctx, self.llm, self.log)
|
||||
self.current: Process | None = None
|
||||
self.pending: PendingRun | None = None
|
||||
self._lock = threading.RLock()
|
||||
self._writes: deque[SkillWrite] = deque()
|
||||
self._write_notify = threading.Condition(self._lock)
|
||||
self._write_thread: threading.Thread | None = None
|
||||
|
||||
# ---- decision templates (all real SemIf, all logged) ----
|
||||
|
||||
@@ -179,6 +197,10 @@ class Scheduler:
|
||||
return "error", f"decision engine unavailable: {exc}"
|
||||
|
||||
def _submit(self, text: str, source: str = "typed") -> tuple[str, str]:
|
||||
with self._lock:
|
||||
return self._submit_locked(text, source)
|
||||
|
||||
def _submit_locked(self, text: str, source: str = "typed") -> tuple[str, str]:
|
||||
request = Request(text, source=source)
|
||||
self.trace.append("submit", request.id, text=text, source=source)
|
||||
if not self._contains_request(request):
|
||||
@@ -189,7 +211,7 @@ class Scheduler:
|
||||
weight, label = self._score(request)
|
||||
self.current = Process(request=request, skill="(scheduling)", weight=weight)
|
||||
try:
|
||||
outcome = self._dispatch(request)
|
||||
outcome = self._dispatch(request, weight=weight)
|
||||
finally:
|
||||
if self.pending is None:
|
||||
self.current = None
|
||||
@@ -208,7 +230,7 @@ class Scheduler:
|
||||
self.queue.push(previous.request, previous.weight)
|
||||
self.current = Process(request=request, skill="(scheduling)", weight=1.0)
|
||||
self.trace.append("preempted", request.id, preempted=previous.skill)
|
||||
outcome = self._dispatch(request)
|
||||
outcome = self._dispatch(request, weight=1.0)
|
||||
if outcome.kind == "needs_input":
|
||||
return "preempted", f"interrupted {previous.skill}; {outcome.summary}"
|
||||
self.current = None
|
||||
@@ -225,19 +247,29 @@ class Scheduler:
|
||||
|
||||
def busy(self, text: str, skill: str = "(driving)") -> None:
|
||||
"""Set a fake in-progress process so the choice/score path is exercised."""
|
||||
with self._lock:
|
||||
if self.pending is not None:
|
||||
self.trace.append("pending_abandoned", self.pending.request.id)
|
||||
self.pending = None
|
||||
self.current = Process(request=Request(text, source="busy"), skill=skill, weight=1.0)
|
||||
|
||||
def idle(self) -> None:
|
||||
with self._lock:
|
||||
if self.pending is not None:
|
||||
self.trace.append("pending_abandoned", self.pending.request.id)
|
||||
self.pending = None
|
||||
self.current = None
|
||||
|
||||
def run_queue(self) -> list[tuple[str, str]]:
|
||||
"""Process the queue while idle. Returns the outcomes."""
|
||||
"""Process the queue while idle. Returns the 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).
|
||||
"""
|
||||
with self._lock:
|
||||
return self._run_queue_locked()
|
||||
|
||||
def _run_queue_locked(self) -> list[tuple[str, str]]:
|
||||
from .engine import EngineUnavailable
|
||||
|
||||
results = []
|
||||
@@ -246,7 +278,7 @@ class Scheduler:
|
||||
self.trace.append("dequeued", request.id)
|
||||
self.current = Process(request=request, skill="(scheduling)", weight=0.0)
|
||||
try:
|
||||
outcome = self._dispatch(request)
|
||||
outcome = self._dispatch(request, weight=0.0)
|
||||
except EngineUnavailable as exc:
|
||||
outcome = DispatchResult(kind="error", summary=f"engine unavailable: {exc}")
|
||||
except Exception as exc:
|
||||
@@ -264,35 +296,65 @@ class Scheduler:
|
||||
|
||||
# ---- dispatch ----
|
||||
|
||||
def _dispatch(self, request: Request) -> DispatchResult:
|
||||
def _dispatch(self, request: Request, weight: float = 0.0) -> DispatchResult:
|
||||
navigation = navigate(self.engine, self.log, self.trace, request, self.tree)
|
||||
if isinstance(navigation, CreateCategory):
|
||||
created = self._create_category(request)
|
||||
if created.kind != "create_category":
|
||||
return created
|
||||
return self._dispatch_skill(request, created.skill)
|
||||
return self._dispatch_skill(request, created.skill, weight)
|
||||
if isinstance(navigation, CreateSkill):
|
||||
return self._dispatch_skill(request, navigation.category)
|
||||
return self._dispatch_skill(request, navigation.category, weight)
|
||||
return self._run_skill(navigation, request)
|
||||
|
||||
def _dispatch_skill(self, request: Request, category: str) -> DispatchResult:
|
||||
"""create_skill in `category`, then run the new skill so the request is answered.
|
||||
def _dispatch_skill(
|
||||
self, request: Request, category: str, weight: float = 0.0
|
||||
) -> DispatchResult:
|
||||
"""create_skill in `category`, then launch an async body write.
|
||||
|
||||
The created leaf is executed directly, not via a re-dispatch that would
|
||||
re-run navigation on a tree that just changed.
|
||||
The stub is authored and registered synchronously so the leaf is
|
||||
navigable immediately; the runnable body is written in the background
|
||||
by the single-slot codegen worker. When the body lands, the original
|
||||
request is re-queued and re-runs navigation onto the new leaf. A
|
||||
re-dispatched request whose skill is still unwritten must not author a
|
||||
second skill — it reports the pending write instead.
|
||||
"""
|
||||
created = self._create_skill(request, category)
|
||||
if created.kind != "create_skill" or not created.body_written:
|
||||
return created
|
||||
skill = next(
|
||||
(s for s in self.tree.get(category, []) if s.name == created.skill),
|
||||
None,
|
||||
pending = request.meta.get("awaiting_skill_body")
|
||||
if pending is not None:
|
||||
category_pending, name = pending
|
||||
return DispatchResult(
|
||||
kind="create_skill",
|
||||
summary=(
|
||||
f"skill {category_pending}.{name} body still being written "
|
||||
f"or failed; restart it with `restart {category_pending} {name}`."
|
||||
),
|
||||
skill=name,
|
||||
)
|
||||
if skill is None:
|
||||
created = self._create_skill(request, category)
|
||||
if created.kind != "create_skill" or created.draft is None:
|
||||
return created
|
||||
self._start_skill_write(request, category, created.draft, weight)
|
||||
return created
|
||||
return self._run_skill(skill, request)
|
||||
|
||||
def _run_skill(self, skill: Skill, request: Request) -> DispatchResult:
|
||||
if skill.writing:
|
||||
return DispatchResult(
|
||||
kind="error",
|
||||
summary=(
|
||||
f"skill {skill.name} body is still being written; "
|
||||
"it will run when ready."
|
||||
),
|
||||
skill=skill.name,
|
||||
)
|
||||
if skill.is_noop():
|
||||
return DispatchResult(
|
||||
kind="error",
|
||||
summary=(
|
||||
f"skill {skill.name} has no body yet; restart it with "
|
||||
f"`restart {skill.category} {skill.name}`."
|
||||
),
|
||||
skill=skill.name,
|
||||
)
|
||||
outcome = self.runner.run(skill, request)
|
||||
return self._finish_run(skill, request, outcome)
|
||||
|
||||
@@ -302,6 +364,7 @@ class Scheduler:
|
||||
Routed directly to the pending run — no gate, score, or navigation —
|
||||
and the run resumes by re-invoking only `act` with the same prediction.
|
||||
"""
|
||||
with self._lock:
|
||||
if self.pending is None:
|
||||
return "error", "no run is waiting for input"
|
||||
pending = self.pending
|
||||
@@ -394,11 +457,12 @@ class Scheduler:
|
||||
def _create_skill(self, request: Request, category: str) -> DispatchResult:
|
||||
"""Author a new skill leaf with the decision model in generation mode.
|
||||
|
||||
The small model writes the title + description; a larger OpenAI-
|
||||
compatible model then writes the runnable body against SKILL.md. The
|
||||
stub is registered first so the leaf is navigable even if the body
|
||||
write fails; a successful write is merged into the tree as a runnable
|
||||
skill and executed directly by _dispatch_skill.
|
||||
The small model writes the title + description; the stub is registered
|
||||
and merged into the tree so the leaf is navigable immediately. If
|
||||
codegen is configured, the runnable body is written asynchronously (see
|
||||
_start_skill_write) and the request is re-dispatched once the body
|
||||
lands; the returned result carries the draft so _dispatch_skill can
|
||||
launch that write. Without codegen the stub is final.
|
||||
"""
|
||||
from .engine import EngineUnavailable
|
||||
|
||||
@@ -421,22 +485,12 @@ class Scheduler:
|
||||
summary=f"create_skill failed: {draft.name} already exists",
|
||||
)
|
||||
|
||||
self.registry.register_skill(category, draft.name, draft.description)
|
||||
self.registry.register_skill(
|
||||
category, draft.name, draft.description, request_text=request.text
|
||||
)
|
||||
self.tree.setdefault(category, []).append(
|
||||
Skill(name=draft.name, category=category, description=draft.description)
|
||||
)
|
||||
contract = skill_contract_ref()
|
||||
self.trace.append(
|
||||
"skill_writing",
|
||||
request.id,
|
||||
category=category,
|
||||
skill=draft.name,
|
||||
description=draft.description,
|
||||
model=self.codegen.model if self.codegen else None,
|
||||
contract_ref=contract["ref"],
|
||||
contract_dirty=contract["dirty"],
|
||||
)
|
||||
|
||||
if self.codegen is None:
|
||||
self.trace.append(
|
||||
"skill_created",
|
||||
@@ -452,61 +506,196 @@ class Scheduler:
|
||||
summary=f"created stub {category}.{draft.name}: {draft.description} (no codegen configured)",
|
||||
skill=draft.name,
|
||||
)
|
||||
return DispatchResult(
|
||||
kind="create_skill",
|
||||
summary=(
|
||||
f"created stub {category}.{draft.name}: {draft.description} — "
|
||||
"body writing in background; request will re-run when ready"
|
||||
),
|
||||
skill=draft.name,
|
||||
draft=draft,
|
||||
)
|
||||
|
||||
# ---- async skill-body writes (single-slot codegen worker) ----
|
||||
|
||||
def _start_skill_write(
|
||||
self, request: Request, category: str, draft: SkillDraft, weight: float
|
||||
) -> None:
|
||||
"""Mark the leaf in-progress and queue the body write for the worker.
|
||||
|
||||
The gate stays free: this returns immediately and the worker (one write
|
||||
at a time, the 12G codegen model can't run twice) writes the body in the
|
||||
background. On completion the original request is re-queued and re-runs
|
||||
navigation onto the new leaf; on failure the leaf stays a restartable
|
||||
stub and only the user is notified.
|
||||
"""
|
||||
with self._lock:
|
||||
leaf = next(
|
||||
(s for s in self.tree.get(category, []) if s.name == draft.name),
|
||||
None,
|
||||
)
|
||||
if leaf is None:
|
||||
return
|
||||
leaf.writing = True
|
||||
contract = skill_contract_ref()
|
||||
self.trace.append(
|
||||
"skill_writing",
|
||||
request.id,
|
||||
category=category,
|
||||
skill=draft.name,
|
||||
description=draft.description,
|
||||
model=self.codegen.model if self.codegen else None,
|
||||
contract_ref=contract["ref"],
|
||||
contract_dirty=contract["dirty"],
|
||||
)
|
||||
self._writes.append(
|
||||
SkillWrite(request=request, category=category, draft=draft, weight=weight)
|
||||
)
|
||||
if self._write_thread is None or not self._write_thread.is_alive():
|
||||
self._write_thread = threading.Thread(
|
||||
target=self._write_worker, name="skill-writer", daemon=True
|
||||
)
|
||||
self._write_thread.start()
|
||||
self._write_notify.notify()
|
||||
print(
|
||||
f"[codegen] queued body write for {category}.{draft.name}; "
|
||||
"it will run in the background and the request will re-run when ready."
|
||||
)
|
||||
|
||||
def _write_worker(self) -> None:
|
||||
"""Drain the skill-write queue one body at a time."""
|
||||
while True:
|
||||
with self._write_notify:
|
||||
while not self._writes:
|
||||
self._write_notify.wait()
|
||||
job = self._writes.popleft()
|
||||
self._write_skill_body(job)
|
||||
|
||||
def _write_skill_body(self, job: SkillWrite) -> None:
|
||||
"""Run codegen for one queued write (no scheduler lock held here).
|
||||
|
||||
The tree is snapshotted under the lock so the prompt build reads a
|
||||
stable view even if the main thread merges another skill meanwhile.
|
||||
"""
|
||||
with self._lock:
|
||||
tree_snapshot = {category: list(skills) for category, skills in self.tree.items()}
|
||||
try:
|
||||
draft.code = generate_skill_body(
|
||||
code = generate_skill_body(
|
||||
self.codegen,
|
||||
request,
|
||||
category,
|
||||
draft,
|
||||
self.tree,
|
||||
job.request,
|
||||
job.category,
|
||||
job.draft,
|
||||
tree_snapshot,
|
||||
degeneration_check=(
|
||||
self.degeneration_check_factory(request.id)
|
||||
self.degeneration_check_factory(job.request.id)
|
||||
if self.degeneration_check_factory is not None
|
||||
else None
|
||||
),
|
||||
)
|
||||
skill = materialize_skill(draft, category, self.body_store)
|
||||
except (CodegenError, ValueError) as exc:
|
||||
self.trace.append(
|
||||
"error",
|
||||
request.id,
|
||||
phase="create_skill",
|
||||
category=category,
|
||||
message=f"skill body write failed: {exc}",
|
||||
)
|
||||
return DispatchResult(
|
||||
kind="create_skill",
|
||||
summary=f"created stub {category}.{draft.name}: {draft.description} (body write failed: {exc})",
|
||||
skill=draft.name,
|
||||
)
|
||||
self._fail_skill_write(job, exc)
|
||||
return
|
||||
self._complete_skill_write(job, code)
|
||||
|
||||
skills = self.tree.setdefault(category, [])
|
||||
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."""
|
||||
job.draft.code = code
|
||||
try:
|
||||
skill = materialize_skill(job.draft, job.category, self.body_store)
|
||||
except ValueError as exc:
|
||||
self._fail_skill_write(job, exc)
|
||||
return
|
||||
with self._lock:
|
||||
skills = self.tree.setdefault(job.category, [])
|
||||
for index, existing in enumerate(skills):
|
||||
if existing.name == draft.name:
|
||||
if existing.name == job.draft.name:
|
||||
skills[index] = skill
|
||||
break
|
||||
else:
|
||||
skills.append(skill)
|
||||
skills.sort(key=lambda s: s.name)
|
||||
body_path = self.body_store.body_path(category, draft.name).as_posix()
|
||||
body_path = self.body_store.body_path(job.category, job.draft.name).as_posix()
|
||||
self.trace.append(
|
||||
"skill_created",
|
||||
request.id,
|
||||
category=category,
|
||||
skill=draft.name,
|
||||
description=draft.description,
|
||||
job.request.id,
|
||||
category=job.category,
|
||||
skill=job.draft.name,
|
||||
description=job.draft.description,
|
||||
body=body_path,
|
||||
written=True,
|
||||
)
|
||||
return DispatchResult(
|
||||
kind="create_skill",
|
||||
summary=f"created skill {category}.{draft.name}: {draft.description}",
|
||||
skill=draft.name,
|
||||
body_written=True,
|
||||
requeued = job.request.copy_for_requeue()
|
||||
requeued.meta["awaiting_skill_body"] = [job.category, job.draft.name]
|
||||
requeued.meta["parent_run"] = job.request.id
|
||||
self.queue.push(requeued, job.weight)
|
||||
self.trace.append(
|
||||
"skill_requeued",
|
||||
job.request.id,
|
||||
text=requeued.text,
|
||||
weight=job.weight,
|
||||
)
|
||||
print(
|
||||
f"[codegen] body ready for {job.category}.{job.draft.name}; "
|
||||
"original request re-queued."
|
||||
)
|
||||
self.run_queue()
|
||||
|
||||
def _fail_skill_write(self, job: SkillWrite, exc: Exception) -> None:
|
||||
"""Clear the in-progress flag and notify; the leaf stays a restartable stub."""
|
||||
with self._lock:
|
||||
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
|
||||
self.trace.append(
|
||||
"skill_write_failed",
|
||||
job.request.id,
|
||||
category=job.category,
|
||||
skill=job.draft.name,
|
||||
message=str(exc),
|
||||
)
|
||||
print(
|
||||
f"[codegen] body write for {job.category}.{job.draft.name} FAILED: {exc}. "
|
||||
f"The leaf is a stub — restart it with `restart {job.category} {job.draft.name}`."
|
||||
)
|
||||
|
||||
def restart_skill(self, category: str, name: str) -> tuple[str, str]:
|
||||
"""Kick off (or re-kick) the body write for an empty not-in-progress 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.writing:
|
||||
return "error", f"skill {category}.{name} is already being written"
|
||||
if self.codegen is None:
|
||||
return "error", "no codegen configured"
|
||||
entry = self.registry.read().get(category, {})
|
||||
row = next(
|
||||
(s for s in entry.get("skills", []) if s.get("name") == name),
|
||||
{},
|
||||
)
|
||||
request_text = row.get("request_text")
|
||||
draft = SkillDraft(
|
||||
name=name,
|
||||
description=leaf.description or row.get("description") or name,
|
||||
)
|
||||
origin = (
|
||||
Request(request_text, source="restart")
|
||||
if request_text
|
||||
else Request(f"write the body for {category}.{name}: {draft.description}", source="restart")
|
||||
)
|
||||
self._start_skill_write(origin, category, draft, 0.5)
|
||||
self.trace.append("skill_restarted", origin.id, category=category, skill=name)
|
||||
return "running", f"restarting body write for {category}.{name}"
|
||||
|
||||
def status(self) -> str:
|
||||
with self._lock:
|
||||
lines = []
|
||||
current = f"{self.current.skill} ({self.current.request.id})" if self.current else "idle"
|
||||
lines.append(f"current: {current}")
|
||||
|
||||
+37
-6
@@ -48,6 +48,14 @@ class ActionContext:
|
||||
config: dict
|
||||
|
||||
|
||||
def _noop_predict(ctx: ActionContext, request: Request) -> Prediction:
|
||||
return Prediction(text="")
|
||||
|
||||
|
||||
def _noop_act(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
|
||||
return ActionResult("", "")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Skill:
|
||||
name: str
|
||||
@@ -55,11 +63,25 @@ class Skill:
|
||||
description: str
|
||||
cost_budget: float = 1.0
|
||||
predict: Callable[[ActionContext, Request], Prediction] = field(
|
||||
default=lambda ctx, req: Prediction(text="")
|
||||
default=_noop_predict
|
||||
)
|
||||
act: Callable[[ActionContext, Request, Prediction], ActionResult] = field(
|
||||
default=lambda ctx, req, pred: ActionResult("", "")
|
||||
default=_noop_act
|
||||
)
|
||||
writing: bool = False
|
||||
|
||||
def is_noop(self) -> bool:
|
||||
"""A stub leaf: authored (title + description) but no runnable body yet."""
|
||||
return self.predict is _noop_predict or self.act is _noop_act
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
"""Leaf readiness: `writing` (codegen in flight), `stub` (no body), `ready`."""
|
||||
if self.writing:
|
||||
return "writing"
|
||||
if self.is_noop():
|
||||
return "stub"
|
||||
return "ready"
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -122,13 +144,22 @@ class CategoryRegistry:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.path.write_text(json.dumps(categories, indent=2) + "\n")
|
||||
|
||||
def register_skill(self, category: str, name: str, description: str) -> None:
|
||||
"""Add a skill leaf to a category, creating the category entry if needed."""
|
||||
def register_skill(
|
||||
self, category: str, name: str, description: str, request_text: str = ""
|
||||
) -> None:
|
||||
"""Add a skill leaf to a category, creating the category entry if needed.
|
||||
|
||||
`request_text` is the originating request, kept so a later restart of the
|
||||
stub can re-drive codegen with the same context.
|
||||
"""
|
||||
categories = self.read()
|
||||
entry = categories.setdefault(category, {"description": "", "skills": []})
|
||||
skills = entry.setdefault("skills", [])
|
||||
if not any(s.get("name") == name for s in skills):
|
||||
skills.append({"name": name, "description": description})
|
||||
entry_row = next((s for s in skills if s.get("name") == name), None)
|
||||
if entry_row is None:
|
||||
skills.append({"name": name, "description": description, "request_text": request_text})
|
||||
else:
|
||||
entry_row["request_text"] = request_text
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.path.write_text(json.dumps(categories, indent=2) + "\n")
|
||||
|
||||
|
||||
@@ -129,6 +129,11 @@ function eventRow(evt) {
|
||||
} else if (evt.kind === "skill_created") {
|
||||
div.textContent = `created ${evt.skill}${evt.written ? " (body written)" : " (stub)"}`;
|
||||
div.title = evt.body || evt.description || "";
|
||||
} else if (evt.kind === "skill_write_failed") {
|
||||
div.textContent = `body write failed: ${evt.skill}`;
|
||||
div.title = evt.message || "";
|
||||
} else if (evt.kind === "skill_restarted") {
|
||||
div.textContent = `restarted body write: ${evt.skill}`;
|
||||
} else if (evt.kind === "needs_input") {
|
||||
div.textContent = "needs input";
|
||||
div.title = evt.question || "";
|
||||
@@ -378,6 +383,23 @@ function eventNode(evt) {
|
||||
node.appendChild(p);
|
||||
}
|
||||
node.classList.add(evt.written ? "ok" : "stub");
|
||||
} else if (evt.kind === "skill_write_failed") {
|
||||
node.classList.add("stub");
|
||||
const title = document.createElement("div");
|
||||
title.className = "skill-title";
|
||||
title.textContent = `${evt.skill} — body write failed`;
|
||||
body.appendChild(title);
|
||||
const msg = document.createElement("div");
|
||||
msg.className = "muted";
|
||||
msg.textContent = evt.message || "";
|
||||
body.appendChild(msg);
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "restart-btn";
|
||||
btn.textContent = "restart";
|
||||
btn.addEventListener("click", () => restartSkill(evt.category, evt.skill));
|
||||
node.appendChild(btn);
|
||||
} else if (evt.kind === "skill_restarted") {
|
||||
body.textContent = `restarted body write for ${evt.skill}`;
|
||||
} else if (evt.kind === "needs_input") {
|
||||
node.classList.add("needs-input");
|
||||
body.textContent = `awaiting input: ${evt.question || ""}`;
|
||||
@@ -434,6 +456,38 @@ function kv(k, v) {
|
||||
|
||||
/* ---------------- skill tree ---------------- */
|
||||
|
||||
async function restartSkill(category, name) {
|
||||
try {
|
||||
const res = await getJSON("/api/restart", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ category, skill: name }),
|
||||
});
|
||||
flash(`[${res.status}] ${res.detail}`);
|
||||
} catch (err) {
|
||||
flash(`restart failed: ${err.message}`);
|
||||
}
|
||||
await refreshAll();
|
||||
}
|
||||
|
||||
function skillStatusBadge(status, category, name) {
|
||||
const span = document.createElement("span");
|
||||
if (status === "writing") {
|
||||
span.className = "sbadge writing";
|
||||
span.textContent = "writing…";
|
||||
} else if (status === "stub") {
|
||||
span.className = "sbadge stub";
|
||||
span.textContent = "stub";
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "restart-btn";
|
||||
btn.textContent = "restart";
|
||||
btn.title = `write the body for ${category}.${name}`;
|
||||
btn.addEventListener("click", () => restartSkill(category, name));
|
||||
span.appendChild(btn);
|
||||
}
|
||||
return span;
|
||||
}
|
||||
|
||||
function renderTree() {
|
||||
const el = $("#skill-tree");
|
||||
el.innerHTML = "";
|
||||
@@ -455,6 +509,7 @@ function renderTree() {
|
||||
desc.textContent = skill.description;
|
||||
row.appendChild(nm);
|
||||
row.appendChild(desc);
|
||||
row.appendChild(skillStatusBadge(skill.status, cat, skill.name));
|
||||
div.appendChild(row);
|
||||
}
|
||||
el.appendChild(div);
|
||||
|
||||
@@ -324,6 +324,24 @@ pre.json {
|
||||
.skill-row { display: flex; gap: 6px; align-items: baseline; padding-left: 8px; font-size: 11px; }
|
||||
.skill-row .sdesc { color: var(--muted); }
|
||||
|
||||
.sbadge {
|
||||
margin-left: auto;
|
||||
font-size: 10px;
|
||||
white-space: nowrap;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.sbadge.writing { color: var(--warn); }
|
||||
.sbadge.stub { color: var(--muted); }
|
||||
|
||||
.restart-btn {
|
||||
padding: 1px 6px;
|
||||
font-size: 10px;
|
||||
border-radius: 4px;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.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; }
|
||||
|
||||
@@ -7,6 +7,7 @@ local LLM endpoint. If either is unavailable this fails loudly — no mocking.
|
||||
"""
|
||||
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -218,8 +219,10 @@ def test_create_category_chain_runs_new_skill(tmp_path):
|
||||
"""A request that needs a brand-new category must end with a skill run.
|
||||
|
||||
Deterministic chain: create_category -> create_skill in the new category ->
|
||||
run that skill (the leaf answers the request, not the category stub). Slow:
|
||||
uses real codegen (~7 min). Run in the background.
|
||||
async codegen body write -> re-dispatch of the original request -> run that
|
||||
skill (the leaf answers the request, not the category stub). Slow: uses real
|
||||
codegen (~25-45 min) and the worker runs in the background, so the test
|
||||
polls the trace for the completion + assessed events. Run in the background.
|
||||
"""
|
||||
config = load_config()
|
||||
require_real(config)
|
||||
@@ -233,13 +236,30 @@ def test_create_category_chain_runs_new_skill(tmp_path):
|
||||
|
||||
status, detail = scheduler.submit("track my drone delivery in real time")
|
||||
print(f"[{status}] {detail}")
|
||||
assert status in ("running", "preempted", "queued", "rejected")
|
||||
assert scheduler.current is None, "gate must be free again right after the stub is created"
|
||||
|
||||
rows = scheduler.trace.read()
|
||||
kinds = [e["kind"] for e in rows]
|
||||
kinds = [e["kind"] for e in scheduler.trace.read()]
|
||||
assert "category_created" in kinds, "category stub must be authored first"
|
||||
created = next(e for e in rows if e["kind"] == "skill_created")
|
||||
assert created["written"] is True, "codegen must produce a runnable body"
|
||||
assessed = next(e for e in rows if e["kind"] == "assessed")
|
||||
assert "skill_writing" in kinds, "the async body write must be launched"
|
||||
|
||||
deadline = time.monotonic() + 55 * 60
|
||||
created = assessed = None
|
||||
while time.monotonic() < deadline:
|
||||
rows = scheduler.trace.read()
|
||||
created = next((e for e in rows if e["kind"] == "skill_created"), None)
|
||||
if created and created.get("written"):
|
||||
assessed = next(
|
||||
(e for e in rows if e["kind"] == "assessed" and e.get("skill") == created["skill"]),
|
||||
None,
|
||||
)
|
||||
if assessed:
|
||||
break
|
||||
time.sleep(10)
|
||||
assert created is not None and created.get("written"), (
|
||||
"codegen must produce a runnable body"
|
||||
)
|
||||
assert assessed is not None, "the created skill must run after the body lands"
|
||||
assert assessed["skill"] == created["skill"], "the created skill must run"
|
||||
|
||||
|
||||
|
||||
@@ -87,6 +87,51 @@ def test_tree_endpoint(tmp_path):
|
||||
server.close()
|
||||
|
||||
|
||||
def test_tree_endpoint_carries_skill_status(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
return ActionResult(action_log="ok", new_state=request.text)
|
||||
|
||||
scheduler.tree["tracking"] = [
|
||||
Skill(name="ready", category="tracking", description="r", predict=predict, act=act),
|
||||
Skill(name="stub", category="tracking", description="s"),
|
||||
]
|
||||
stub = next(s for s in scheduler.tree["tracking"] if s.name == "stub")
|
||||
stub.writing = True
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.get("/api/tree")
|
||||
assert status == 200
|
||||
by_name = {s["name"]: s["status"] for s in payload["categories"]["tracking"]}
|
||||
assert by_name["ready"] == "ready"
|
||||
assert by_name["stub"] == "writing"
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def test_restart_without_codegen_returns_error_json(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
scheduler.tree["tracking"] = [
|
||||
Skill(name="track_live", category="tracking", description="Follow a package.")
|
||||
]
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.post("/api/restart", {"category": "tracking", "skill": "track_live"})
|
||||
assert status == 200
|
||||
assert payload["status"] == "error"
|
||||
assert "codegen" in payload["detail"]
|
||||
|
||||
status, payload = server.post("/api/restart", {"category": "tracking", "skill": "missing"})
|
||||
assert payload["status"] == "error"
|
||||
assert "no skill" in payload["detail"]
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def test_trace_endpoint_empty(tmp_path):
|
||||
server = Server(build_scheduler(tmp_path))
|
||||
try:
|
||||
|
||||
+202
-5
@@ -1,12 +1,21 @@
|
||||
"""Pure-stdlib tests for skill-tree authoring: category and skill prompts, draft
|
||||
parsing, the category registry, and the error path when the engine is unavailable.
|
||||
parsing, the category registry, the async codegen-body workflow, and the error
|
||||
path when the engine is unavailable.
|
||||
|
||||
No mocking: engine-dependent success paths are exercised only by the box
|
||||
integration tests against the real decision model.
|
||||
No mocking: the async write test uses a real CodegenClient against a throwaway
|
||||
stdlib HTTP server (real endpoint, per the repo rule); engine-dependent success
|
||||
paths are exercised only by the box integration tests against the real decision
|
||||
model.
|
||||
"""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
import pytest
|
||||
|
||||
from semif_agent.codegen import CodegenClient
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.engine import EngineConfig, EngineUnavailable, SemIfEngine
|
||||
from semif_agent.llm import LLMClient
|
||||
@@ -17,6 +26,7 @@ from semif_agent.skills import (
|
||||
CategoryDraft,
|
||||
CategoryRegistry,
|
||||
CreateCategory,
|
||||
Skill,
|
||||
SkillDraft,
|
||||
build_category_prompt,
|
||||
build_skill_prompt,
|
||||
@@ -32,6 +42,67 @@ from semif_agent.skills import (
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
|
||||
GOOD_BODY = """\
|
||||
from semif_agent.decisions import DecisionRequest, Option
|
||||
from semif_agent.skills import ActionResult, Prediction
|
||||
|
||||
def predict(ctx, request):
|
||||
return Prediction(text="ok", decisions=[])
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
return ActionResult(action_log="probe ran", new_state=request.text)
|
||||
"""
|
||||
|
||||
|
||||
def _fake_codegen_server() -> tuple[ThreadingHTTPServer, str]:
|
||||
"""Single-shot OpenAI-compatible SSE server standing in for ollama. Also
|
||||
answers `/api/show` so the client's context-window probe succeeds."""
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.rfile.read(length)
|
||||
if self.path.endswith("/api/show"):
|
||||
body = json.dumps({"parameters": {"num_ctx": 4242}}).encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
frame = "data: " + json.dumps(
|
||||
{"choices": [{"delta": {"content": GOOD_BODY}}]}
|
||||
) + "\n\n"
|
||||
body = (frame + "data: [DONE]\n\n").encode("utf-8")
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "text/event-stream")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=httpd.serve_forever, daemon=True).start()
|
||||
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
|
||||
|
||||
|
||||
def _scheduler(tmp_path, codegen=None):
|
||||
return Scheduler(
|
||||
engine=SemIfEngine(EngineConfig()),
|
||||
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"),
|
||||
},
|
||||
trace=TraceLog(str(tmp_path / "runs.jsonl")),
|
||||
codegen=codegen,
|
||||
)
|
||||
|
||||
|
||||
def test_action_result_needs_input_defaults_none():
|
||||
assert ActionResult("log", "state").needs_input is None
|
||||
|
||||
@@ -180,14 +251,32 @@ def test_category_registry_register_skill(tmp_path):
|
||||
registry.register_skill("brand_new", "ping", "Probe the service.")
|
||||
loaded = registry.read()
|
||||
assert loaded["delivery"]["skills"] == [
|
||||
{"name": "track_live", "description": "Follow a package in real time."}
|
||||
{
|
||||
"name": "track_live",
|
||||
"description": "Follow a package in real time.",
|
||||
"request_text": "",
|
||||
}
|
||||
]
|
||||
assert loaded["brand_new"] == {
|
||||
"description": "",
|
||||
"skills": [{"name": "ping", "description": "Probe the service."}],
|
||||
"skills": [{"name": "ping", "description": "Probe the service.", "request_text": ""}],
|
||||
}
|
||||
|
||||
|
||||
def test_category_registry_register_skill_keeps_request_text(tmp_path):
|
||||
registry = CategoryRegistry(str(tmp_path / "categories.json"))
|
||||
registry.register_skill(
|
||||
"delivery",
|
||||
"track_live",
|
||||
"Follow a package in real time.",
|
||||
request_text="track my drone delivery in real time",
|
||||
)
|
||||
loaded = registry.read()
|
||||
assert loaded["delivery"]["skills"][0]["request_text"] == (
|
||||
"track my drone delivery in real time"
|
||||
)
|
||||
|
||||
|
||||
def test_merge_registry_loads_categories_and_skills(tmp_path):
|
||||
registry = CategoryRegistry(str(tmp_path / "categories.json"))
|
||||
registry.register_skill("delivery", "track_live", "Follow a package in real time.")
|
||||
@@ -228,3 +317,111 @@ def test_dispatch_create_category_without_engine_returns_error(tmp_path):
|
||||
result = scheduler._dispatch(Request("anything"))
|
||||
assert result.kind == "error"
|
||||
assert "create_category failed" in result.summary
|
||||
|
||||
|
||||
def test_skill_status_reflects_writing_and_noop():
|
||||
"""A fresh Skill is a stub; marking it writing shows `writing`; a real body
|
||||
shows `ready`."""
|
||||
stub = Skill(name="probe", category="tracking", description="Probe.")
|
||||
assert stub.is_noop()
|
||||
assert stub.status == "stub"
|
||||
stub.writing = True
|
||||
assert stub.status == "writing"
|
||||
stub.writing = False
|
||||
|
||||
def predict(ctx, request):
|
||||
return None
|
||||
|
||||
def act(ctx, request, prediction):
|
||||
return None
|
||||
|
||||
ready = Skill(name="probe", category="tracking", description="Probe.", predict=predict, act=act)
|
||||
assert not ready.is_noop()
|
||||
assert ready.status == "ready"
|
||||
|
||||
|
||||
def test_restart_skill_without_codegen_returns_error(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.tree["tracking"] = [
|
||||
Skill(name="track_live", category="tracking", description="Follow a package.")
|
||||
]
|
||||
status, detail = scheduler.restart_skill("tracking", "track_live")
|
||||
assert status == "error"
|
||||
assert "no codegen" in detail
|
||||
|
||||
|
||||
def test_restart_skill_unknown_leaf_returns_error(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
status, detail = scheduler.restart_skill("tracking", "missing")
|
||||
assert status == "error"
|
||||
assert "no skill" in detail
|
||||
|
||||
|
||||
def test_dispatch_skill_awaiting_body_does_not_reauthor(tmp_path):
|
||||
"""A re-dispatched request whose skill body is still pending must report the
|
||||
pending write instead of authoring a second skill."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
request = Request("track my package")
|
||||
request.meta["awaiting_skill_body"] = ["tracking", "track_live"]
|
||||
result = scheduler._dispatch_skill(request, "tracking", 0.5)
|
||||
assert result.kind == "create_skill"
|
||||
assert "track_live" in result.summary
|
||||
assert "restart" in result.summary
|
||||
|
||||
|
||||
def test_run_skill_guards_stub_and_writing_leaves(tmp_path):
|
||||
"""Running a writing leaf or a body-less stub must not silently no-op."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
writing = Skill(name="w", category="tracking", description="writing")
|
||||
writing.writing = True
|
||||
result = scheduler._run_skill(writing, Request("x"))
|
||||
assert result.kind == "error"
|
||||
assert "still being written" in result.summary
|
||||
|
||||
stub = Skill(name="s", category="tracking", description="stub")
|
||||
result = scheduler._run_skill(stub, Request("x"))
|
||||
assert result.kind == "error"
|
||||
assert "no body" in result.summary
|
||||
|
||||
|
||||
def test_async_skill_write_materializes_merges_and_requeues(tmp_path):
|
||||
"""The full async path: _start_skill_write flags the leaf in-progress and
|
||||
the single-slot worker materializes the body, hot-merges it into the tree,
|
||||
and re-queues the original request for re-dispatch."""
|
||||
httpd, base = _fake_codegen_server()
|
||||
try:
|
||||
scheduler = _scheduler(tmp_path, codegen=CodegenClient(base_url=base, model="test", timeout=10))
|
||||
scheduler.tree["tracking"] = [
|
||||
Skill(name="track_live", category="tracking", description="Follow a package.")
|
||||
]
|
||||
leaf = scheduler.tree["tracking"][0]
|
||||
|
||||
request = Request("track my drone delivery in real time")
|
||||
scheduler._start_skill_write(request, "tracking", SkillDraft(name="track_live", description="Follow a package."), 0.5)
|
||||
|
||||
assert leaf.writing is True
|
||||
deadline = time.monotonic() + 10
|
||||
created = None
|
||||
while time.monotonic() < deadline:
|
||||
created = next(
|
||||
(e for e in scheduler.trace.read() if e["kind"] == "skill_created"),
|
||||
None,
|
||||
)
|
||||
if created:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
assert created is not None, "worker must complete the body write"
|
||||
assert created["written"] is True
|
||||
|
||||
upgraded = scheduler.tree["tracking"][0]
|
||||
assert upgraded is not leaf
|
||||
assert not upgraded.is_noop()
|
||||
assert callable(upgraded.predict) and callable(upgraded.act)
|
||||
|
||||
# The worker drains the queue when idle (run_queue), so an empty queue
|
||||
# is a valid end state; the requeue trace proves the push happened.
|
||||
events = [e["kind"] for e in scheduler.trace.read()]
|
||||
assert "skill_requeued" in events
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
httpd.server_close()
|
||||
Reference in new issue
Block a user