response: rebuild as a closed tree of canned replies; drop the gate

There is no up-front handle/ignore filter any more. Every input is scored
and dispatched; inputs that are not tasks fall through navigation into the
closed response category of hardcoded canned lines (greeting/thanks/
acknowledge/farewell/affirm/unable + the catchall response.clarify). The
category is CANNED_CATEGORIES: navigation offers no create_skill there,
dispatch/restart refuse to author it, and the runner skips assessment and
repair for it (a canned line has no side effect to assess).

Removes _contains_request/build_gate_decision and the dropped path.
This commit is contained in:
Denton Social committed 2026-09-29 03:46:53 -05:00
1 parent 5a6f220e79
commit 22f91e0360
9 files changed
+258 -144

No files matched your search

+21 -7
View File
@@ -38,8 +38,10 @@ Guessing, inventing data, or shipping a toy is always the wrong answer.
## What this is ## What this is
A local desktop CLI agent whose entire control flow is a single decision model A local desktop CLI agent whose entire control flow is a single decision model
(SemIf). Inputs are gated, scored for urgency, queued, and dispatched through a (SemIf). Inputs are scored for urgency, queued, and dispatched through a
skill tree. Every SemIf decision is logged as a labeled training row; the skill tree. Nothing is gated out up front: every input is dispatched and inputs
that are not tasks fall through navigation into the closed `response` tree of
canned replies. Every SemIf decision is logged as a labeled training row; the
`dream` pass computes the prediction-vs-observation cost (cross-entropy / NLL + `dream` pass computes the prediction-vs-observation cost (cross-entropy / NLL +
ECE) that later drives fine-tuning. See "Product premise" above for what the ECE) that later drives fine-tuning. See "Product premise" above for what the
agent is for; this section is the machinery. agent is for; this section is the machinery.
@@ -62,8 +64,7 @@ capability is a new bridge, not a gateway feature.
cli.py argparse: run (REPL / --script), dream, skills, status, relabel, cli.py argparse: run (REPL / --script), dream, skills, status, relabel,
dashboard, gateway (command intake), bridge (standalone dashboard, gateway (command intake), bridge (standalone
third-party API bridges) third-party API bridges)
scheduler.py gate (handle/ignore; state carries the user's expectation + scheduler.py no up-front gate: every input is dispatched
the available skills, so lookups are not read as small talk)
-> choice(tau) -> score -> queue; preempt + requeue; -> choice(tau) -> score -> queue; preempt + requeue;
a skill run paused for input (needs_input) keeps `current` a skill run paused for input (needs_input) keeps `current`
busy; `answer` routes straight to the pending run, bypassing busy; `answer` routes straight to the pending run, bypassing
@@ -79,8 +80,8 @@ scheduler.py gate (handle/ignore; state carries the user's expectation +
failed real run triggers a logged SemIf repair choice failed real run triggers a logged SemIf repair choice
(retry/repair_skill/ask_user/no_repair) surfaced to the user (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 queue.py urgency max-heap (desc weight, FIFO seq), age pulls toward 1.0
skills.py tree + registry (hardcoded built-in: response.reject, service-free skills.py tree + registry (hardcoded built-ins: the closed `response` canned
behaviors only), navigation = SemIf choices per level (logged), tree only), navigation = SemIf choices per level (logged),
create_category create_category
and create_skill author + register stubs via the decision model and create_skill author + register stubs via the decision model
in generation mode; SkillStore persists one folder per skill in generation mode; SkillStore persists one folder per skill
@@ -283,6 +284,19 @@ CLI, unit tests (24) + box integration tests (2).
option (a genuinely unmatched action still reaches authoring through the option (a genuinely unmatched action still reaches authoring through the
intent guard) and traces `create_suppressed` with the probs. An empty intent guard) and traces `create_suppressed` with the probs. An empty
tree/category still short-circuits straight to create. tree/category still short-circuits straight to create.
- **No handle/ignore gate; the `response` tree is the catchall** (Sep 2026):
the top-level `_contains_request` handle/ignore gate is gone. Every input is
scored and dispatched; inputs that are not tasks fall through navigation into
the closed `response` category, a hardcoded tree of canned replies
(`response.greeting`, `response.thanks`, `response.acknowledge`,
`response.farewell`, `response.affirm`, `response.unable`, and the catchall
`response.clarify` — "Could you try being more specific?"). `response` is a
`CANNED_CATEGORIES` member: `navigate` never offers `create_skill` there (the
intent guard is skipped too), `Scheduler._dispatch_skill`/`restart_skill`
refuse to author it, and the runner skips `assess:outcome`/repair for it — a
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.
- **Real integrations, implementation questions, fidelity + repair** (Sep 2026): - **Real integrations, implementation questions, fidelity + repair** (Sep 2026):
elicitation is on by default and asks implementation questions (which elicitation is on by default and asks implementation questions (which
service/account, how to connect, where the credential comes from, what success service/account, how to connect, where the credential comes from, what success
@@ -741,7 +755,7 @@ CLI, unit tests (24) + box integration tests (2).
(a scheduler hook, default `None`) copies that ownership across an updated (a scheduler hook, default `None`) copies that ownership across an updated
request so its completion still routes home. A `needs_input` pause sets request so its completion still routes home. A `needs_input` pause sets
`pending_owner` from the pending run's source; the same chat's next message `pending_owner` from the pending run's source; the same chat's next message
goes straight to `Scheduler.answer` (no gate/score/navigation). A *different* goes straight to `Scheduler.answer` (no score/navigation). A *different*
chat during another chat's pause is told to wait — the single-slot scheduler chat during another chat's pause is told to wait — the single-slot scheduler
must not silently abandon the first chat's run. A background poll calls must not silently abandon the first chat's run. A background poll calls
`Scheduler.run_queue()` (routing each `[run_id] summary` to its owner) and `Scheduler.run_queue()` (routing each `[run_id] summary` to its owner) and
+2 -4
View File
@@ -1,6 +1,6 @@
# Semif Agent # Semif Agent
A local desktop CLI agent whose control flow is a single decision model (SemIf). Inputs are gated, scored, queued, and dispatched through a skill tree; every decision is logged as a labeled training row, and the decision model is fine-tuned at regular intervals on the accumulated prediction-vs-observation cost. A local desktop CLI agent whose control flow is a single decision model (SemIf). Inputs are scored, queued, and dispatched through a skill tree; every decision is logged as a labeled training row, and the decision model is fine-tuned at regular intervals on the accumulated prediction-vs-observation cost. Nothing is gated out up front: every input is dispatched, and inputs that are not tasks fall through navigation into the closed `response` tree of canned replies.
## Engine: SemIf (local decision layer) ## Engine: SemIf (local decision layer)
@@ -13,8 +13,6 @@ A local desktop CLI agent whose control flow is a single decision model (SemIf).
``` ```
intake (typed / events / timers / other skills) intake (typed / events / timers / other skills)
└─ contains_request? (gate: should the agent handle this? the state
carries the user's expectation + available skills)
└─ choice (SemIf: "should this interrupt the current process?") └─ choice (SemIf: "should this interrupt the current process?")
├─ yes → preempt current, requeue it with state preserved ├─ yes → preempt current, requeue it with state preserved
└─ no → score (SemIf: "how urgent?") └─ no → score (SemIf: "how urgent?")
@@ -33,7 +31,7 @@ All decisions are SemIf calls: `{state, question, options[]}`. State is the curr
- **`choice`** — binary: `interrupt` / `defer`. Interrupt iff `P(interrupt) >= τ`. - **`choice`** — binary: `interrupt` / `defer`. Interrupt iff `P(interrupt) >= τ`.
- **`score`** — ordinal urgency: `critical` / `high` / `medium` / `low`, mapped to numeric weights for sorting. - **`score`** — ordinal urgency: `critical` / `high` / `medium` / `low`, mapped to numeric weights for sorting.
- **skill navigation** — at each tree level: choose category / descend; the category level offers a `create_category` suggestion and the leaf level a `create_skill` suggestion. - **skill navigation** — at each tree level: choose category / descend; the category level offers a `create_category` suggestion and the leaf level a `create_skill` suggestion. Inputs that are not tasks descend into the closed `response` category of canned replies (never codegen).
- **`read_next()`** — argument selection within a skill (e.g., which contact is "girlfriend"). - **`read_next()`** — argument selection within a skill (e.g., which contact is "girlfriend").
**LLM/SemIf boundary**: SemIf for fast, repeated, low-latency decisions (gating, scoring, routing, argument selection). LLM for generation and assessment (email body, self-assessment summary). Never the reverse. **LLM/SemIf boundary**: SemIf for fast, repeated, low-latency decisions (gating, scoring, routing, argument selection). LLM for generation and assessment (email body, self-assessment summary). Never the reverse.
+30 -54
View File
@@ -1,8 +1,10 @@
"""The scheduler: gate, choice, score, queue, dispatch. """The scheduler: choice, score, queue, dispatch.
Every SemIf decision (gate, choice, score, navigation, prediction) is logged. Every SemIf decision (choice, score, navigation, prediction) is logged.
A high-priority input can preempt the current process, which requeues with its A high-priority input can preempt the current process, which requeues with its
state preserved; a deferred input is scored and queued by urgency. state preserved; a deferred input is scored and queued by urgency. There is no
up-front handle/ignore gate: every input is dispatched, and inputs that are not
tasks fall through navigation into the closed `response` tree of canned replies.
""" """
from __future__ import annotations from __future__ import annotations
@@ -35,6 +37,8 @@ from .log import DecisionLog
from .queue import UrgencyQueue from .queue import UrgencyQueue
from .skill import SkillRunner from .skill import SkillRunner
from .skills import ( from .skills import (
CANNED_CATEGORIES,
RESPONSE_FALLBACK,
ActionContext, ActionContext,
CategoryRegistry, CategoryRegistry,
CreateCategory, CreateCategory,
@@ -54,12 +58,9 @@ from .skills import (
merge_seed_store, merge_seed_store,
merge_skill_store, merge_skill_store,
navigate, navigate,
tree_summary,
) )
from .trace import TraceLog from .trace import TraceLog
GATE_YES = "yes"
GATE_CAPABILITY_CHARS = 1200
CHOICE_INTERRUPT = "interrupt" CHOICE_INTERRUPT = "interrupt"
URGENCY_OPTIONS = [ URGENCY_OPTIONS = [
("critical", "Immediate danger or critical failure."), ("critical", "Immediate danger or critical failure."),
@@ -70,43 +71,6 @@ URGENCY_OPTIONS = [
URGENCY_WEIGHTS = {"critical": 1.0, "high": 0.75, "medium": 0.5, "low": 0.25} URGENCY_WEIGHTS = {"critical": 1.0, "high": 0.75, "medium": 0.5, "low": 0.25}
def build_gate_decision(request: Request, tree: dict[str, list[Skill]]) -> DecisionRequest:
"""The top-level handle/ignore filter, with end-user expectation and the
agent's real capabilities in the state.
Without them the decision model reads an information request ("tell me the
next event in my nextcloud calendar") as small talk and drops it: "actionable"
implies a side effect, and the model cannot see that looking a value up in a
configured service is exactly what this agent does. The available skills are
listed so a request naming one of them is visibly within the agent's remit.
"""
capabilities = tree_summary(tree)[:GATE_CAPABILITY_CHARS] or " (none yet)"
state = (
f"User input: {request.text}\n"
"[Context: the user is talking to a personal task agent. Any imperative "
"request to perform a task — send, message, tell, check, create, remind, "
"or look something up — must be handled, even if no skill matches yet. "
"Only chatter, thanks, and bare greetings should be ignored.]\n"
f"[Available skills:\n{capabilities}]"
)
return DecisionRequest(
state=state,
question="Should the agent handle this input?",
options=[
Option(
GATE_YES,
"Yes — do what it asks, including looking something up, reporting "
"information, or performing an action using the agent's skills.",
),
Option(
"no",
"No — it is not a request for the agent to do or answer anything "
"(background text, noise, or a bare greeting).",
),
],
)
@dataclass @dataclass
class Process: class Process:
request: Request request: Request
@@ -296,14 +260,6 @@ class Scheduler:
# ---- decision templates (all real SemIf, all logged) ---- # ---- decision templates (all real SemIf, all logged) ----
def _contains_request(self, request: Request) -> bool:
decision = build_gate_decision(request, self.tree)
result = self.engine.call(decision)
self.log.append(
decision, result, extra={"phase": "gate", "run_id": request.id}
)
return result.prob(GATE_YES) >= self.tau
def _choice(self, request: Request, current: Process) -> bool: def _choice(self, request: Request, current: Process) -> bool:
decision = DecisionRequest( decision = DecisionRequest(
state=compose_state(request, current=current.skill), state=compose_state(request, current=current.skill),
@@ -362,9 +318,6 @@ class Scheduler:
def _submit_locked(self, text: str, source: str = "typed") -> tuple[str, str, str]: def _submit_locked(self, text: str, source: str = "typed") -> tuple[str, str, str]:
request = Request(text, source=source) request = Request(text, source=source)
self.trace.append("submit", request.id, text=text, source=source) self.trace.append("submit", request.id, text=text, source=source)
if not self._contains_request(request):
self.trace.append("dropped", request.id, reason="no actionable request")
return "dropped", "no actionable request", request.id
if self.current is None: if self.current is None:
weight, label = self._score(request) weight, label = self._score(request)
@@ -473,7 +426,20 @@ class Scheduler:
return created return created
return self._dispatch_skill(request, created.skill, weight) return self._dispatch_skill(request, created.skill, weight)
if isinstance(navigation, CreateSkill): if isinstance(navigation, CreateSkill):
if navigation.category in CANNED_CATEGORIES:
fallback = self._canned_fallback(navigation.category)
if fallback is not None:
self.trace.append(
"create_suppressed",
request.id,
level="canned_category",
category=navigation.category,
fallback=fallback.name,
)
return self._run_skill(fallback, request)
return self._dispatch_skill(request, navigation.category, weight) return self._dispatch_skill(request, navigation.category, weight)
if navigation.category in CANNED_CATEGORIES:
return self._run_skill(navigation, request)
if not confirm_skill_fit( if not confirm_skill_fit(
self.engine, self.log, self.trace, request, navigation, self.tau self.engine, self.log, self.trace, request, navigation, self.tau
): ):
@@ -486,6 +452,14 @@ class Scheduler:
return self._dispatch_skill(request, navigation.category, weight) return self._dispatch_skill(request, navigation.category, weight)
return self._run_skill(navigation, request) return self._run_skill(navigation, request)
def _canned_fallback(self, category: str) -> Skill | None:
"""The catchall canned reply for a closed category, else its first leaf."""
skills = self.tree.get(category, [])
for skill in skills:
if skill.name == RESPONSE_FALLBACK:
return skill
return skills[0] if skills else None
def _dispatch_skill( def _dispatch_skill(
self, request: Request, category: str, weight: float = 0.0 self, request: Request, category: str, weight: float = 0.0
) -> DispatchResult: ) -> DispatchResult:
@@ -1587,6 +1561,8 @@ class Scheduler:
) )
if leaf is None: if leaf is None:
return "error", f"no skill {category}.{name}" return "error", f"no skill {category}.{name}"
if category in CANNED_CATEGORIES:
return "error", f"{category} is a closed canned tree; there is no body to write"
if leaf.writing: if leaf.writing:
return "error", f"skill {category}.{name} is already being written" return "error", f"skill {category}.{name} is already being written"
if self.codegen is None: if self.codegen is None:
+14
View File
@@ -23,6 +23,7 @@ from dataclasses import dataclass
from .decisions import DecisionRequest, Option, Request from .decisions import DecisionRequest, Option, Request
from .log import DecisionLog from .log import DecisionLog
from .skills import ( from .skills import (
CANNED_CATEGORIES,
ActionContext, ActionContext,
Prediction, Prediction,
Skill, Skill,
@@ -301,6 +302,19 @@ class SkillRunner:
self, skill: Skill, request: Request, prediction: Prediction | None, action self, skill: Skill, request: Request, prediction: Prediction | None, action
) -> RunResult: ) -> RunResult:
observed = action.new_state observed = action.new_state
if skill.category in CANNED_CATEGORIES:
summary = deterministic_summary(
skill.category, skill.name, True, action.action_log, observed
)
return RunResult(
skill=skill.name,
success=True,
summary=summary,
action_log=action.action_log,
new_state=observed,
assessment_summary=summary,
prediction=prediction,
)
success, updated_request = self._assess(skill, request, action) success, updated_request = self._assess(skill, request, action)
decisions = getattr(prediction, "decisions", []) decisions = getattr(prediction, "decisions", [])
+111 -7
View File
@@ -470,9 +470,64 @@ def compose_state(request: Request, current: str | None = None) -> str:
return " ".join(parts) return " ".join(parts)
def _response_reject(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult: def _canned_predict(ctx: ActionContext, request: Request) -> Prediction:
message = f"Rejected: I cannot act on this while busy ({request.text})." return Prediction(text="")
return ActionResult(action_log=f"response.reject: {message}", new_state=message)
def _canned_response(name: str, message: str):
"""An act that returns a fixed line. No transport, no generation, no config."""
def act(ctx: ActionContext, request: Request, prediction: Prediction) -> ActionResult:
return ActionResult(action_log=f"{name}: {message}", new_state=message)
return act
# The `response` category is a closed tree of canned replies: it never authors a
# skill (no create route) and its runs are not assessed (there is no side effect
# to succeed or fail). Every non-task input lands here instead of being gated.
CANNED_CATEGORIES = frozenset({"response"})
RESPONSE_FALLBACK = "response.clarify"
_CANNED_RESPONSES = [
(
"greeting",
"The user is greeting the agent (hello, hi, good morning).",
"Hello! What can I help you with?",
),
(
"thanks",
"The user is thanking the agent.",
"You're welcome! Anything else?",
),
(
"acknowledge",
"The user is acknowledging or making filler the agent should nod to.",
"Got it.",
),
(
"farewell",
"The user is signing off (bye, goodbye, see you).",
"Goodbye! Talk to you later.",
),
(
"affirm",
"The user is agreeing or confirming (yes, ok, sure, sounds good).",
"Okay!",
),
(
"unable",
"A request the agent understands but has no way to perform.",
"I'm not able to do that yet.",
),
(
"clarify",
"The input is too vague to act on; ask the user to be more specific.",
"Could you try being more specific?",
),
]
_RESPONSE_MESSAGES = {f"response.{name}": message for name, _, message in _CANNED_RESPONSES}
def build_skills(config: dict) -> list[Skill]: def build_skills(config: dict) -> list[Skill]:
@@ -483,17 +538,24 @@ def build_skills(config: dict) -> list[Skill]:
`seeds/`. A fabricated built-in here shadows the authoring path for a real `seeds/`. A fabricated built-in here shadows the authoring path for a real
one (navigation routes to it), so keep this list to behaviors that need no one (navigation routes to it), so keep this list to behaviors that need no
external service. external service.
The `response` category is a closed tree of canned replies (see
CANNED_CATEGORIES): it is the catchall for inputs that are not tasks, and it
never goes through codegen.
""" """
return [ return [
Skill( Skill(
name="response.reject", name=f"response.{name}",
category="response", category="response",
description="Politely reject a request because the agent is busy.", description=description,
act=_response_reject, predict=_canned_predict,
), act=_canned_response(f"response.{name}", message),
)
for name, description, message in _CANNED_RESPONSES
] ]
def build_tree(skills: list[Skill]) -> dict[str, list[Skill]]: def build_tree(skills: list[Skill]) -> dict[str, list[Skill]]:
tree: dict[str, list[Skill]] = {} tree: dict[str, list[Skill]] = {}
for skill in skills: for skill in skills:
@@ -551,6 +613,46 @@ def _clears_create_gate(
return create_p >= tau and (create_p - best) >= margin return create_p >= tau and (create_p - best) >= margin
def _navigate_canned(
engine: SemIfEngine,
log: DecisionLog,
trace: TraceLog,
request: Request,
category: str,
skills: list[Skill],
) -> Skill:
"""Pick one canned reply from a closed category. No create branch, ever.
The catchall (`RESPONSE_FALLBACK`) is offered last so the decision question
can point at it by name; it is the answer when nothing specific fits.
"""
ordered = [s for s in skills if not s.is_noop()] or list(skills)
fallback = next((s for s in ordered if s.name == RESPONSE_FALLBACK), None)
ordered = [s for s in ordered if s is not fallback] + ([fallback] if fallback else [])
if len(ordered) == 1:
return ordered[0]
leaf = DecisionRequest(
state=compose_state(request, current=category),
question=(
"Which canned response best fits this input? "
f"Choose {ordered[-1].name} if none of the others does."
),
options=[Option(s.name, s.description) for s in ordered],
)
result = engine.call(leaf)
log.append(leaf, result, extra={"phase": "navigate:response", "run_id": request.id})
chosen = next((s for s in ordered if s.name == result.selected), ordered[-1])
trace.append(
"response_selected",
request.id,
category=category,
skill=chosen.name,
selected=result.selected,
probs=result.probs,
)
return chosen
def navigate( def navigate(
engine: SemIfEngine, engine: SemIfEngine,
log: DecisionLog, log: DecisionLog,
@@ -625,6 +727,8 @@ def navigate(
) )
return CreateCategory() return CreateCategory()
skills = tree[category] skills = tree[category]
if category in CANNED_CATEGORIES:
return _navigate_canned(engine, log, trace, request, category, skills)
create_skill = Option( create_skill = Option(
"create_skill", "create_skill",
"No existing skill performs this action; create a new skill for it.", "No existing skill performs this action; create a new skill for it.",
+16 -32
View File
@@ -140,15 +140,10 @@ def test_pipeline_end_to_end(tmp_path):
assert "queue:" in skills assert "queue:" in skills
def test_gate_accepts_information_requests_and_rejects_noise(tmp_path): def test_navigation_routes_noise_into_the_response_tree(tmp_path):
"""Regression: the gate must not drop lookups phrased as questions. """There is no up-front handle/ignore gate any more: every input is
dispatched, and chatter that is not a task must land in the closed `response`
Before the gate state carried the end-user expectation and the available tree (a canned reply), never in an integration category or codegen."""
skills, "tell me the next event in my nextcloud calendar" scored 0.599
(just under tau 0.6) and "what is the next event in my nextcloud calendar?"
scored 0.191, so both were dropped as "no actionable request". All lookup
variants must pass now, while chatter stays out.
"""
config = load_config() config = load_config()
require_real(config) require_real(config)
_isolate_runtime(config, tmp_path) _isolate_runtime(config, tmp_path)
@@ -157,32 +152,21 @@ def test_gate_accepts_information_requests_and_rejects_noise(tmp_path):
lookups = [ lookups = [
"tell me the next event in my nextcloud calendar", "tell me the next event in my nextcloud calendar",
"what is the next event in my nextcloud calendar?", "what is the next event in my nextcloud calendar?",
"what is the next event in my nextcloud calendar Morgan",
"tell me the next event in my nextcloud calendar Morgan",
"tell me the next even in my calendar", "tell me the next even in my calendar",
"tell me the next event in my personal calendar",
]
# Imperative tasks with no matching skill are still actionable: the agent
# learns them. Regression: "send a simplex message to pepper saying hi"
# scored 0.135 and was dropped as "no actionable request".
tasks = [
"send a simplex message to pepper saying hi",
"send a simplex message to pepper that says hello back to them",
"send a new simplex message to pepper: hey",
"send a simplex message",
"email Sam about lunch",
] ]
noise = ["hello there", "thanks!", "the sky is blue", "what's up"] noise = ["hello there", "thanks!", "the sky is blue", "what's up"]
for text in lookups + tasks: for text in lookups:
accepted = scheduler._contains_request(Request(text)) result = navigate(
row = scheduler.log.read()[-1] scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
print(f"[task] {row['predicted_probs']} accepted={accepted} {text!r}") )
assert accepted, f"gate dropped a task: {text!r}" print(f"[lookup] {text!r} -> {result!r}")
assert getattr(result, "category", None) == "calendar", f"lookup misrouted: {text!r}"
for text in noise: for text in noise:
accepted = scheduler._contains_request(Request(text)) result = navigate(
row = scheduler.log.read()[-1] scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
print(f"[noise] {row['predicted_probs']} accepted={accepted} {text!r}") )
assert not accepted, f"gate accepted noise: {text!r}" print(f"[noise] {text!r} -> {result!r}")
assert getattr(result, "category", None) == "response", f"noise left the response tree: {text!r}"
def test_navigate_routes_unmatched_action_to_create_skill(tmp_path): def test_navigate_routes_unmatched_action_to_create_skill(tmp_path):
@@ -252,7 +236,7 @@ def test_busy_choice_path(tmp_path):
scheduler.busy("driving on the freeway", skill="driving") scheduler.busy("driving on the freeway", skill="driving")
status, detail = scheduler.submit("tell me if my package was delivered") status, detail = scheduler.submit("tell me if my package was delivered")
print(f"[{status}] {detail}") print(f"[{status}] {detail}")
assert status in ("preempted", "queued", "dropped") assert status in ("preempted", "queued")
scheduler.idle() scheduler.idle()
+2 -2
View File
@@ -34,11 +34,11 @@ def test_result_selected_and_probs():
def test_request_requeue_preserves_state(): def test_request_requeue_preserves_state():
original = Request(text="t", priority=0.7) original = Request(text="t", priority=0.7)
original.resume["from_skill"] = "response.reject" original.resume["from_skill"] = "response.clarify"
updated = original.copy_for_requeue() updated = original.copy_for_requeue()
assert updated.id == original.id assert updated.id == original.id
assert updated.priority == original.priority assert updated.priority == original.priority
assert updated.resume["from_skill"] == "response.reject" assert updated.resume["from_skill"] == "response.clarify"
assert updated.reentries == original.reentries + 1 assert updated.reentries == original.reentries + 1
+1 -1
View File
@@ -84,7 +84,7 @@ def test_tree_endpoint(tmp_path):
status, payload = server.get("/api/tree") status, payload = server.get("/api/tree")
assert status == 200 assert status == 200
assert "response" in payload["categories"] assert "response" in payload["categories"]
assert any(s["name"] == "response.reject" for s in payload["categories"]["response"]) assert any(s["name"] == "response.clarify" for s in payload["categories"]["response"])
finally: finally:
server.close() server.close()
+61 -37
View File
@@ -29,7 +29,6 @@ from semif_agent.scheduler import (
RepairOffer, RepairOffer,
Scheduler, Scheduler,
SkillWrite, SkillWrite,
build_gate_decision,
) )
from semif_agent.skills import ( from semif_agent.skills import (
ActionResult, ActionResult,
@@ -218,14 +217,19 @@ def test_build_category_prompt_contains_request_and_tree():
assert "category" in messages[0]["content"] assert "category" in messages[0]["content"]
joined = messages[1]["content"] joined = messages[1]["content"]
assert "tracking for my drone delivery" in joined assert "tracking for my drone delivery" in joined
assert "response: response.reject" in joined assert "response: response.acknowledge" in joined
def test_build_skills_is_internal_behaviors_only(): def test_build_skills_are_canned_responses_only():
"""Real integrations are generated or seeded, never fabricated here: a """Real integrations are generated or seeded, never fabricated here: a
hardcoded fake shadows the authoring path for a real skill (navigation hardcoded fake shadows the authoring path for a real skill (navigation
routes to it). Only service-free behaviors stay built-in.""" routes to it). The only built-ins are the closed `response` canned tree."""
assert [skill.name for skill in build_skills({"skills": {}})] == ["response.reject"] skills = build_skills({"skills": {}})
names = [skill.name for skill in skills]
assert names and all(name.startswith("response.") for name in names)
assert "response.clarify" in names
assert all(skill.category == "response" for skill in skills)
assert not any(skill.is_noop() for skill in skills)
def test_parse_category_draft_plain_json(): def test_parse_category_draft_plain_json():
@@ -535,44 +539,63 @@ def test_navigate_empty_tree_short_circuits(tmp_path):
assert any(e["kind"] == "create_category" for e in trace.read()) assert any(e["kind"] == "create_category" for e in trace.read())
def test_gate_decision_carries_expectation_and_capabilities(): def test_navigate_canned_category_never_offers_create(tmp_path):
"""The gate must know the user expects handling and what the agent can """The `response` tree is closed: its leaf choice has no create_skill option
actually do; without that context, lookups are read as small talk and and never authors, regardless of how weak the match is."""
dropped (the nextcloud calendar regression).""" log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
tree = build_tree(build_skills({"skills": {}})) tree = build_tree(build_skills({"skills": {}}))
tree["calendar"] = [
Skill(name="next_event", category="calendar", description="Report the next event.") class Recording:
] def __init__(self):
decision = build_gate_decision( self.request = None
Request("tell me the next event in my nextcloud calendar"), tree
) def call(self, request):
assert "tell me the next event in my nextcloud calendar" in decision.state from semif_agent.decisions import DecisionResult
assert "perform a task" in decision.state
assert "look something up" in decision.state self.request = request
assert "calendar: next_event" in decision.state ids = [o.id for o in request.options]
assert decision.question == "Should the agent handle this input?" return DecisionResult(request=request, option_ids=ids, probabilities=[1.0] * len(ids))
assert [o.id for o in decision.options] == ["yes", "no"]
assert "performing an action" in decision.options[0].description engine = Recording()
assert "greeting" in decision.options[1].description result = navigate(engine, log, trace, Request("hello there"), tree)
assert isinstance(result, Skill)
assert result.category == "response"
assert all(o.id != "create_skill" for o in engine.request.options)
assert "create_skill" not in [o.id for o in engine.request.options]
assert result.name in [o.id for o in engine.request.options]
def test_gate_decision_accepts_imperative_tasks_with_no_matching_skill(): def test_navigate_canned_category_points_at_the_catchall(tmp_path):
"""A request to do something the tree has no skill for is still actionable — """The catchall is offered last and named in the question when nothing
the agent learns it. Regression: 'send a simplex message to pepper saying specific fits."""
hi' scored 0.135 and was dropped as 'no actionable request' because the gate log = DecisionLog(str(tmp_path / "decisions.jsonl"))
context only vouched for lookups.""" trace = TraceLog(str(tmp_path / "runs.jsonl"))
tree = build_tree(build_skills({"skills": {}})) tree = build_tree(build_skills({"skills": {}}))
tree["simplex"] = [ engine = _ProbEngine({"canned response": {"response.clarify": 1.0}})
Skill(name="next_message", category="simplex", description="Read the next SimpleX message."), result = navigate(engine, log, trace, Request("do the thing"), tree)
] assert result.name == "response.clarify"
decision = build_gate_decision(Request("send a simplex message to pepper saying hi"), tree) leaf = engine.calls[-1]
assert "even if no skill matches yet" in decision.state assert "response.clarify" in leaf.question
assert leaf.options[-1].id == "response.clarify"
assert "navigate:response" in [r["extra"]["phase"] for r in log.read()]
def test_gate_decision_empty_tree_still_builds(): def test_canned_response_runs_without_assessment(tmp_path):
decision = build_gate_decision(Request("hello"), {}) """A canned reply is a fixed line: no side effect to assess, no repair loop.
assert "(none yet)" in decision.state The runner returns success without an assess:outcome decision."""
assert decision.options[0].id == "yes" from semif_agent.skill import SkillRunner
from semif_agent.skills import ActionContext
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
skill = next(s for s in build_skills({"skills": {}}) if s.name == "response.greeting")
runner = SkillRunner(ActionContext(engine=_ProbEngine({}), config={}), log)
outcome = runner.run(skill, Request("hello"))
assert outcome.success is True
assert outcome.new_state == "Hello! What can I help you with?"
assert outcome.error is None
assert log.read() == []
def test_navigate_leaf_offers_create_for_unmatched_action(tmp_path): def test_navigate_leaf_offers_create_for_unmatched_action(tmp_path):
@@ -769,6 +792,7 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
tmp_path, tmp_path,
choices={"same action": "different"}, choices={"same action": "different"},
) )
scheduler.tree.pop("response", None)
scheduler.tree["simplex"] = [ scheduler.tree["simplex"] = [
Skill(name="next_message", category="simplex", description="Read the next SimpleX message."), Skill(name="next_message", category="simplex", description="Read the next SimpleX message."),
] ]