Compare commits
2
Commits
8751e7c08e
...
215c22afb8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
215c22afb8 | ||
|
|
25ade160df |
No files matched your search
@@ -73,14 +73,19 @@ scheduler.py no up-front gate: every input is dispatched
|
||||
single-slot workers: a create_category/create_skill request is
|
||||
queued, the gate stays free, the category job chains into its
|
||||
skill job, and the original request is re-queued and re-runs the
|
||||
new leaf when the body lands; the body worker runs the full
|
||||
new leaf when the body lands; an optional human approval gate
|
||||
(`creation_approval`, off by default) blocks the draft worker
|
||||
after the proposal is authored and before anything is
|
||||
registered — one prompt per request, denial/timeout aborts
|
||||
creation, surfaced via the approval queue; the body worker runs the full
|
||||
pipeline: elicitation ->
|
||||
codegen body (declares its own flat `CONTRACT`) -> fidelity
|
||||
gate -> test -> auto-run test (SemIf regen ladder on failure,
|
||||
code/test); config
|
||||
search auto-populates the skill config from the full config
|
||||
cascade; elicitation asks implementation questions (all front ends
|
||||
defer via the question queue, `wait_timeout`); a
|
||||
cascade; elicitation asks implementation questions one at a
|
||||
time (all front ends defer via the question queue, `answer_timeout`
|
||||
per question); a
|
||||
failed real run triggers a logged SemIf repair choice
|
||||
(retry/repair_skill/ask_user/no_repair) surfaced to the user
|
||||
queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0
|
||||
@@ -349,11 +354,26 @@ CLI, unit tests (24) + box integration tests (2).
|
||||
canned line has no side effect to assess. The leaf choice logs phase
|
||||
`navigate:response` and traces `response_selected`. `response.reject` (a stub
|
||||
that never ran) is gone.
|
||||
- **Optional human approval on creation** (Oct 2026): `creation_approval`
|
||||
(top-level, default `false`) is a single boolean. When on, the single-slot
|
||||
`llm` draft worker blocks after it authors a proposal and before anything is
|
||||
registered; the human approves/denies via the REPL prompt, the dashboard
|
||||
approvals panel (`GET/POST /api/approvals`), or a gateway chat reply
|
||||
(`yes`/`no`). One prompt per creation request — a new category's chained skill
|
||||
is covered by the category approval (`DraftAuthor.approved`). Denial or
|
||||
timeout aborts creation: nothing is registered, no body is written, and the
|
||||
request is not re-dispatched; the wait reuses
|
||||
`codegen.elicitation.wait_timeout`. With no deferring front end it denies
|
||||
immediately rather than stalling the worker. Traced as
|
||||
`creation_approval_requested` / `_approved` / `_denied` / `_timeout` /
|
||||
`_skipped`; it is a human veto, not a decision row — the SemIf create doors
|
||||
still make and log the routing decision.
|
||||
- **Real integrations, implementation questions, fidelity + repair** (Sep 2026):
|
||||
elicitation is on by default and asks implementation questions (which
|
||||
service/account, how to connect, where the credential comes from, what success
|
||||
looks like); every front end defers via the question queue
|
||||
(`/api/questions`, worker waits `codegen.elicitation.wait_timeout`). Bodies
|
||||
(`/api/questions`, worker waits `codegen.elicitation.answer_timeout` per
|
||||
question, one at a time). Bodies
|
||||
must perform the real action via stdlib transports with values from
|
||||
`ctx.config` and declare `INTEGRATION` (service/transport/config_vars); a
|
||||
fidelity gate (`authoring:fidelity`, a SemIf accept/reconsider decision) plus
|
||||
@@ -652,8 +672,9 @@ CLI, unit tests (24) + box integration tests (2).
|
||||
The codegen worker runs the full authoring pipeline:
|
||||
1. **elicitation** (`generate_elicitation`): implementation questions +
|
||||
integration hint. Every front end (REPL, dashboard, gateway) sets
|
||||
`defer_questions` and the worker posts to the question queue and waits
|
||||
(`codegen.elicitation.wait_timeout`) for answers.
|
||||
`defer_questions` and the worker posts them to the question queue one at a
|
||||
time, waiting `codegen.elicitation.answer_timeout` seconds for each (the
|
||||
clock resets on every answer submit; a timeout stops the sequence).
|
||||
2. **codegen body** (`generate_skill_body` / `regenerate_skill_body` on
|
||||
repair): SKILL.md + request + tree + requirements answers; the body is a
|
||||
single `act(ctx, request)`, reads every operational value from `ctx.config`,
|
||||
@@ -716,9 +737,11 @@ CLI, unit tests (24) + box integration tests (2).
|
||||
connect (which service/account, how to connect, where the credential comes
|
||||
from, what success looks like, how failure should behave). Every front end
|
||||
defers — the single-slot worker posts
|
||||
questions to `scheduler.questions` (`GET/POST /api/questions`) and waits up to
|
||||
`codegen.elicitation.wait_timeout` seconds, then proceeds with whatever
|
||||
answers arrived (`questions_timeout` trace). Answers ride on the draft into
|
||||
questions to `scheduler.questions` (`GET/POST /api/questions`) one at a time
|
||||
and waits up to `codegen.elicitation.answer_timeout` seconds for each (the
|
||||
clock resets on every answer submit, so the next question is only shown after
|
||||
the current is answered; a timeout stops the sequence), then proceeds with
|
||||
whatever answers arrived (`questions_timeout` trace). Answers ride on the draft into
|
||||
every body attempt (including retries and regens) and are persisted in the
|
||||
registry so a `restart` does not ask again. The prompt keeps an explicit
|
||||
anti-pattern block: never config-vs-input cadence questions ("should the
|
||||
@@ -816,7 +839,11 @@ CLI, unit tests (24) + box integration tests (2).
|
||||
`semif-gateway.service` agent process, so the gateway runs across
|
||||
logout/reboot. The gateway is its own process — the REPL and the gateway are
|
||||
independent front ends onto the same on-disk logs/registry (do not run two
|
||||
scheduler processes over one skill store concurrently).
|
||||
scheduler processes over one skill store concurrently). **On connect the
|
||||
gateway prints the bot's own SimpleX contact link once** (show-or-create via
|
||||
the daemon it already owns, from the CLI, `_gateway_address_callback`) so a
|
||||
human can reach it without running `scripts/simplex-address.py` — the operator
|
||||
front end prints it; the command adapter itself gains no address surface.
|
||||
- **Bot address / v7 relay gotcha.** The daemon must NOT run with `--headless`
|
||||
or `--relay`: in SimpleX Chat v7 `--headless` means "chat relay" (requires
|
||||
`--relay`) and yields a *relay* address, not a user contact address. Run bot
|
||||
|
||||
+3
-1
@@ -2,6 +2,7 @@
|
||||
"_comment": "Per-machine config. config.json is gitignored; copy this file to config.json and adjust paths. The box (guppy) keeps its own config.json with local paths.",
|
||||
"tau": 0.6,
|
||||
"max_reentries": 3,
|
||||
"creation_approval": false,
|
||||
"navigation": {
|
||||
"_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. Leaf: the softmax offers only existing skills; confirm_skill_fit then compares the winner's action to the request (phase navigate:intent, P(same) >= intent_tau) and a mismatch authors a new leaf. Both taus are separate from the top-level tau so tuning reuse-vs-create does not move run assessment/fidelity. The check is deliberately permissive: with real descriptions in-scope requests score 0.9-1.0, so a borderline over-cover routes into a plausible category and the leaf guard catches it.",
|
||||
"intent_tau": 0.6,
|
||||
@@ -64,9 +65,10 @@
|
||||
"frequency_penalty": 1,
|
||||
"max_attempts": 3,
|
||||
"elicitation": {
|
||||
"_comment": "Ask the product owner implementation questions before the body is written: which service/account, how to connect, where the credential comes from, what success looks like. Every front end defers questions to the questions panel and the single-slot writer waits up to wait_timeout seconds. Questions never ask for operational data values (collected at first fire) or config-vs-input cadence (the config step owns that).",
|
||||
"_comment": "Ask the product owner implementation questions before the body is written: which service/account, how to connect, where the credential comes from, what success looks like. Every front end defers questions to the questions panel; the single-slot writer asks them one at a time and waits answer_timeout seconds for each (the clock resets on every answer submit, so the user only ever sees the next question after answering the current one; a timeout stops the sequence). wait_timeout is the separate, longer wait for the optional creation-approval gate. Questions never ask for operational data values (collected at first fire) or config-vs-input cadence (the config step owns that).",
|
||||
"enabled": true,
|
||||
"max_questions": 4,
|
||||
"answer_timeout": 30,
|
||||
"wait_timeout": 900
|
||||
},
|
||||
"fidelity": {
|
||||
|
||||
+89
-1
@@ -291,6 +291,42 @@ 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.
|
||||
"""
|
||||
while True:
|
||||
pending = scheduler.pending_approvals()
|
||||
if not pending:
|
||||
return
|
||||
item = pending[0]
|
||||
target = (
|
||||
item["category"]
|
||||
if item["kind"] == "category"
|
||||
else f"{item['category']}.{item['skill']}"
|
||||
)
|
||||
answer = input(
|
||||
f"[approval] create new {item['kind']} {target}: {item['description']}\n"
|
||||
"approve? (y/N): "
|
||||
).strip().lower()
|
||||
status, detail = scheduler.answer_approval(
|
||||
item["id"], answer in ("y", "yes")
|
||||
)
|
||||
print(f"[{status}] {detail}")
|
||||
|
||||
|
||||
def _print_approvals(scheduler: Scheduler) -> None:
|
||||
for item in scheduler.pending_approvals():
|
||||
target = (
|
||||
item["category"]
|
||||
if item["kind"] == "category"
|
||||
else f"{item['category']}.{item['skill']}"
|
||||
)
|
||||
print(f"[approval] {item['id']} new {item['kind']} {target}: {item['description']}")
|
||||
|
||||
|
||||
def _fatal_exit(scheduler: Scheduler) -> int | None:
|
||||
"""If the scheduler hit a fatal engine failure, print it and return non-zero.
|
||||
|
||||
@@ -309,10 +345,11 @@ def repl(scheduler: Scheduler, config: dict) -> int:
|
||||
print(
|
||||
"type a request, or one of: busy <text> | idle | status | skills | dream | "
|
||||
"relabel <id> <outcome> | restart <category> <skill> | "
|
||||
"repairs | repair <offer-id> [action] | quit"
|
||||
"repairs | repair <offer-id> [action] | approvals | quit"
|
||||
)
|
||||
while True:
|
||||
_answer_questions(scheduler)
|
||||
_answer_approvals(scheduler)
|
||||
try:
|
||||
line = input("> ").strip()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
@@ -335,6 +372,9 @@ def repl(scheduler: Scheduler, config: dict) -> int:
|
||||
if lower == "repairs":
|
||||
_print_repairs(scheduler)
|
||||
continue
|
||||
if lower == "approvals":
|
||||
_print_approvals(scheduler)
|
||||
continue
|
||||
if lower.startswith(("repair ", "/repair ")):
|
||||
parts = line.lstrip("/").split()
|
||||
if len(parts) not in (2, 3):
|
||||
@@ -345,6 +385,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}")
|
||||
continue
|
||||
@@ -387,6 +428,7 @@ def repl(scheduler: Scheduler, config: dict) -> int:
|
||||
if _fatal_exit(scheduler) is not None:
|
||||
return 1
|
||||
_answer_questions(scheduler)
|
||||
_answer_approvals(scheduler)
|
||||
_print_repairs(scheduler)
|
||||
return _fatal_exit(scheduler) or 0
|
||||
|
||||
@@ -404,6 +446,49 @@ def scripted(scheduler: Scheduler, path: str) -> int:
|
||||
return _fatal_exit(scheduler) or 0
|
||||
|
||||
|
||||
def _gateway_address_callback(adapter):
|
||||
"""Return an `on_connected` coroutine that prints the bot's contact link once.
|
||||
|
||||
A human cannot reach the gateway without the bot's SimpleX contact address,
|
||||
and the only thing that surfaced it before was `scripts/simplex-address.py`
|
||||
run once at provision time. Print it on connect, from the operator front end
|
||||
(the CLI), through the daemon the gateway already owns — show-or-create, no
|
||||
second connection, no new transport surface. The lookup is best-effort: a
|
||||
failure is reported once (to stderr) and retried on the next connect, and it
|
||||
never takes the socket down.
|
||||
"""
|
||||
printed = False
|
||||
warned = False
|
||||
|
||||
async def _announce() -> None:
|
||||
nonlocal printed, warned
|
||||
if printed:
|
||||
return
|
||||
try:
|
||||
link = await adapter.daemon.address()
|
||||
except Exception as exc:
|
||||
if not warned:
|
||||
warned = True
|
||||
print(
|
||||
f"gateway simplex: could not read contact link: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return
|
||||
short = (link or {}).get("short_link") or ""
|
||||
full = (link or {}).get("full_link") or ""
|
||||
if not (short or full):
|
||||
if not warned:
|
||||
warned = True
|
||||
print("gateway simplex: no contact link available", file=sys.stderr)
|
||||
return
|
||||
printed = True
|
||||
print(f"gateway simplex contact link: {short}")
|
||||
if full:
|
||||
print(full)
|
||||
|
||||
return _announce
|
||||
|
||||
|
||||
def run_gateway(
|
||||
scheduler: Scheduler,
|
||||
config: dict,
|
||||
@@ -420,6 +505,9 @@ def run_gateway(
|
||||
from .gateway.simplex import SimplexAdapter
|
||||
|
||||
adapter = SimplexAdapter(cfg, trace=scheduler.trace)
|
||||
# Print the bot's own contact link once, on connect, so the operator can
|
||||
# actually reach the gateway (see _gateway_address_callback).
|
||||
adapter.daemon.on_connected = _gateway_address_callback(adapter)
|
||||
else:
|
||||
print(f"unknown gateway platform {platform!r}")
|
||||
return 1
|
||||
|
||||
@@ -118,6 +118,7 @@ def build_status(scheduler: Scheduler) -> dict:
|
||||
queue_max = scheduler.queue.max_size
|
||||
questions = scheduler.pending_questions()
|
||||
repairs = scheduler.pending_repairs()
|
||||
approvals = scheduler.pending_approvals()
|
||||
return {
|
||||
"current": current,
|
||||
"pending": pending,
|
||||
@@ -126,6 +127,7 @@ def build_status(scheduler: Scheduler) -> dict:
|
||||
"queue_max": queue_max,
|
||||
"questions": questions,
|
||||
"repairs": repairs,
|
||||
"approvals": approvals,
|
||||
}
|
||||
|
||||
|
||||
@@ -228,6 +230,9 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
||||
if path == "/api/repairs":
|
||||
self._send(200, {"repairs": self.scheduler.pending_repairs()})
|
||||
return
|
||||
if path == "/api/approvals":
|
||||
self._send(200, {"approvals": self.scheduler.pending_approvals()})
|
||||
return
|
||||
self._send_error(404, "no such endpoint")
|
||||
|
||||
def do_POST(self):
|
||||
@@ -302,6 +307,18 @@ class DashboardHandler(BaseHTTPRequestHandler):
|
||||
return
|
||||
self._send(200, {"status": status, "detail": detail})
|
||||
return
|
||||
if path == "/api/approvals":
|
||||
with self.lock:
|
||||
try:
|
||||
body = self._read_json()
|
||||
status, detail = self.scheduler.answer_approval(
|
||||
str(body.get("id", "")), bool(body.get("approve"))
|
||||
)
|
||||
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):
|
||||
|
||||
@@ -34,6 +34,17 @@ _REPAIR_ACTIONS = {
|
||||
"no_repair": "no_repair",
|
||||
}
|
||||
|
||||
_APPROVAL_ACTIONS = {
|
||||
"yes": True,
|
||||
"y": True,
|
||||
"approve": True,
|
||||
"ok": True,
|
||||
"no": False,
|
||||
"n": False,
|
||||
"deny": False,
|
||||
"skip": False,
|
||||
}
|
||||
|
||||
|
||||
def _strip_run_id(text: str) -> str:
|
||||
return _LEADING_RUN_ID.sub("", text or "")
|
||||
@@ -65,6 +76,7 @@ class GatewayService:
|
||||
self._pending_owner: str | None = None
|
||||
self._question_for_chat: dict[str, str] = {}
|
||||
self._repair_for_chat: dict[str, str] = {}
|
||||
self._approval_for_chat: dict[str, str] = {}
|
||||
self._surfaced: set[str] = set()
|
||||
self._route_lock = threading.Lock()
|
||||
self._stop = threading.Event()
|
||||
@@ -131,6 +143,12 @@ class GatewayService:
|
||||
status, detail = self.scheduler.resolve_repair(offer_id, action)
|
||||
self._surfaced.add(offer_id)
|
||||
self._reply(reply_to, detail)
|
||||
elif msg.chat_id in self._approval_for_chat and msg.text.strip().lower() in _APPROVAL_ACTIONS:
|
||||
approval_id = self._approval_for_chat.pop(msg.chat_id)
|
||||
approved = _APPROVAL_ACTIONS[msg.text.strip().lower()]
|
||||
status, detail = self.scheduler.answer_approval(approval_id, approved)
|
||||
self._surfaced.add(approval_id)
|
||||
self._reply(reply_to, detail)
|
||||
else:
|
||||
status, detail, run_id = self.scheduler.submit_request(
|
||||
msg.text, source=self.source_for(msg.chat_id)
|
||||
@@ -199,6 +217,31 @@ class GatewayService:
|
||||
),
|
||||
)
|
||||
|
||||
approvals = self.scheduler.pending_approvals()
|
||||
live_ids = {a["id"] for a in approvals}
|
||||
self._approval_for_chat = {
|
||||
chat: aid for chat, aid in self._approval_for_chat.items() if aid in live_ids
|
||||
}
|
||||
for item in approvals:
|
||||
if item["id"] in self._surfaced:
|
||||
continue
|
||||
self._surfaced.add(item["id"])
|
||||
chat = self._owner_of(item["run_id"]) or origin or self.home_channel
|
||||
if chat:
|
||||
self._approval_for_chat[chat] = item["id"]
|
||||
target = (
|
||||
item["category"]
|
||||
if item["kind"] == "category"
|
||||
else f"{item['category']}.{item['skill']}"
|
||||
)
|
||||
self._reply(
|
||||
chat,
|
||||
(
|
||||
f"Approve creating new {item['kind']} {target}: "
|
||||
f"{item['description']}\nReply yes / no."
|
||||
),
|
||||
)
|
||||
|
||||
# ---- scheduler requeue hook (called under the scheduler lock) ----
|
||||
|
||||
def on_request_requeued(self, parent_id: str, child_id: str) -> None:
|
||||
|
||||
+246
-42
@@ -109,13 +109,16 @@ class DraftAuthor:
|
||||
|
||||
`kind` is "category" (author a top-level category) or "skill" (author a
|
||||
leaf inside `category`). A category job chains into its skill job so the
|
||||
create_category -> create_skill order stays deterministic.
|
||||
create_category -> create_skill order stays deterministic. `approved` marks
|
||||
a chained skill job whose parent category was already approved, so the
|
||||
creation-approval prompt is asked once per request, not once per level.
|
||||
"""
|
||||
|
||||
request: Request
|
||||
category: str | None
|
||||
weight: float
|
||||
kind: str
|
||||
approved: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -123,8 +126,9 @@ class PendingQuestion:
|
||||
"""A question waiting for the human (deferred elicitation or repair).
|
||||
|
||||
Posted by the codegen worker; answered via
|
||||
the dashboard (`/api/questions`) or `Scheduler.answer_question`. The worker
|
||||
waits (bounded by `codegen.elicitation.wait_timeout`) and continues with
|
||||
the dashboard (`/api/questions`) or `Scheduler.answer_question`. Elicitation
|
||||
posts one at a time and waits `codegen.elicitation.answer_timeout` seconds
|
||||
for each (the clock resets on every answer); the worker then continues with
|
||||
whatever answers arrived.
|
||||
"""
|
||||
|
||||
@@ -164,6 +168,27 @@ class RepairOffer:
|
||||
created_at: float = field(default_factory=time.time)
|
||||
|
||||
|
||||
@dataclass
|
||||
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.
|
||||
"""
|
||||
|
||||
id: str
|
||||
run_id: str
|
||||
kind: str # category | skill
|
||||
category: str
|
||||
skill: str
|
||||
description: str
|
||||
status: str = "pending" # pending | approved | denied | timeout
|
||||
created_at: float = field(default_factory=time.time)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DispatchResult:
|
||||
kind: str # ran | create_category | create_skill | needs_input | error
|
||||
@@ -209,7 +234,11 @@ class Scheduler:
|
||||
self.elicitation_enabled = bool(elicitation_cfg.get("enabled", True))
|
||||
self.elicitation_max = int(elicitation_cfg.get("max_questions", 4))
|
||||
self.elicitation_wait = float(elicitation_cfg.get("wait_timeout", 900.0))
|
||||
self.elicitation_answer_timeout = float(
|
||||
elicitation_cfg.get("answer_timeout", 30.0)
|
||||
)
|
||||
self.defer_questions = False
|
||||
self.creation_approval = bool(config.get("creation_approval", False))
|
||||
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))
|
||||
@@ -251,6 +280,8 @@ class Scheduler:
|
||||
self.questions: list[PendingQuestion] = []
|
||||
self.repairs: list[RepairOffer] = []
|
||||
self._repair_counts: dict[str, int] = {}
|
||||
self._approval_notify = threading.Condition(self._lock)
|
||||
self.approvals: list[PendingApproval] = []
|
||||
|
||||
# ---- fatal handling ----
|
||||
|
||||
@@ -742,6 +773,50 @@ class Scheduler:
|
||||
return self._repair_with_answer(offer_id, answer)
|
||||
return "ok", "answer recorded" if answer else "question skipped"
|
||||
|
||||
def pending_approvals(self) -> list[dict]:
|
||||
"""Creation proposals awaiting the human's yes/no."""
|
||||
with self._lock:
|
||||
return [
|
||||
{
|
||||
"id": a.id,
|
||||
"run_id": a.run_id,
|
||||
"kind": a.kind,
|
||||
"category": a.category,
|
||||
"skill": a.skill,
|
||||
"description": a.description,
|
||||
"created_at": a.created_at,
|
||||
}
|
||||
for a in self.approvals
|
||||
if a.status == "pending"
|
||||
]
|
||||
|
||||
def answer_approval(self, approval_id: str, approved: bool) -> tuple[str, str]:
|
||||
"""Approve or deny a pending creation proposal.
|
||||
|
||||
The draft worker is blocked in `_request_approval`; setting the status
|
||||
and notifying releases it (True registers + writes the body, False
|
||||
aborts). The terminal trace event is written by the worker, not here.
|
||||
"""
|
||||
with self._lock:
|
||||
approval = next(
|
||||
(a for a in self.approvals if a.id == approval_id), None
|
||||
)
|
||||
if approval is None:
|
||||
return "error", f"no pending approval {approval_id}"
|
||||
if approval.status != "pending":
|
||||
return "error", f"approval {approval_id} is already {approval.status}"
|
||||
approval.status = "approved" if approved else "denied"
|
||||
self._approval_notify.notify_all()
|
||||
target = (
|
||||
approval.category
|
||||
if approval.kind == "category"
|
||||
else f"{approval.category}.{approval.skill}"
|
||||
)
|
||||
return (
|
||||
"ok",
|
||||
f"{'approved' if approved else 'denied'} {approval.kind} {target}",
|
||||
)
|
||||
|
||||
def pending_repairs(self) -> list[dict]:
|
||||
with self._lock:
|
||||
return [
|
||||
@@ -888,17 +963,23 @@ class Scheduler:
|
||||
category: str | None,
|
||||
kind: str,
|
||||
weight: float,
|
||||
approved: bool = False,
|
||||
) -> None:
|
||||
"""Queue a category or skill draft for the `llm` worker.
|
||||
|
||||
The gate stays free: this returns immediately and one draft at a time is
|
||||
authored in the background. A category job chains into its skill job; a
|
||||
skill job hands off to the codegen body worker.
|
||||
skill job hands off to the codegen body worker. `approved` marks a
|
||||
chained skill job whose category was already approved.
|
||||
"""
|
||||
with self._lock:
|
||||
self._drafts.append(
|
||||
DraftAuthor(
|
||||
request=request, category=category, weight=weight, kind=kind
|
||||
request=request,
|
||||
category=category,
|
||||
weight=weight,
|
||||
kind=kind,
|
||||
approved=approved,
|
||||
)
|
||||
)
|
||||
if self._draft_thread is None or not self._draft_thread.is_alive():
|
||||
@@ -940,10 +1021,14 @@ class Scheduler:
|
||||
def _author_category(self, job: DraftAuthor) -> None:
|
||||
"""Author a top-level category, then chain into its skill leaf.
|
||||
|
||||
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 `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.
|
||||
"""
|
||||
draft = generate_category(self.llm, job.request, self._tree_snapshot())
|
||||
if not self._request_approval(job, "category", draft.name, draft.description):
|
||||
return
|
||||
with self._lock:
|
||||
if draft.name in self.tree:
|
||||
self.trace.append(
|
||||
@@ -961,13 +1046,19 @@ class Scheduler:
|
||||
category=draft.name,
|
||||
description=draft.description,
|
||||
)
|
||||
self._queue_draft(job.request, draft.name, "skill", job.weight)
|
||||
self._queue_draft(job.request, draft.name, "skill", job.weight, approved=True)
|
||||
|
||||
def _author_skill(self, job: DraftAuthor) -> None:
|
||||
"""Author a skill leaf stub, then launch the codegen body write."""
|
||||
"""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).
|
||||
"""
|
||||
draft = generate_skill(
|
||||
self.llm, job.request, job.category, self._tree_snapshot()
|
||||
)
|
||||
if not self._request_approval(job, "skill", draft.name, draft.description):
|
||||
return
|
||||
with self._lock:
|
||||
existing = {s.name for s in self.tree.get(job.category, [])}
|
||||
if draft.name in existing:
|
||||
@@ -1022,6 +1113,103 @@ class Scheduler:
|
||||
"The request was not re-dispatched."
|
||||
)
|
||||
|
||||
# ---- creation approval (opt-in human veto on new categories/skills) ----
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
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.
|
||||
"""
|
||||
if not self.creation_approval or job.approved:
|
||||
return True
|
||||
target = name if kind == "category" else f"{job.category}.{name}"
|
||||
if not self.defer_questions:
|
||||
self.trace.append(
|
||||
"creation_approval_skipped",
|
||||
job.request.id,
|
||||
target_kind=kind,
|
||||
category=target if kind == "category" else job.category,
|
||||
skill="" if kind == "category" else name,
|
||||
reason="no front end to answer; creation denied",
|
||||
)
|
||||
print(
|
||||
f"[approval] {kind} {target} needs approval but no front end is "
|
||||
"deferring questions; creation denied."
|
||||
)
|
||||
return False
|
||||
approval = PendingApproval(
|
||||
id=uuid.uuid4().hex[:12],
|
||||
run_id=job.request.id,
|
||||
kind=kind,
|
||||
category=target if kind == "category" else (job.category or ""),
|
||||
skill="" if kind == "category" else name,
|
||||
description=description,
|
||||
)
|
||||
with self._lock:
|
||||
self.approvals.append(approval)
|
||||
self._approval_notify.notify_all()
|
||||
self.trace.append(
|
||||
"creation_approval_requested",
|
||||
job.request.id,
|
||||
target_kind=kind,
|
||||
category=approval.category,
|
||||
skill=approval.skill,
|
||||
description=description,
|
||||
)
|
||||
print(
|
||||
f"[approval] new {kind} {target} — {description}. "
|
||||
"Approve in the REPL/dashboard (denies on timeout)."
|
||||
)
|
||||
deadline = (
|
||||
None
|
||||
if self.elicitation_wait <= 0
|
||||
else time.monotonic() + self.elicitation_wait
|
||||
)
|
||||
with self._lock:
|
||||
while approval.status == "pending":
|
||||
if deadline is not None and time.monotonic() >= deadline:
|
||||
approval.status = "timeout"
|
||||
break
|
||||
self._approval_notify.wait(timeout=1.0)
|
||||
self.approvals = [a for a in self.approvals if a.id != approval.id]
|
||||
self._approval_notify.notify_all()
|
||||
status = approval.status
|
||||
if status == "approved":
|
||||
self.trace.append(
|
||||
"creation_approval_approved",
|
||||
job.request.id,
|
||||
target_kind=kind,
|
||||
category=approval.category,
|
||||
skill=approval.skill,
|
||||
)
|
||||
return True
|
||||
event = (
|
||||
"creation_approval_timeout"
|
||||
if status == "timeout"
|
||||
else "creation_approval_denied"
|
||||
)
|
||||
self.trace.append(
|
||||
event,
|
||||
job.request.id,
|
||||
target_kind=kind,
|
||||
category=approval.category,
|
||||
skill=approval.skill,
|
||||
)
|
||||
print(
|
||||
f"[approval] {kind} {target} "
|
||||
f"{'timed out' if status == 'timeout' else 'denied'}; creation aborted."
|
||||
)
|
||||
return False
|
||||
|
||||
# ---- async skill-body writes (single-slot codegen worker) ----
|
||||
|
||||
def _start_skill_write(
|
||||
@@ -1175,10 +1363,11 @@ class Scheduler:
|
||||
"""Generate questions in the background, post them, wait for answers.
|
||||
|
||||
The single-slot worker itself asks: the REPL, dashboard, and gateway all
|
||||
defer questions to `self.questions` now that authoring is async. It
|
||||
pauses here for up to `elicitation.wait_timeout` while the gate stays
|
||||
free and other requests proceed; whatever answers arrive (possibly none)
|
||||
feed the body writer.
|
||||
defer questions to `self.questions` now that authoring is async. It asks
|
||||
them one at a time, waiting up to `elicitation.answer_timeout` seconds
|
||||
for each (the clock resets on every answer); the gate stays free while
|
||||
it waits and other requests proceed. A timeout stops the sequence and
|
||||
the worker proceeds with whatever answers arrived (possibly none).
|
||||
"""
|
||||
if not (self.defer_questions and self.elicitation_enabled and self.codegen):
|
||||
if self.elicitation_enabled and self.codegen is not None:
|
||||
@@ -1217,20 +1406,14 @@ class Scheduler:
|
||||
def _post_questions(
|
||||
self, job: SkillWrite, questions: list[str]
|
||||
) -> dict[str, str]:
|
||||
"""Post a question group and block the worker until answered or timed out."""
|
||||
group = [
|
||||
PendingQuestion(
|
||||
id=uuid.uuid4().hex[:12],
|
||||
run_id=job.request.id,
|
||||
category=job.category,
|
||||
skill=job.draft.name,
|
||||
question=question,
|
||||
)
|
||||
for question in questions
|
||||
]
|
||||
with self._lock:
|
||||
self.questions.extend(group)
|
||||
self._question_notify.notify_all()
|
||||
"""Ask the questions one at a time, waiting for each answer.
|
||||
|
||||
Only one question is live at a time: the next is posted only after the
|
||||
current is answered (an empty answer is accepted) or skipped. Each
|
||||
question gets a fresh `elicitation.answer_timeout` seconds — the clock
|
||||
resets on every answer submit. A timeout stops the sequence so the
|
||||
worker proceeds with whatever answers arrived.
|
||||
"""
|
||||
self.trace.append(
|
||||
"questions_asked",
|
||||
job.request.id,
|
||||
@@ -1239,29 +1422,50 @@ class Scheduler:
|
||||
questions=questions,
|
||||
)
|
||||
print(
|
||||
f"[codegen] {len(group)} question(s) waiting about "
|
||||
f"[codegen] {len(questions)} question(s) about "
|
||||
f"{job.category}.{job.draft.name} — answer in the dashboard."
|
||||
)
|
||||
deadline = (
|
||||
None if self.elicitation_wait <= 0
|
||||
else time.monotonic() + self.elicitation_wait
|
||||
)
|
||||
with self._lock:
|
||||
while not all(q.answer is not None or q.skipped for q in group):
|
||||
if deadline is not None and time.monotonic() >= deadline:
|
||||
break
|
||||
self._question_notify.wait(timeout=1.0)
|
||||
answers = {q.question: q.answer for q in group if q.answer}
|
||||
self.questions = [q for q in self.questions if q not in group]
|
||||
self._question_notify.notify_all()
|
||||
if len(answers) < len(group):
|
||||
answers: dict[str, str] = {}
|
||||
asked = 0
|
||||
timed_out = False
|
||||
for question in questions:
|
||||
pending = PendingQuestion(
|
||||
id=uuid.uuid4().hex[:12],
|
||||
run_id=job.request.id,
|
||||
category=job.category,
|
||||
skill=job.draft.name,
|
||||
question=question,
|
||||
)
|
||||
with self._lock:
|
||||
self.questions.append(pending)
|
||||
self._question_notify.notify_all()
|
||||
asked += 1
|
||||
deadline = (
|
||||
None
|
||||
if self.elicitation_answer_timeout <= 0
|
||||
else time.monotonic() + self.elicitation_answer_timeout
|
||||
)
|
||||
with self._lock:
|
||||
while pending.answer is None and not pending.skipped:
|
||||
if deadline is not None and time.monotonic() >= deadline:
|
||||
timed_out = True
|
||||
break
|
||||
self._question_notify.wait(timeout=1.0)
|
||||
if pending.answer is not None:
|
||||
answers[question] = pending.answer
|
||||
self.questions = [q for q in self.questions if q is not pending]
|
||||
self._question_notify.notify_all()
|
||||
if pending.answer is None and not pending.skipped:
|
||||
# The current question timed out; don't post the rest.
|
||||
break
|
||||
if timed_out:
|
||||
self.trace.append(
|
||||
"questions_timeout",
|
||||
job.request.id,
|
||||
category=job.category,
|
||||
skill=job.draft.name,
|
||||
answered=len(answers),
|
||||
asked=len(group),
|
||||
asked=asked,
|
||||
)
|
||||
return answers
|
||||
|
||||
|
||||
@@ -308,12 +308,18 @@ class SimplexDaemon:
|
||||
self._ws = ws
|
||||
backoff = self.reconnect_initial
|
||||
self._event("gateway_connected", url=self.ws_url)
|
||||
await self._notify_connected()
|
||||
sender = asyncio.create_task(self._outbound_loop(ws))
|
||||
# The on_connected hook may issue correlated commands (e.g.
|
||||
# the startup contact-address lookup), so run it
|
||||
# CONCURRENTLY with the read loop: awaiting it inline would
|
||||
# block the loop that resolves its own response and the
|
||||
# request would time out.
|
||||
hook = asyncio.create_task(self._notify_connected())
|
||||
try:
|
||||
async for raw in ws:
|
||||
await self._consume(raw)
|
||||
finally:
|
||||
hook.cancel()
|
||||
sender.cancel()
|
||||
except Exception as exc: # reconnect on any transport failure
|
||||
self._event("gateway_error", message=str(exc)[:300])
|
||||
|
||||
@@ -590,6 +590,20 @@ async function resolveRepair(id, action) {
|
||||
await refreshAll();
|
||||
}
|
||||
|
||||
async function resolveApproval(id, approve) {
|
||||
try {
|
||||
const res = await getJSON("/api/approvals", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ id, approve }),
|
||||
});
|
||||
flash(`[${res.status}] ${res.detail}`);
|
||||
} catch (err) {
|
||||
flash(`approval failed: ${err.message}`);
|
||||
}
|
||||
await refreshAll();
|
||||
}
|
||||
|
||||
function skillStatusBadge(status, category, name) {
|
||||
const span = document.createElement("span");
|
||||
if (status === "writing") {
|
||||
@@ -738,6 +752,28 @@ function renderQuestions() {
|
||||
box.appendChild(actions);
|
||||
el.appendChild(box);
|
||||
}
|
||||
for (const a of state.status.approvals || []) {
|
||||
const box = document.createElement("div");
|
||||
box.className = "pending-line";
|
||||
const target = a.kind === "category" ? a.category : `${a.category}.${a.skill}`;
|
||||
const label = document.createElement("div");
|
||||
label.textContent = `approve new ${a.kind} ${target}: ${a.description}`;
|
||||
box.appendChild(label);
|
||||
const actions = document.createElement("div");
|
||||
const yes = document.createElement("button");
|
||||
yes.type = "button";
|
||||
yes.textContent = "approve";
|
||||
yes.className = "primary";
|
||||
yes.addEventListener("click", () => resolveApproval(a.id, true));
|
||||
const no = document.createElement("button");
|
||||
no.type = "button";
|
||||
no.textContent = "deny";
|
||||
no.addEventListener("click", () => resolveApproval(a.id, false));
|
||||
actions.appendChild(yes);
|
||||
actions.appendChild(no);
|
||||
box.appendChild(actions);
|
||||
el.appendChild(box);
|
||||
}
|
||||
}
|
||||
|
||||
function renderAnswerFeedback() {
|
||||
|
||||
@@ -16,7 +16,7 @@ from semif_agent.decisions import DecisionRequest, DecisionResult, Option, Reque
|
||||
from semif_agent.engine import EngineConfig, SemIfEngine
|
||||
from semif_agent.llm import LLMClient
|
||||
from semif_agent.log import DecisionLog
|
||||
from semif_agent.scheduler import PendingQuestion, RepairOffer, Scheduler
|
||||
from semif_agent.scheduler import PendingApproval, PendingQuestion, RepairOffer, Scheduler
|
||||
from semif_agent.skills import ActionResult, Skill
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
@@ -356,11 +356,43 @@ def test_status_carries_questions_and_repairs(tmp_path):
|
||||
selected="retry", reason="boom", request_text="track", failure="boom",
|
||||
)
|
||||
)
|
||||
scheduler.approvals.append(
|
||||
PendingApproval(
|
||||
id="a1", run_id="run-1", kind="skill", category="tracking",
|
||||
skill="track_live", description="Follow a package.",
|
||||
)
|
||||
)
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.get("/api/status")
|
||||
assert payload["questions"][0]["id"] == "q1"
|
||||
assert payload["repairs"][0]["id"] == "r1"
|
||||
assert payload["approvals"][0]["id"] == "a1"
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
def test_approvals_endpoint_roundtrip(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
scheduler.approvals.append(
|
||||
PendingApproval(
|
||||
id="a1", run_id="run-1", kind="category", category="travel",
|
||||
skill="", description="Trips.",
|
||||
)
|
||||
)
|
||||
server = Server(scheduler)
|
||||
try:
|
||||
status, payload = server.get("/api/approvals")
|
||||
assert status == 200
|
||||
assert payload["approvals"][0]["id"] == "a1"
|
||||
assert payload["approvals"][0]["kind"] == "category"
|
||||
|
||||
status, payload = server.post("/api/approvals", {"id": "a1", "approve": True})
|
||||
assert payload["status"] == "ok"
|
||||
assert scheduler.pending_approvals() == []
|
||||
|
||||
status, payload = server.post("/api/approvals", {"id": "missing", "approve": False})
|
||||
assert payload["status"] == "error"
|
||||
finally:
|
||||
server.close()
|
||||
|
||||
|
||||
+76
-1
@@ -11,6 +11,7 @@ integration concern, not a dev-box unit test.
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from semif_agent.cli import _gateway_address_callback
|
||||
from semif_agent.decisions import Request
|
||||
from semif_agent.engine import EngineConfig, SemIfEngine
|
||||
from semif_agent.gateway.base import InboundMessage
|
||||
@@ -18,7 +19,7 @@ from semif_agent.gateway.service import GatewayService
|
||||
from semif_agent.gateway.simplex import SimplexAdapter
|
||||
from semif_agent.llm import LLMClient
|
||||
from semif_agent.log import DecisionLog
|
||||
from semif_agent.scheduler import Scheduler
|
||||
from semif_agent.scheduler import PendingApproval, Scheduler
|
||||
from semif_agent.skills import ActionResult, Skill
|
||||
from semif_agent.trace import TraceLog
|
||||
|
||||
@@ -66,6 +67,55 @@ def test_check_requirements_needs_url():
|
||||
assert "ws_url" in hint
|
||||
|
||||
|
||||
# ---- startup contact-link announcement ----
|
||||
|
||||
class _FakeDaemon:
|
||||
def __init__(self, result):
|
||||
self._result = result
|
||||
self.calls = 0
|
||||
|
||||
async def address(self, timeout=20.0):
|
||||
self.calls += 1
|
||||
if isinstance(self._result, Exception):
|
||||
raise self._result
|
||||
return self._result
|
||||
|
||||
|
||||
class _FakeAdapter:
|
||||
def __init__(self, daemon):
|
||||
self.daemon = daemon
|
||||
|
||||
|
||||
def test_gateway_address_callback_prints_link_once(capsys):
|
||||
daemon = _FakeDaemon(
|
||||
{"short_link": "simplex:/abc", "full_link": "simplex://full"}
|
||||
)
|
||||
announce = _gateway_address_callback(_FakeAdapter(daemon))
|
||||
asyncio.run(announce())
|
||||
asyncio.run(announce()) # a reconnect must not reprint
|
||||
out = capsys.readouterr()
|
||||
assert "simplex:/abc" in out.out
|
||||
assert "simplex://full" in out.out
|
||||
assert daemon.calls == 1
|
||||
|
||||
|
||||
def test_gateway_address_callback_failure_is_not_fatal(capsys):
|
||||
daemon = _FakeDaemon(RuntimeError("not connected"))
|
||||
announce = _gateway_address_callback(_FakeAdapter(daemon))
|
||||
asyncio.run(announce()) # must not raise
|
||||
asyncio.run(announce()) # retried on the next connect
|
||||
captured = capsys.readouterr()
|
||||
assert "could not read contact link" in captured.err
|
||||
assert daemon.calls == 2
|
||||
|
||||
|
||||
def test_gateway_address_callback_no_link_warns(capsys):
|
||||
daemon = _FakeDaemon({"short_link": "", "full_link": ""})
|
||||
announce = _gateway_address_callback(_FakeAdapter(daemon))
|
||||
asyncio.run(announce())
|
||||
assert "no contact link available" in capsys.readouterr().err
|
||||
|
||||
|
||||
# ---- adapter: send command ----
|
||||
|
||||
def test_send_command_is_structured_not_shortcut():
|
||||
@@ -201,3 +251,28 @@ def test_service_answered_question_routes_back(tmp_path):
|
||||
|
||||
service.handle_inbound(InboundMessage(text="work", chat_id="4", contact_id="4"))
|
||||
assert not scheduler.pending_questions()
|
||||
|
||||
|
||||
def test_service_surfaces_and_resolves_approval(tmp_path):
|
||||
scheduler = build_scheduler(tmp_path)
|
||||
service = build_service(scheduler)
|
||||
scheduler.approvals.append(
|
||||
PendingApproval(
|
||||
id="a1",
|
||||
run_id="r1",
|
||||
kind="skill",
|
||||
category="tracking",
|
||||
skill="track_live",
|
||||
description="Follow a package.",
|
||||
)
|
||||
)
|
||||
service._owners["r1"] = "4"
|
||||
service.surface()
|
||||
assert any(
|
||||
"Approve creating new skill tracking.track_live" in text
|
||||
for text in drain_outbound(service)
|
||||
)
|
||||
|
||||
service.handle_inbound(InboundMessage(text="yes", chat_id="4", contact_id="4"))
|
||||
assert scheduler.pending_approvals() == []
|
||||
assert any("approved" in text for text in drain_outbound(service))
|
||||
@@ -404,6 +404,49 @@ def test_on_connected_hook_runs_and_failures_are_swallowed():
|
||||
asyncio.run(SimplexDaemon("ws://x")._notify_connected())
|
||||
|
||||
|
||||
def test_on_connected_hook_may_roundtrip_while_reading():
|
||||
"""The hook runs concurrently with the read loop, not blocking it.
|
||||
|
||||
Regression: `on_connected` was awaited inline before the read loop started,
|
||||
so a hook that issued a correlated command (the gateway's startup contact
|
||||
link) could never receive its own response and always timed out.
|
||||
"""
|
||||
daemon = SimplexDaemon("ws://x", user_id=1)
|
||||
seen = []
|
||||
|
||||
async def hook():
|
||||
link = await daemon.address(timeout=2)
|
||||
seen.append(link)
|
||||
|
||||
daemon.on_connected = hook
|
||||
daemon._loop = asyncio.new_event_loop()
|
||||
|
||||
async def scenario():
|
||||
daemon._loop = asyncio.get_running_loop()
|
||||
ws = FakeWS(
|
||||
daemon,
|
||||
[
|
||||
{
|
||||
"type": "userContactLink",
|
||||
"contactLink": {
|
||||
"connLinkContact": {"connShortLink": "simplex:/a", "connFullLink": ""}
|
||||
},
|
||||
}
|
||||
],
|
||||
)
|
||||
daemon._ws = ws
|
||||
hook_task = asyncio.create_task(daemon._notify_connected())
|
||||
# The read loop is what resolves the correlated response.
|
||||
for message in list(ws.sent):
|
||||
pass
|
||||
await hook_task
|
||||
return ws
|
||||
|
||||
ws = asyncio.run(scenario())
|
||||
assert seen == [{"short_link": "simplex:/a", "full_link": "", "created": False}]
|
||||
assert [m["cmd"] for m in ws.sent] == ["/_show_address 1"]
|
||||
|
||||
|
||||
# ---- chat previews / history (true unread) ----
|
||||
|
||||
def chat_item(item_id=10, text="hello", status="rcvNew", direction="directRcv", shape="api"):
|
||||
|
||||
+205
-12
@@ -24,6 +24,7 @@ from semif_agent.llm import LLMClient, LLMError
|
||||
from semif_agent.log import DecisionLog
|
||||
from semif_agent.skill import RunResult
|
||||
from semif_agent.scheduler import (
|
||||
DraftAuthor,
|
||||
PendingQuestion,
|
||||
RepairOffer,
|
||||
Scheduler,
|
||||
@@ -963,6 +964,162 @@ def test_dispatch_create_category_queues_draft_and_is_not_fatal(tmp_path):
|
||||
assert scheduler.fatal is None
|
||||
|
||||
|
||||
def _answer_approval_when_posted(scheduler, approved, timeout=5.0):
|
||||
"""Approve/deny the first pending creation proposal, as a front end would."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_approvals()
|
||||
if pending:
|
||||
scheduler.answer_approval(pending[0]["id"], approved)
|
||||
return True
|
||||
time.sleep(0.02)
|
||||
return False
|
||||
|
||||
|
||||
def test_creation_approval_off_proceeds(tmp_path):
|
||||
"""The default (no `creation_approval`) leaves creation unchanged: the gate
|
||||
returns immediately and posts nothing."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"), category=None, weight=0.5, kind="category"
|
||||
)
|
||||
assert scheduler._request_approval(job, "category", "travel", "Trips.") is True
|
||||
assert scheduler.pending_approvals() == []
|
||||
|
||||
|
||||
def test_creation_approval_approved_proceeds(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.creation_approval = True
|
||||
scheduler.defer_questions = True
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"), category=None, weight=0.5, kind="category"
|
||||
)
|
||||
result = {}
|
||||
thread = threading.Thread(
|
||||
target=lambda: result.__setitem__(
|
||||
"ok", scheduler._request_approval(job, "category", "travel", "Trips.")
|
||||
)
|
||||
)
|
||||
thread.start()
|
||||
assert _answer_approval_when_posted(scheduler, approved=True)
|
||||
thread.join()
|
||||
assert result["ok"] is True
|
||||
kinds = [e["kind"] for e in scheduler.trace.read()]
|
||||
assert "creation_approval_requested" in kinds
|
||||
assert "creation_approval_approved" in kinds
|
||||
assert scheduler.pending_approvals() == []
|
||||
|
||||
|
||||
def test_creation_approval_denied_aborts(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.creation_approval = True
|
||||
scheduler.defer_questions = True
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"), category="travel", weight=0.5, kind="skill"
|
||||
)
|
||||
result = {}
|
||||
thread = threading.Thread(
|
||||
target=lambda: result.__setitem__(
|
||||
"ok", scheduler._request_approval(job, "skill", "book_flight", "Book.")
|
||||
)
|
||||
)
|
||||
thread.start()
|
||||
assert _answer_approval_when_posted(scheduler, approved=False)
|
||||
thread.join()
|
||||
assert result["ok"] is False
|
||||
assert any(
|
||||
e["kind"] == "creation_approval_denied" for e in scheduler.trace.read()
|
||||
)
|
||||
|
||||
|
||||
def test_creation_approval_timeout_denies(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.creation_approval = True
|
||||
scheduler.defer_questions = True
|
||||
scheduler.elicitation_wait = 0.1
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"), category="travel", weight=0.5, kind="skill"
|
||||
)
|
||||
assert scheduler._request_approval(job, "skill", "book_flight", "Book.") is False
|
||||
assert any(
|
||||
e["kind"] == "creation_approval_timeout" for e in scheduler.trace.read()
|
||||
)
|
||||
|
||||
|
||||
def test_creation_approval_without_front_end_denies(tmp_path):
|
||||
"""With no deferring front end there is nobody to answer, so creation is
|
||||
denied immediately rather than stalling the draft worker."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.creation_approval = True
|
||||
scheduler.defer_questions = False
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"), category="travel", weight=0.5, kind="skill"
|
||||
)
|
||||
assert scheduler._request_approval(job, "skill", "book_flight", "Book.") is False
|
||||
assert any(
|
||||
e["kind"] == "creation_approval_skipped" for e in scheduler.trace.read()
|
||||
)
|
||||
|
||||
|
||||
def test_creation_approval_chain_skips_second_prompt(tmp_path):
|
||||
"""A skill job chained from an approved category is already covered."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.creation_approval = True
|
||||
scheduler.defer_questions = True
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"),
|
||||
category="travel",
|
||||
weight=0.5,
|
||||
kind="skill",
|
||||
approved=True,
|
||||
)
|
||||
assert scheduler._request_approval(job, "skill", "book_flight", "Book.") is True
|
||||
assert scheduler.pending_approvals() == []
|
||||
|
||||
|
||||
def test_author_category_denied_does_not_register(tmp_path, monkeypatch):
|
||||
"""The category hook: a denied proposal registers nothing and queues no
|
||||
chained skill draft."""
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.creation_approval = True
|
||||
scheduler.defer_questions = True
|
||||
monkeypatch.setattr(
|
||||
"semif_agent.scheduler.generate_category",
|
||||
lambda client, request, tree: CategoryDraft(name="travel", description="Trips."),
|
||||
)
|
||||
job = DraftAuthor(
|
||||
request=Request("book a trip"), category=None, weight=0.5, kind="category"
|
||||
)
|
||||
thread = threading.Thread(target=scheduler._author_category, args=(job,))
|
||||
thread.start()
|
||||
assert _answer_approval_when_posted(scheduler, approved=False)
|
||||
thread.join()
|
||||
assert "travel" not in scheduler.tree
|
||||
assert not any(e["kind"] == "category_created" for e in scheduler.trace.read())
|
||||
assert list(scheduler._drafts) == []
|
||||
|
||||
|
||||
def test_author_skill_denied_does_not_register(tmp_path, monkeypatch):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.creation_approval = True
|
||||
scheduler.defer_questions = True
|
||||
monkeypatch.setattr(
|
||||
"semif_agent.scheduler.generate_skill",
|
||||
lambda client, request, category, tree: SkillDraft(
|
||||
name="book_flight", description="Book a flight."
|
||||
),
|
||||
)
|
||||
job = DraftAuthor(
|
||||
request=Request("book a flight"), category="travel", weight=0.5, kind="skill"
|
||||
)
|
||||
thread = threading.Thread(target=scheduler._author_skill, args=(job,))
|
||||
thread.start()
|
||||
assert _answer_approval_when_posted(scheduler, approved=False)
|
||||
thread.join()
|
||||
assert scheduler.tree.get("travel", []) == []
|
||||
assert not any(e["kind"] == "skill_created" for e in scheduler.trace.read())
|
||||
|
||||
|
||||
def test_skill_status_reflects_writing_and_noop():
|
||||
"""A fresh Skill is a stub; marking it writing shows `writing`; a real body
|
||||
shows `ready`."""
|
||||
@@ -1291,9 +1448,9 @@ def test_answer_question_unknown_id_errors(tmp_path):
|
||||
assert "no pending question" in detail
|
||||
|
||||
|
||||
def test_post_questions_waits_for_answers(tmp_path):
|
||||
def test_post_questions_asks_one_at_a_time(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_wait = 5.0
|
||||
scheduler.elicitation_answer_timeout = 5.0
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
@@ -1305,26 +1462,62 @@ def test_post_questions_waits_for_answers(tmp_path):
|
||||
target=lambda: result.update(scheduler._post_questions(job, ["Q1?", "Q2?"]))
|
||||
)
|
||||
thread.start()
|
||||
|
||||
def next_pending(deadline: float) -> list:
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_questions()
|
||||
if pending:
|
||||
return pending
|
||||
time.sleep(0.02)
|
||||
return []
|
||||
|
||||
deadline = time.monotonic() + 5
|
||||
pending = []
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_questions()
|
||||
if len(pending) == 2:
|
||||
break
|
||||
time.sleep(0.02)
|
||||
assert len(pending) == 2
|
||||
scheduler.answer_question(pending[0]["id"], "A1")
|
||||
scheduler.answer_question(pending[1]["id"], "")
|
||||
first = next_pending(deadline)
|
||||
assert [q["question"] for q in first] == ["Q1?"]
|
||||
scheduler.answer_question(first[0]["id"], "A1")
|
||||
second = next_pending(deadline)
|
||||
assert [q["question"] for q in second] == ["Q2?"]
|
||||
scheduler.answer_question(second[0]["id"], "")
|
||||
thread.join(timeout=5)
|
||||
assert result == {"Q1?": "A1"}
|
||||
assert scheduler.pending_questions() == []
|
||||
kinds = [e["kind"] for e in scheduler.trace.read()]
|
||||
assert "questions_asked" in kinds
|
||||
# An empty answer is accepted (the question is dismissed), not a timeout.
|
||||
assert "questions_timeout" not in kinds
|
||||
|
||||
|
||||
def test_post_questions_timeout_drops_remaining(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_answer_timeout = 0.2
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
draft=SkillDraft(name="probe", description="Probe."),
|
||||
weight=0.5,
|
||||
)
|
||||
result: dict = {}
|
||||
thread = threading.Thread(
|
||||
target=lambda: result.update(scheduler._post_questions(job, ["Q1?", "Q2?"]))
|
||||
)
|
||||
thread.start()
|
||||
deadline = time.monotonic() + 3
|
||||
while time.monotonic() < deadline:
|
||||
pending = scheduler.pending_questions()
|
||||
if pending:
|
||||
scheduler.answer_question(pending[0]["id"], "A1")
|
||||
break
|
||||
time.sleep(0.02)
|
||||
thread.join(timeout=3)
|
||||
assert result == {"Q1?": "A1"}
|
||||
assert scheduler.pending_questions() == []
|
||||
events = [e for e in scheduler.trace.read() if e["kind"] == "questions_timeout"]
|
||||
assert events and events[-1]["answered"] == 1 and events[-1]["asked"] == 2
|
||||
|
||||
|
||||
def test_post_questions_times_out(tmp_path):
|
||||
scheduler = _scheduler(tmp_path)
|
||||
scheduler.elicitation_wait = 0.1
|
||||
scheduler.elicitation_answer_timeout = 0.1
|
||||
job = SkillWrite(
|
||||
request=Request("track it"),
|
||||
category="tracking",
|
||||
|
||||
Reference in new issue
Block a user