Compare commits

..
2 Commits
Author SHA1 Message Date
gabby da53e1eefc Merge remote-tracking branch 'origin/main' into main
Resolve the navigate() leaf conflict: keep the local two-stage navigation
refactor (descriptions, confirm_category_fit, create_skill removed from the
leaf softmax) and apply origin's compose_state intent on top.

origin/main (857ad1a) was not runnable as pushed:
- compose_state renamed its param to additional_context but its body still
  read `current` (NameError) and _navigate_canned called it with a stray
  `additional_context:` annotation (SyntaxError).
- the rename was not propagated to scheduler.py's two callers (TypeError).

Resolution:
- compose_state(request, additional_context=None) renders `({additional_context})`.
- canned + navigate leaf decisions pass
  additional_context=f"all choices are within the {category} category".
- scheduler.py builds its state inline to keep the exact
  `[current process: …]` wording for the interrupt/priority decisions.
2026-10-01 20:16:43 +00:00
gabby de78a0e96a tune category selection 2026-10-01 14:16:29 +00:00
9 changed files with 662 additions and 241 deletions

No files matched your search

+23 -8
View File
@@ -313,14 +313,29 @@ CLI, unit tests (24) + box integration tests (2).
graceful (traced `draft_failed`, user notified, request not re-dispatched); graceful (traced `draft_failed`, user notified, request not re-dispatched);
only SemIf availability is fatal. Authoring is still a single pass — only SemIf availability is fatal. Authoring is still a single pass —
validating/reusing written bodies across runs is future work. validating/reusing written bodies across runs is future work.
**Create-branch confidence gate** (Sep 2026): `create_skill`/`create_category` **Navigation is two-stage at both levels; the guards are the create doors**
compete in a softmax with the real options, so a weak plurality win is not (Oct 2026). Category level: the softmax offers every existing category **with
evidence that nothing matches. Navigation fires a create branch only when its description** plus `create_category`, and the winner is confirmed by
`P(create) >= navigation.create_tau` **and** it leads the best existing option `confirm_category_fit` (phase `navigate:category_scope`, P(covers) >=
by `navigation.create_margin`; otherwise it falls back to the best existing `navigation.category_tau`); a rejected winner or a `create_category` win
option (a genuinely unmatched action still reaches authoring through the authors a new category. Descriptions are load-bearing — with bare names the
intent guard) and traces `create_suppressed` with the probs. An empty model sent "book a flight to japan" to `simplex` (0.49 vs create_category
tree/category still short-circuits straight to create. 0.12); with descriptions it picks `create_category` 0.87. `Skill` carries
`category_description`, seeded by `CATEGORY_DESCRIPTIONS` for the built-ins
(response/calendar/simplex) and read from the registry for authored
categories; `category_descriptions(tree)` collapses it per category so an
empty bucket is never offered bare. The old category threshold gate
(`create_tau`/`create_margin`) is **retired**. Leaf level: the softmax
contains **only existing skills** — `create_skill` was removed because sharing
a softmax with the real skills diluted its probability and let a crowded tree
drift into create on a weak plurality (real runs scored `create_skill`
0.585–0.803 on requests a seed skill clearly matched). The reuse-vs-create
decision is the **intent guard** (`confirm_skill_fit`, phase
`navigate:intent`) at `navigation.intent_tau`. Both taus are separate from the
top-level `tau`, so tuning reuse-vs-create does not move
assessment/fidelity. The guards are deliberately permissive (in-scope scores
0.9–1.0): a borderline over-cover routes into a plausible category and the
leaf guard catches it. Empty and single-skill categories skip their softmax.
- **No handle/ignore gate; the `response` tree is the catchall** (Sep 2026): - **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 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 scored and dispatched; inputs that are not tasks fall through navigation into
+22 -12
View File
@@ -112,17 +112,27 @@ Skills are leaves: categories → skills → actions. Navigation is a chain of S
choices, one per level (`navigate` in `semif_agent/skills.py`), and **every choices, one per level (`navigate` in `semif_agent/skills.py`), and **every
choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`). choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`).
- The category level offers a `create_category` branch; the leaf level offers - **Two-stage at both levels; the guards are the create doors.**
`create_skill`. - **Category.** The softmax offers every existing category **with its
- **Create-confidence gate.** `create_skill`/`create_category` share a softmax description** plus a `create_category` branch, and the winner is confirmed by
with the real options, so a weak plurality win is not evidence that nothing the **scope guard** (`confirm_category_fit`, phase `navigate:category_scope`):
matches. A create branch fires only when `P(create) >= navigation.create_tau` a name-anchored SemIf check at `navigation.category_tau` asking whether that
**and** it leads the best existing option by `navigation.create_margin`; category's scope covers the request. Confirmed → descend; rejected (or a
otherwise navigation falls back to the best existing option and traces `create_category` win) → author a new category. Descriptions are load-bearing:
`create_suppressed` with the probabilities. An empty tree/category still with bare names the model sent "book a flight to japan" to `simplex` (0.49 vs
short-circuits straight to create. `create_category` 0.12); with descriptions it picks `create_category` 0.87.
- There is a second door to authoring: an **intent guard** An empty tree short-circuits straight to create.
(`confirm_skill_fit`, phase `navigate:intent`) for genuinely unmatched actions. - **Leaf.** The leaf softmax picks only among the existing skills (a create
option diluted its probability and let a crowded tree drift into create on a
weak plurality). The picked skill then goes through the **intent guard**
(`confirm_skill_fit`, phase `navigate:intent`): an action comparison at
`navigation.intent_tau` asking whether the skill performs the same action the
request asks for. Same → run it; different → author a new leaf in that
category. An empty (or single-skill) category skips the softmax and goes
straight to the guard.
- Both guards are deliberately permissive; with real descriptions the in-scope
cases score 0.9–1.0, so a borderline over-cover routes into a plausible
category and the leaf guard catches it.
### The skill run loop ### The skill run loop
@@ -463,7 +473,7 @@ Key blocks:
| `engine` | SemIf source/revision, GGUF path, context, threads | | `engine` | SemIf source/revision, GGUF path, context, threads |
| `llm` | small model endpoint that authors new category/skill title + description | | `llm` | small model endpoint that authors new category/skill title + description |
| `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget | | `codegen` | skill-body model endpoint, timeouts, sampler, elicitation, fidelity, repair, test, degeneration watchdog, token budget |
| `navigation` | create-gate `create_tau` / `create_margin` | | `navigation` | two-stage guards: leaf `intent_tau`, category `category_tau` |
| `tau` | decision threshold; `max_reentries` requeue bound | | `tau` | decision threshold; `max_reentries` requeue bound |
| `queue` | `max_size`, `age_rate` | | `queue` | `max_size`, `age_rate` |
| `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) | | `skill_bodies` / `skill_seeds` / `log` / `trace` / `category_registry` | runtime paths (anchored to the checkout) |
+3 -3
View File
@@ -3,9 +3,9 @@
"tau": 0.6, "tau": 0.6,
"max_reentries": 3, "max_reentries": 3,
"navigation": { "navigation": {
"_comment": "Confidence gate on the create branches. create_skill/create_category share a softmax with the real skills/categories, so a weak plurality win is not evidence that nothing matches. The create branch only fires when P(create) >= create_tau AND it leads the best existing option by create_margin; otherwise navigation falls back to the best existing option (a genuinely unmatched action still reaches authoring through the intent guard). Suppressed picks are traced as create_suppressed with their probs so the thresholds can be calibrated from real runs. A level with nothing to choose from still short-circuits to create.", "_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.",
"create_tau": 0.5, "intent_tau": 0.6,
"create_margin": 0.35 "category_tau": 0.75
}, },
"queue": {"max_size": 100, "age_rate": 0.01}, "queue": {"max_size": 100, "age_rate": 0.01},
"engine": { "engine": {
View File
Whitespace-only changes.
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env python3
"""Tune the two-stage navigation guards.
Navigation is two-stage at both levels, and the guards are the create doors:
- **Category**: the softmax offers every existing category WITH its description
plus `create_category`; `confirm_category_fit` confirms the winner's scope.
`navigation.category_tau` is that guard's P(covers) floor.
- **Leaf**: the softmax offers only existing skills; `confirm_skill_fit`
compares the winner's action to the request. `navigation.intent_tau` is that
guard's P(same) floor.
This replays a hand-labeled eval set through the **real** decision engine and
the **real** skill tree, measuring each guard's probability per request so the
floors can be placed between the true matches and the true mismatches. Run it on
a box with the pinned engine (jarvis):
.runtime/venv/bin/python scripts/tune_navigation.py
.runtime/venv/bin/python scripts/tune_navigation.py --level leaf --tau 0.6
The tree is whatever the box currently has loaded (committed seeds + the runtime
`data/skills/`), so an expectation naming a skill that is not present is
reported as N/A rather than counted wrong. Labels are hand-written ground truth;
self-labeled decision rows are not evidence. Nothing is written to the runtime
logs.
"""
from __future__ import annotations
import argparse
import sys
import tempfile
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO))
from semif_agent.cli import build_scheduler, load_config
from semif_agent.decisions import Request
from semif_agent.log import DecisionLog
from semif_agent.skills import (
CreateCategory,
category_descriptions,
confirm_category_fit,
confirm_skill_fit,
navigate,
)
from semif_agent.trace import TraceLog
# (request, expected) at the LEAF level: "category.skill" or "create".
LEAF_EVAL: list[tuple[str, str]] = [
("what is my next message on simplex?", "simplex.next_message"),
("check my next message on simplex", "simplex.next_message"),
("read the next simplex message", "simplex.next_message"),
("show me my simplex messages", "simplex.next_message"),
('send a message on simplex to pepper: "hey!"', "simplex.send_simplex_message"),
("send a simplex message to pepper saying hi", "simplex.send_simplex_message"),
("what is my simplex connection link?", "simplex.connect_link"),
("give me my simplex contact link", "simplex.connect_link"),
("tell me the next event in my nextcloud calendar", "calendar.next_event"),
("translate my last simplex message to French", "create"),
("delete my next simplex message", "create"),
("book a flight to japan", "create"),
]
# (request, expected) at the CATEGORY level: a category name or "create".
CATEGORY_EVAL: list[tuple[str, str]] = [
("what is my next message on simplex?", "simplex"),
("send a simplex message to pepper saying hi", "simplex"),
("what is my simplex connection link?", "simplex"),
("tell me the next event in my nextcloud calendar", "calendar"),
("hello there", "response"),
("thanks!", "response"),
("book a flight to japan", "create"),
("what is the weather in paris", "create"),
("order me a pizza", "create"),
("tell me if my package was delivered", "create"),
]
SWEEP = [0.30, 0.40, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90]
def _present(tree: dict, qualified: str) -> bool:
if qualified == "create":
return True
if "." not in qualified:
return qualified in tree
category, _, name = qualified.partition(".")
return any(s.name == name for s in tree.get(category, []))
def measure(
scheduler, log, trace, request: Request, level: str, tau: float
) -> dict:
"""Run one navigation pass and return the guard probability for `level`."""
before = len(trace.read())
nav = navigate(
scheduler.engine, log, trace, request, scheduler.tree, category_tau=tau
)
events = trace.read()[before:]
if level == "category":
if isinstance(nav, CreateCategory):
return {"picked": "create", "p": None}
# navigate already ran the guard internally; read its event.
guard = next((e for e in events if e["kind"] == "category_scope"), None)
return {"picked": nav.category, "p": guard["probs"]["covers"] if guard else None}
# leaf: navigate returns a Skill, CreateSkill, or CreateCategory.
if not hasattr(nav, "name"):
return {"picked": "create", "p": None}
confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau)
events = trace.read()[before:]
guard = next((e for e in events if e["kind"] == "intent_guard"), None)
return {"picked": f"{nav.category}.{nav.name}", "p": guard["probs"]["same"] if guard else None}
def verdict(measured: dict, tau: float) -> str:
if measured["p"] is None:
return measured["picked"]
if measured["p"] >= tau:
return measured["picked"]
return "create"
def run_level(scheduler, log, trace, level: str, tau: float, eval_set, sweep) -> None:
print(f"### {level.upper()} level (real engine; ~1s/decision)\n")
results = []
for text, expected in eval_set:
present = _present(scheduler.tree, expected)
measured = measure(scheduler, log, trace, Request(text), level, tau)
results.append((text, expected, present, measured))
print(f"{'request':52s} {'picked':28s} {'p':>8s} {'expected':24s}")
print("-" * 116)
for text, expected, present, m in results:
picked = m["picked"] or "(create)"
p = f"{m['p']:.3f}" if m["p"] is not None else " -"
exp = expected + ("" if present else " [N/A]")
print(f"{text[:52]:52s} {picked:28s} {p:>8s} {exp:24s}")
print(f"\n{'tau':>6s} {'correct':>8s} {'false_create':>13s} {'false_reuse':>12s} {'na':>4s}")
print("-" * 46)
for t in sweep:
correct = fc = fr = na = 0
for _text, expected, present, m in results:
if not present:
na += 1
continue
got = verdict(m, t)
if got == expected:
correct += 1
elif expected == "create":
fr += 1
else:
fc += 1
print(f"{t:6.2f} {correct:8d} {fc:13d} {fr:12d} {na:4d}")
print()
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", default=str(REPO / "config.json"))
parser.add_argument("--tau", type=float, default=None, help="report a single tau only")
parser.add_argument(
"--level", choices=["leaf", "category", "both"], default="both"
)
args = parser.parse_args()
config = load_config(args.config)
scheduler, _ = build_scheduler(config)
scratch = Path(tempfile.mkdtemp(prefix="tune_navigation."))
log = DecisionLog(str(scratch / "decisions.jsonl"))
trace = TraceLog(str(scratch / "runs.jsonl"))
sweep = [args.tau] if args.tau is not None else SWEEP
if args.level in ("category", "both"):
run_level(
scheduler, log, trace, "category", args.tau or 0.5, CATEGORY_EVAL, sweep
)
if args.level in ("leaf", "both"):
run_level(scheduler, log, trace, "leaf", args.tau or 0.6, LEAF_EVAL, sweep)
print(
"false_create = should have reused something existing but authored a new one\n"
"false_reuse = should have authored something new but used an existing one"
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+7 -10
View File
@@ -49,7 +49,6 @@ from .skills import (
SkillStore, SkillStore,
build_skills, build_skills,
build_tree, build_tree,
compose_state,
confirm_skill_fit, confirm_skill_fit,
generate_category, generate_category,
generate_skill, generate_skill,
@@ -198,8 +197,8 @@ class Scheduler:
self.config = config self.config = config
self.tau = tau self.tau = tau
nav_cfg = config.get("navigation", {}) or {} nav_cfg = config.get("navigation", {}) or {}
self.create_tau = float(nav_cfg.get("create_tau", 0.5)) self.intent_tau = float(nav_cfg.get("intent_tau", 0.6))
self.create_margin = float(nav_cfg.get("create_margin", 0.35)) self.category_tau = float(nav_cfg.get("category_tau", 0.75))
self.max_reentries = max_reentries self.max_reentries = max_reentries
self.codegen = codegen self.codegen = codegen
self.degeneration_check_factory = degeneration_check_factory self.degeneration_check_factory = degeneration_check_factory
@@ -273,7 +272,7 @@ class Scheduler:
def _interrupt_choice(self, request: Request, current: Process) -> bool: def _interrupt_choice(self, request: Request, current: Process) -> bool:
decision = DecisionRequest( decision = DecisionRequest(
state=compose_state(request, current=current.skill), state=f"{request.text} [current process: {current.skill}]",
question="Should this be allowed to interrupt the current process?", question="Should this be allowed to interrupt the current process?",
options=[ options=[
Option(CHOICE_INTERRUPT, "Yes, interrupt the current process."), Option(CHOICE_INTERRUPT, "Yes, interrupt the current process."),
@@ -290,7 +289,7 @@ class Scheduler:
def _priority_score(self, request: Request, current: str | None = None) -> tuple[float, str]: def _priority_score(self, request: Request, current: str | None = None) -> tuple[float, str]:
decision = DecisionRequest( decision = DecisionRequest(
state=compose_state(request, current=current), state=f"{request.text} [current process: {current}]",
question="How urgent is this request?", question="How urgent is this request?",
options=[Option(option_id, description) for option_id, description in URGENCY_OPTIONS], options=[Option(option_id, description) for option_id, description in URGENCY_OPTIONS],
) )
@@ -428,8 +427,7 @@ class Scheduler:
self.trace, self.trace,
request, request,
self.tree, self.tree,
create_tau=self.create_tau, category_tau=self.category_tau,
create_margin=self.create_margin,
) )
if isinstance(navigation, CreateCategory): if isinstance(navigation, CreateCategory):
return self._dispatch_create_category(request, weight) return self._dispatch_create_category(request, weight)
@@ -438,9 +436,8 @@ class Scheduler:
fallback = self._canned_fallback(navigation.category) fallback = self._canned_fallback(navigation.category)
if fallback is not None: if fallback is not None:
self.trace.append( self.trace.append(
"create_suppressed", "canned_fallback",
request.id, request.id,
level="canned_category",
category=navigation.category, category=navigation.category,
fallback=fallback.name, fallback=fallback.name,
) )
@@ -449,7 +446,7 @@ class Scheduler:
if navigation.category in CANNED_CATEGORIES: if navigation.category in CANNED_CATEGORIES:
return self._run_skill(navigation, request) 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.intent_tau
): ):
self.trace.append( self.trace.append(
"intent_mismatch", "intent_mismatch",
+174 -98
View File
@@ -59,6 +59,7 @@ class Skill:
contract: dict = field(default_factory=dict) contract: dict = field(default_factory=dict)
integration: dict = field(default_factory=dict) integration: dict = field(default_factory=dict)
integration_source: str = "unknown" integration_source: str = "unknown"
category_description: str = ""
def is_noop(self) -> bool: def is_noop(self) -> bool:
"""A stub leaf: authored (title + description) but no runnable body yet.""" """A stub leaf: authored (title + description) but no runnable body yet."""
@@ -349,6 +350,9 @@ def merge_skill_store(
for skill in entry.get("skills", []): for skill in entry.get("skills", []):
if skill.get("name") == name: if skill.get("name") == name:
description = skill.get("description", "") description = skill.get("description", "")
category_description = str(
entry.get("description") or CATEGORY_DESCRIPTIONS.get(category, "")
)
try: try:
module = load_skill_module(category, name, store.path) module = load_skill_module(category, name, store.path)
except Exception: except Exception:
@@ -371,6 +375,7 @@ def merge_skill_store(
contract=contract, contract=contract,
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
category_description=category_description,
) )
skills = tree.setdefault(category, []) skills = tree.setdefault(category, [])
for index, existing in enumerate(skills): for index, existing in enumerate(skills):
@@ -425,6 +430,7 @@ def merge_seed_store(
contract=contract, contract=contract,
integration=integration, integration=integration,
integration_source=integration_source, integration_source=integration_source,
category_description=CATEGORY_DESCRIPTIONS.get(category, ""),
) )
skills = tree.setdefault(category, []) skills = tree.setdefault(category, [])
for index, existing in enumerate(skills): for index, existing in enumerate(skills):
@@ -467,7 +473,7 @@ def unresolved_variables(
def compose_state(request: Request, additional_context: str | None = None) -> str: def compose_state(request: Request, additional_context: str | None = None) -> str:
parts = [request.text] parts = [request.text]
if current: if additional_context:
parts.append(f"({additional_context})") parts.append(f"({additional_context})")
return " ".join(parts) return " ".join(parts)
@@ -527,6 +533,27 @@ _CANNED_RESPONSES = [
_RESPONSE_MESSAGES = {f"response.{name}": message for name, _, message in _CANNED_RESPONSES} _RESPONSE_MESSAGES = {f"response.{name}": message for name, _, message in _CANNED_RESPONSES}
# Built-in category descriptions. A category level that offers only bare names
# carries no signal (real runs sent "book a flight to japan" to the `simplex`
# bucket 0.49 vs create_category 0.12); giving the model the category's scope
# flips that to create_category 0.87 vs simplex 0.02. Authored categories carry
# their own description from the registry; this is the seed for the built-ins and
# the fallback for a legacy entry with no description.
CATEGORY_DESCRIPTIONS: dict[str, str] = {
"response": (
"Anything that is not a request to perform an action: greetings, thanks, "
"chit-chat, off-topic statements, and inputs the agent cannot act on."
),
"calendar": (
"Calendar and scheduling: reading or changing the user's calendar "
"events and reminders."
),
"simplex": (
"SimpleX messaging: reading incoming messages, sending messages to "
"contacts, and showing the user's contact link."
),
}
def build_skills(config: dict) -> list[Skill]: def build_skills(config: dict) -> list[Skill]:
"""The hardcoded built-ins: internal behaviors only. """The hardcoded built-ins: internal behaviors only.
@@ -547,11 +574,32 @@ def build_skills(config: dict) -> list[Skill]:
category="response", category="response",
description=description, description=description,
act=_canned_response(f"response.{name}", message), act=_canned_response(f"response.{name}", message),
category_description=CATEGORY_DESCRIPTIONS["response"],
) )
for name, description, message in _CANNED_RESPONSES for name, description, message in _CANNED_RESPONSES
] ]
def category_descriptions(tree: dict[str, list[Skill]]) -> dict[str, str]:
"""The description to offer for each category, best-effort.
An authored skill carries the registry description on its `Skill`
(merge_registry/merge_skill_store); a seed or a legacy entry with no
description falls back to `CATEGORY_DESCRIPTIONS`. An empty category bucket
(no skills to carry it) falls back too, so a category is never offered bare.
"""
merged: dict[str, str] = {}
for category, skills in tree.items():
for skill in skills:
if skill.category_description:
merged[category] = skill.category_description
break
for category in tree:
if not merged.get(category):
merged[category] = CATEGORY_DESCRIPTIONS.get(category, "")
return merged
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]] = {}
@@ -570,6 +618,7 @@ def merge_registry(tree: dict[str, list[Skill]], categories: dict[str, dict]) ->
""" """
for category, data in categories.items(): for category, data in categories.items():
tree.setdefault(category, []) tree.setdefault(category, [])
description = str(data.get("description") or CATEGORY_DESCRIPTIONS.get(category, ""))
existing = {s.name for s in tree[category]} existing = {s.name for s in tree[category]}
for skill in data.get("skills", []): for skill in data.get("skills", []):
name = skill.get("name") name = skill.get("name")
@@ -580,36 +629,12 @@ def merge_registry(tree: dict[str, list[Skill]], categories: dict[str, dict]) ->
name=name, name=name,
category=category, category=category,
description=skill.get("description", ""), description=skill.get("description", ""),
category_description=description,
) )
) )
existing.add(name) existing.add(name)
def _clears_create_gate(
result,
create_id: str,
existing_ids: list[str],
tau: float,
margin: float,
) -> bool:
"""Should the create branch actually fire, or is it a weak plurality win?
The create option shares a softmax with the real categories/skills, so its
probability is diluted by every existing option — it is not a measure of
"confidence that nothing matches". Require both an absolute floor (`tau`)
and a clear lead over the best existing option (`margin`); a create that
only squeaks past on a crowded tree is suppressed and navigation falls back
to the best existing branch (the intent guard remains a second door to
authoring). Returns True when the gate is effectively disabled.
"""
probs = result.probs
if create_id not in probs:
return True
create_p = probs[create_id]
best = max((probs[i] for i in existing_ids if i in probs), default=0.0)
return create_p >= tau and (create_p - best) >= margin
def _navigate_canned( def _navigate_canned(
engine: SemIfEngine, engine: SemIfEngine,
log: DecisionLog, log: DecisionLog,
@@ -629,7 +654,10 @@ def _navigate_canned(
if len(ordered) == 1: if len(ordered) == 1:
return ordered[0] return ordered[0]
leaf = DecisionRequest( leaf = DecisionRequest(
state=compose_state(request, additional_context: f"all choices are within the {category} category"), state=compose_state(
request,
additional_context=f"all choices are within the {category} category",
),
question=( question=(
"Which canned response best fits this input? " "Which canned response best fits this input? "
f"Choose {ordered[-1].name} if none of the others does." f"Choose {ordered[-1].name} if none of the others does."
@@ -656,30 +684,39 @@ def navigate(
trace: TraceLog, trace: TraceLog,
request: Request, request: Request,
tree: dict[str, list[Skill]], tree: dict[str, list[Skill]],
create_tau: float = 0.5, category_tau: float = 0.75,
create_margin: float = 0.35,
) -> Skill | CreateCategory | CreateSkill: ) -> Skill | CreateCategory | CreateSkill:
"""Descend the tree one SemIf choice per level. Every choice is logged. """Descend the tree one SemIf choice per level. Every choice is logged.
The category level offers a "create_category" branch and the leaf level a The category level is **two-stage** (mirroring the leaf). The softmax offers
"create_skill" branch; both are handled live by dispatch and log a every existing category **with its description** plus a `create_category`
suggestion event to the trace. A level with nothing to choose from branch; the winner is then confirmed by `confirm_category_fit`, a name-anchored
(an empty tree, or a category with no skills yet) short-circuits straight to scope check. A confirmed winner is descended into; a winner that does not
the create branch: SemIf decisions need at least two options, and asking cover the request (or a `create_category` win) authors a new category. Bare
"which of one?" is meaningless. category names carry no signal — real runs sent "book a flight to japan" to
the `simplex` bucket (0.49 vs create_category 0.12) until the descriptions
were added — so the descriptions are load-bearing, and the confirm guard is
the create door (there is no threshold gate any more). A level with nothing
to choose from (an empty tree) short-circuits straight to create: SemIf
decisions need at least two options.
A create branch that wins the softmax but fails the confidence gate The leaf level is two-stage too: navigation only ever picks among the
(`create_tau` floor and `create_margin` lead over the best existing option) existing skills (`create_skill` is deliberately NOT in the softmax), and the
is suppressed: navigation falls back to the best existing option so a reuse-vs-create decision is the intent guard in dispatch
genuinely unmatched action still reaches authoring through the intent guard, (`confirm_skill_fit`), keyed by `navigation.intent_tau`.
while a crowded tree no longer drifts into create on a weak plurality.
""" """
categories = sorted(tree.keys()) categories = sorted(tree.keys())
create_category = Option("create_category", "Suggest a new category for this.") descriptions = category_descriptions(tree)
create_category = Option(
"create_category",
"No existing category covers this request; a new top-level category is "
"needed.",
)
top = DecisionRequest( top = DecisionRequest(
state=compose_state(request), state=compose_state(request),
question="Which top-level category handles this request?", question="Which top-level category handles this request?",
options=[Option(c, c) for c in categories] + [create_category], options=[Option(c, descriptions.get(c, c)) for c in categories]
+ [create_category],
) )
if not categories: if not categories:
trace.append( trace.append(
@@ -695,23 +732,17 @@ def navigate(
top_result = engine.call(top) top_result = engine.call(top)
log.append(top, top_result, extra={"phase": "navigate:category", "run_id": request.id}) log.append(top, top_result, extra={"phase": "navigate:category", "run_id": request.id})
category = top_result.selected category = top_result.selected
if category == "create_category" and not _clears_create_gate( if category != "create_category" and not confirm_category_fit(
top_result, "create_category", categories, create_tau, create_margin engine, log, trace, request, category, descriptions.get(category, ""),
category_tau,
): ):
fallback = max(
(c for c in categories if c in top_result.probs),
key=lambda c: top_result.probs[c],
)
trace.append( trace.append(
"create_suppressed", "category_scope_rejected",
request.id, request.id,
level="category", category=category,
fallback=fallback,
probs=top_result.probs, probs=top_result.probs,
tau=create_tau,
margin=create_margin,
) )
category = fallback category = "create_category"
if category == "create_category": if category == "create_category":
trace.append( trace.append(
"create_category", "create_category",
@@ -726,62 +757,102 @@ def navigate(
skills = tree[category] skills = tree[category]
if category in CANNED_CATEGORIES: if category in CANNED_CATEGORIES:
return _navigate_canned(engine, log, trace, request, category, skills) return _navigate_canned(engine, log, trace, request, category, skills)
create_skill = Option(
"create_skill",
"No existing skill performs this action; create a new skill for it.",
)
leaf = DecisionRequest(
state=compose_state(request),
question=f"Which {category} skill performs the action this request asks for? "
"Choose create_skill if none does.",
options=[Option(s.name, s.description) for s in skills] + [create_skill],
)
if not skills: if not skills:
trace.append( trace.append(
"skill_needed", "skill_needed",
request.id, request.id,
category=category, category=category,
state=leaf.state, state=compose_state(
question=leaf.question, request,
options=[o.id for o in leaf.options], additional_context=f"all choices are within the {category} category",
),
question="(this category has no skills yet)",
options=[],
selected="create_skill", selected="create_skill",
probs={}, probs={},
) )
return CreateSkill(category=category) return CreateSkill(category=category)
if len(skills) == 1:
# A one-option softmax is meaningless; hand the sole skill to the intent
# guard, which owns the reuse-vs-create decision.
return skills[0]
leaf = DecisionRequest(
state=compose_state(
request,
additional_context=f"all choices are within the {category} category",
),
question=f"Which {category} skill performs the action this request asks for?",
options=[Option(s.name, s.description) for s in skills],
)
leaf_result = engine.call(leaf) leaf_result = engine.call(leaf)
log.append(leaf, leaf_result, extra={"phase": "navigate:leaf", "run_id": request.id}) log.append(leaf, leaf_result, extra={"phase": "navigate:leaf", "run_id": request.id})
pick = leaf_result.selected pick = leaf_result.selected
if pick == "create_skill" and not _clears_create_gate( return next((s for s in skills if s.name == pick), skills[0])
leaf_result, "create_skill", [s.name for s in skills], create_tau, create_margin
):
fallback = max( def confirm_category_fit(
(s.name for s in skills if s.name in leaf_result.probs), engine: SemIfEngine,
key=lambda n: leaf_result.probs[n], log: DecisionLog,
trace: TraceLog,
request: Request,
category: str,
description: str,
tau: float = 0.75,
) -> bool:
"""Does this category's scope actually cover what the request asks for?
The category-level counterpart of `confirm_skill_fit`, and the create door
at that level: the described-category softmax proposes the best category,
and this name-anchored scope check confirms it. A rejected winner (or a
`create_category` win) authors a new category instead. The threshold is
`navigation.category_tau` (default 0.75 — measured so true non-tasks, which
score 0.87–0.999 on `response`, sit above it and a task misrouted into
`response` at 0.61 sits below).
Name-anchored on purpose: asking whether *the winner we picked* covers the
request is far cleaner than a global "does any category cover this?" — the
global wording collapsed in-scope and out-of-scope requests into one band
(0.47-0.98) and over-covered a non-task ("thank pepper ..."). This compares
one category's stated scope to the request. The check is deliberately
permissive: with real descriptions the in-scope cases score 0.9-1.0, so a
borderline over-cover routes into a plausible category and the leaf intent
guard catches it (a skill is only authored if no existing leaf matches).
"""
decision = DecisionRequest(
state=(
f"Request: {request.text}\n"
f"Category: {category}\n"
f"Scope: {description}"
),
question=f"Does the scope of the {category} category cover this request?",
options=[
Option("covers", "Yes, this category covers the request."),
Option(
"none",
"No, this category does not cover the request; a new category is needed.",
),
],
) )
trace.append( result = engine.call(decision)
"create_suppressed", log.append(
request.id, decision,
level="leaf", result,
category=category, extra={
fallback=fallback, "phase": "navigate:category_scope",
probs=leaf_result.probs, "run_id": request.id,
tau=create_tau, "category": category,
margin=create_margin, },
) )
pick = fallback fits = result.prob("covers") >= tau
if pick == "create_skill":
trace.append( trace.append(
"skill_needed", "category_scope",
request.id, request.id,
category=category, category=category,
state=leaf.state, selected=result.selected,
question=leaf.question, probs=result.probs,
options=[o.id for o in leaf.options], fits=fits,
selected=leaf_result.selected,
probs=leaf_result.probs,
) )
return CreateSkill(category=category) return fits
return next(s for s in skills if s.name == pick)
def confirm_skill_fit( def confirm_skill_fit(
@@ -794,16 +865,21 @@ def confirm_skill_fit(
) -> bool: ) -> bool:
"""Does this skill's action actually match what the request asks for? """Does this skill's action actually match what the request asks for?
Navigation picks the closest leaf; a seeded read skill can outscore the Navigation picks the closest existing leaf; this guard is now the **sole**
generic "create a new skill" branch on a request whose verb (send) no leaf-level reuse-vs-create decision (create_skill is no longer an option in
existing action performs. This one SemIf decision guards against silently the leaf softmax). If the skill's action is not the same action the request
running the wrong skill: a mismatch sends dispatch to author a new leaf asks for, dispatch authors a new leaf instead. The threshold is
instead. Wording tuned against the real model: comparing the two *actions* `navigation.intent_tau` (deliberately separate from the run-assessment
`tau`, so tuning reuse-vs-create does not move assessment/fidelity).
Wording tuned against the real model: comparing the two *actions*
("different action") is unambiguous where "can this serve the request" was ("different action") is unambiguous where "can this serve the request" was
not — e.g. "message Sam" (an implicit send in instant-messaging syntax) not — e.g. "message Sam" (an implicit send in instant-messaging syntax)
reads as a different action from "read the next message". Do not add an reads as a different action from "read the next message". Do not add an
instant-messaging context hint: it over-fires and pulls read phrasings to instant-messaging context hint: it over-fires and pulls read phrasings to
the send side. the send side. The comparison is over-permissive on near-synonyms (read vs
send score "same" ~0.74-0.78), so it is paired with the softmax that
disambiguates them — the guard only ever sees the softmax winner.
""" """
decision = DecisionRequest( decision = DecisionRequest(
state=( state=(
+40 -28
View File
@@ -27,7 +27,6 @@ from semif_agent.scheduler import SkillWrite
from semif_agent.skills import ( from semif_agent.skills import (
ActionResult, ActionResult,
CategoryDraft, CategoryDraft,
CreateSkill,
Skill, Skill,
SkillDraft, SkillDraft,
SkillStore, SkillStore,
@@ -93,6 +92,7 @@ def _install_tracking_fixture(scheduler):
category="tracking", category="tracking",
description="Check the delivery status of a package.", description="Check the delivery status of a package.",
act=act, act=act,
category_description="Package tracking: checking the delivery status of parcels and shipments.",
) )
] ]
@@ -120,7 +120,6 @@ def test_pipeline_end_to_end(tmp_path):
phases = [r.get("extra", {}).get("phase") for r in rows] phases = [r.get("extra", {}).get("phase") for r in rows]
assert "navigate:category" in phases, "navigation decisions must be logged" assert "navigate:category" in phases, "navigation decisions must be logged"
assert "navigate:leaf" in phases, "navigation decisions must be logged"
for row in rows: for row in rows:
assert row.get("extra", {}).get("run_id"), "every decision must carry a run_id" assert row.get("extra", {}).get("run_id"), "every decision must carry a run_id"
@@ -150,7 +149,18 @@ def test_navigation_routes_noise_into_the_response_tree(tmp_path):
"what is the next event in my nextcloud calendar?", "what is the next event in my nextcloud calendar?",
"tell me the next even in my calendar", "tell me the next even in my calendar",
] ]
noise = ["hello there", "thanks!", "the sky is blue", "what's up"] noise = [
"hello there",
"thanks!",
"the sky is blue",
"what's up",
# Stray statements not addressed to the agent: these have no action to
# perform, so they must fall to the `response` catchall, not author a
# category. Regression: an under-covering `response` description sent
# "the sky is blue"/"1+1=2"/"random thought here" to create_category.
"1+1=2",
"random thought here",
]
for text in lookups: for text in lookups:
result = navigate( result = navigate(
scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree scheduler.engine, scheduler.log, scheduler.trace, Request(text), scheduler.tree
@@ -166,23 +176,32 @@ def test_navigation_routes_noise_into_the_response_tree(tmp_path):
def test_navigate_routes_unmatched_action_to_create_skill(tmp_path): def test_navigate_routes_unmatched_action_to_create_skill(tmp_path):
"""A send request must navigate to create_skill, not silently to the read """Two-stage leaf: navigation picks the closest existing skill, then the
skill that merely shares the word 'message'. intent guard decides reuse-vs-create. A send request must reach create_skill
for simplex — not silently run the read skill that merely shares the word
'message'; a read request must reuse next_message.
Regression: every send phrasing picked simplex.next_message (P 0.46-0.73) Regression: the old single-stage leaf put create_skill in the softmax with
while the create_skill fallback scored only 0.007-0.09, because its option the real skills, so a send phrasing could win on a weak plurality while the
description named the mechanism ("suggest creating a new skill") instead of read skill stayed high. Now create_skill is never an option; the guard's
the trigger. This asserts the navigation outcome only — no codegen write. action comparison is the door. Asserts the routing outcome only — the draft
queue is stubbed and the read leaf's act is a stub, so no codegen write and
no network.
""" """
config = load_config() config = load_config()
require_real(config) require_real(config)
_isolate_runtime(config, tmp_path) _isolate_runtime(config, tmp_path)
scheduler, config = build_scheduler(config) scheduler, config = build_scheduler(config)
def read_act(ctx, request):
return ActionResult(action_log="read fixture", new_state="read")
scheduler.tree["simplex"] = [ scheduler.tree["simplex"] = [
Skill( Skill(
name="next_message", name="next_message",
category="simplex", category="simplex",
description="Read the next unread SimpleX message bridge.", description="Read the next unread SimpleX message bridge.",
act=read_act,
), ),
Skill( Skill(
name="connect_link", name="connect_link",
@@ -190,36 +209,29 @@ def test_navigate_routes_unmatched_action_to_create_skill(tmp_path):
description="Show (creating if needed) the SimpleX contact link others use to connect to this agent.", description="Show (creating if needed) the SimpleX contact link others use to connect to this agent.",
), ),
] ]
queued: list = []
scheduler._queue_draft = lambda request, category, kind, weight: queued.append(
(category, kind)
)
for text in [ for text in [
"send a simplex message to pepper saying hi", "send a simplex message to pepper saying hi",
"send a new simplex message to pepper: hey", "send a new simplex message to pepper: hey",
]: ]:
before = len(scheduler.log.read()) before = len(scheduler.log.read())
result = navigate( result = scheduler._dispatch(Request(text))
scheduler.engine,
scheduler.log,
scheduler.trace,
Request(text),
scheduler.tree,
)
leaf_rows = [ leaf_rows = [
r for r in scheduler.log.read()[before:] r for r in scheduler.log.read()[before:]
if r.get("extra", {}).get("phase") == "navigate:leaf" if r.get("extra", {}).get("phase") == "navigate:leaf"
] ]
print(f"[nav] {leaf_rows[-1]['predicted_probs'] if leaf_rows else '-'} :: {text!r} -> {result}") print(f"[nav] {leaf_rows[-1]['predicted_probs'] if leaf_rows else '-'} :: {text!r} -> {result.kind}")
assert isinstance(result, CreateSkill), f"send must route to create_skill, got {result!r}" assert result.kind == "create_skill", f"send must route to create_skill, got {result!r}"
assert result.category == "simplex" assert queued and all(category == "simplex" for category, _ in queued)
read = navigate( read = scheduler._dispatch(Request("read the next simplex message"))
scheduler.engine, print(f"[nav control] read -> {read.kind} {read.skill}")
scheduler.log, assert read.kind == "ran", "a read request must still run the read skill"
scheduler.trace, assert read.skill == "next_message"
Request("read the next simplex message"),
scheduler.tree,
)
print(f"[nav control] read -> {read}")
assert getattr(read, "name", None) == "next_message", "a read request must still route to the read skill"
def test_busy_choice_path(tmp_path): def test_busy_choice_path(tmp_path):
+201 -82
View File
@@ -42,7 +42,10 @@ from semif_agent.skills import (
build_skill_prompt, build_skill_prompt,
build_skills, build_skills,
build_tree, build_tree,
confirm_category_fit,
confirm_skill_fit, confirm_skill_fit,
category_descriptions,
CATEGORY_DESCRIPTIONS,
generate_category, generate_category,
generate_skill, generate_skill,
merge_registry, merge_registry,
@@ -392,6 +395,28 @@ def test_merge_registry_loads_categories_and_skills(tmp_path):
assert tree["delivery"][0].category == "delivery" assert tree["delivery"][0].category == "delivery"
def test_category_descriptions_never_bare_and_seeded(tmp_path):
"""Every category must carry a usable description at the softmax — a bare
name carries no signal. Built-ins come from CATEGORY_DESCRIPTIONS; an
authored category carries its registry description; a legacy/empty entry
falls back to the built-in or empty string without crashing."""
tree = build_tree(build_skills({"skills": {}}))
assert tree["response"][0].category_description # built-in seed
registry = CategoryRegistry(str(tmp_path / "categories.json"))
registry.register("travel", "Booking flights, hotels, and trips.")
registry.register_skill("travel", "book_flight", "Book a flight.")
merge_registry(tree, registry.read())
assert tree["travel"][0].category_description == "Booking flights, hotels, and trips."
descriptions = category_descriptions(tree)
assert descriptions["response"] == CATEGORY_DESCRIPTIONS["response"]
assert descriptions["travel"] == "Booking flights, hotels, and trips."
# an empty bucket (no skill to carry the description) still resolves to text
tree["orphan"] = []
assert category_descriptions(tree)["orphan"] == ""
def _write_seed(seed_store, category, name, description=""): def _write_seed(seed_store, category, name, description=""):
directory = seed_store.dir(category, name) directory = seed_store.dir(category, name)
directory.mkdir(parents=True, exist_ok=True) directory.mkdir(parents=True, exist_ok=True)
@@ -581,11 +606,10 @@ def test_canned_response_runs_without_assessment(tmp_path):
def test_navigate_leaf_offers_create_for_unmatched_action(tmp_path): def test_navigate_leaf_picks_among_existing_skills_only(tmp_path):
"""The create_skill fallback must describe the *trigger* (no skill performs """Two-stage leaf: create_skill is NOT an option in the leaf softmax. The
the action), not the mechanism ('suggest creating a new skill'): the leaf decision offers only the existing skills, and navigation returns the
decision model only sees option descriptions, and the generic wording lost best-matching one; the intent guard in dispatch owns reuse-vs-create."""
0.03-0.06 to a read skill on send requests."""
class Recording: class Recording:
def __init__(self): def __init__(self):
@@ -601,16 +625,22 @@ def test_navigate_leaf_offers_create_for_unmatched_action(tmp_path):
engine = Recording() engine = Recording()
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
tree = {"simplex": [Skill(name="next_message", category="simplex", description="Read the next SimpleX message.")]} tree = {
navigate(engine, log, trace, Request("send a simplex message"), tree) "simplex": [
create = next(o for o in engine.request.options if o.id == "create_skill") Skill(name="next_message", category="simplex", description="Read the next SimpleX message."),
assert "No existing skill performs this action" in create.description Skill(name="connect_link", category="simplex", description="Show the contact link."),
assert "action" in engine.request.question ]
}
result = navigate(engine, log, trace, Request("send a simplex message"), tree)
ids = [o.id for o in engine.request.options]
assert ids == ["next_message", "connect_link"]
assert "create_skill" not in ids
assert getattr(result, "name", None) in ids
class _ProbEngine: class _ProbEngine:
"""Returns caller-specified probabilities, keyed by a substring of the """Returns caller-specified probabilities, keyed by a substring of the
decision question, so a test can force a weak create plurality.""" decision question, so a test can force a specific navigation outcome."""
def __init__(self, by_question: dict[str, dict[str, float]]): def __init__(self, by_question: dict[str, dict[str, float]]):
self.by_question = by_question self.by_question = by_question
@@ -626,6 +656,9 @@ class _ProbEngine:
if key in request.question: if key in request.question:
probs_map = value probs_map = value
break break
if not probs_map:
probs_map = {ids[0]: 1.0}
probs_map = {k: v for k, v in probs_map.items() if k in ids}
if not probs_map: if not probs_map:
probs_map = {ids[0]: 1.0} probs_map = {ids[0]: 1.0}
return DecisionResult( return DecisionResult(
@@ -642,111 +675,197 @@ def _leaf_tree():
name="next_message", name="next_message",
category="simplex", category="simplex",
description="Read the next SimpleX message.", description="Read the next SimpleX message.",
) ),
Skill(
name="connect_link",
category="simplex",
description="Show the contact link.",
),
] ]
} }
def test_navigate_suppresses_weak_create_plurality(tmp_path): def test_navigate_leaf_returns_best_existing_skill(tmp_path):
"""create_skill wins the softmax by a hair but fails the margin gate: the """The leaf softmax picks the highest-probability existing skill; no create
weak plurality must fall back to the best existing skill, not author.""" branch competes with it (that was the dilution bug)."""
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 1.0}, "top-level category": {"simplex": 1.0},
"skill performs": {"next_message": 0.45, "create_skill": 0.5}, "Does the scope": {"covers": 1.0},
"skill performs": {"next_message": 0.45, "connect_link": 0.55},
} }
) )
result = navigate( result = navigate(
engine, log, trace, Request("send a simplex message"), _leaf_tree() engine, log, trace, Request("send a simplex message"), _leaf_tree()
) )
assert getattr(result, "name", None) == "connect_link"
assert not isinstance(result, CreateSkill)
def test_navigate_single_skill_category_skips_the_softmax(tmp_path):
"""A one-option softmax is meaningless; the sole skill is returned directly
and the guard decides reuse-vs-create."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = _ProbEngine(
{"top-level category": {"simplex": 1.0}, "Does the scope": {"covers": 1.0}}
)
tree = {
"simplex": [
Skill(name="next_message", category="simplex", description="Read the next SimpleX message.")
]
}
result = navigate(engine, log, trace, Request("read the next message"), tree)
assert getattr(result, "name", None) == "next_message" assert getattr(result, "name", None) == "next_message"
suppressed = [e for e in trace.read() if e["kind"] == "create_suppressed"] # only the category decision was made; the leaf softmax was skipped
assert len(suppressed) == 1 assert all("Which simplex skill" not in c.question for c in engine.calls)
assert suppressed[0]["level"] == "leaf"
assert suppressed[0]["fallback"] == "next_message"
def test_navigate_create_clears_margin_and_tau(tmp_path): def test_navigate_empty_category_short_circuits_to_create(tmp_path):
"""A create that leads the best skill by >= margin and clears tau fires."""
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = _ProbEngine( engine = _ProbEngine({"top-level category": {"simplex": 1.0}})
{ result = navigate(engine, log, trace, Request("anything"), {"simplex": []})
"top-level category": {"simplex": 1.0},
"skill performs": {"next_message": 0.2, "create_skill": 0.7},
}
)
result = navigate(
engine, log, trace, Request("send a simplex message"), _leaf_tree()
)
assert isinstance(result, CreateSkill) assert isinstance(result, CreateSkill)
assert result.category == "simplex" assert result.category == "simplex"
assert not [e for e in trace.read() if e["kind"] == "create_suppressed"] assert any(e["kind"] == "skill_needed" for e in trace.read())
def test_navigate_create_below_tau_is_suppressed(tmp_path): def test_navigate_category_options_carry_descriptions(tmp_path):
"""Even with a clear lead, a create below the absolute floor is suppressed """The category softmax must offer each category WITH its description — bare
(all options weak => nothing is a confident match).""" names carry no signal (the misroute bug)."""
engine = _ProbEngine({"top-level category": {"simplex": 1.0}})
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
tree = {
"simplex": [
Skill(
name="next_message",
category="simplex",
description="Read the next SimpleX message.",
category_description="SimpleX messaging: read/send messages.",
)
]
}
navigate(engine, log, trace, Request("read the next message"), tree)
cat_decision = next(c for c in engine.calls if "top-level category" in c.question)
by_id = {o.id: o.description for o in cat_decision.options}
assert by_id["simplex"] == "SimpleX messaging: read/send messages."
assert "new top-level category is needed" in by_id["create_category"]
def test_navigate_category_rejected_scope_authors_category(tmp_path):
"""The confirm guard is the category create door: a softmax winner whose
scope the guard rejects authors a new category."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
tree = _leaf_tree()
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 1.0}, "top-level category": {"simplex": 1.0},
"skill performs": {"next_message": 0.1, "create_skill": 0.3}, "Does the scope": {"none": 1.0},
}
)
result = navigate(
engine, log, trace, Request("send a simplex message"), _leaf_tree()
)
assert getattr(result, "name", None) == "next_message"
assert any(e["kind"] == "create_suppressed" for e in trace.read())
def test_navigate_category_create_gate_suppresses_and_falls_back(tmp_path):
"""The same gate applies to create_category: a weak plurality win falls back
to the best existing category and descends into it."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
tree = _leaf_tree()
tree["calendar"] = [
Skill(name="next_event", category="calendar", description="Report the next event.")
]
engine = _ProbEngine(
{
"top-level category": {
"calendar": 0.30,
"simplex": 0.32,
"create_category": 0.38,
},
"skill performs": {"next_message": 1.0},
}
)
result = navigate(engine, log, trace, Request("send a simplex message"), tree)
assert getattr(result, "name", None) == "next_message"
suppressed = [e for e in trace.read() if e["kind"] == "create_suppressed"]
assert len(suppressed) == 1 and suppressed[0]["level"] == "category"
assert suppressed[0]["fallback"] == "simplex"
def test_navigate_category_create_clears_gate(tmp_path):
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
tree = _leaf_tree()
engine = _ProbEngine(
{
"top-level category": {
"simplex": 0.1,
"create_category": 0.8,
},
} }
) )
result = navigate(engine, log, trace, Request("book a flight"), tree) result = navigate(engine, log, trace, Request("book a flight"), tree)
assert isinstance(result, CreateCategory) assert isinstance(result, CreateCategory)
assert not [e for e in trace.read() if e["kind"] == "create_suppressed"] assert any(e["kind"] == "category_scope_rejected" for e in trace.read())
assert any(e["kind"] == "create_category" for e in trace.read())
def test_navigate_category_confirmed_scope_descends(tmp_path):
"""A softmax winner the guard confirms is descended into (no create)."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = _ProbEngine(
{
"top-level category": {"simplex": 1.0},
"Does the scope": {"covers": 1.0},
"skill performs": {"next_message": 1.0, "connect_link": 0.0},
}
)
result = navigate(engine, log, trace, Request("read a message"), _leaf_tree())
assert getattr(result, "name", None) == "next_message"
assert not isinstance(result, CreateCategory)
assert any(e["kind"] == "category_scope" and e["fits"] for e in trace.read())
def test_confirm_category_fit_threshold(tmp_path):
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = ScriptedEngine(choices={"Does the scope": "covers"})
assert (
confirm_category_fit(
engine, log, trace, Request("check my calendar"), "calendar", "Calendars.", tau=0.5
)
is True
)
assert log.read()[-1]["extra"]["phase"] == "navigate:category_scope"
engine = ScriptedEngine(choices={"Does the scope": "none"})
assert (
confirm_category_fit(
engine, log, trace, Request("order pizza"), "calendar", "Calendars.", tau=0.5
)
is False
)
def test_dispatch_intent_tau_controls_reuse_vs_create(tmp_path):
"""The leaf reuse-vs-create knob is navigation.intent_tau, separate from the
top-level tau: a borderline guard verdict flips on it while assessment is
untouched."""
def build(intent_tau: float):
engine = _ProbEngine(
{
"top-level category": {"simplex": 1.0},
"Does the scope": {"covers": 1.0},
"skill performs": {"next_message": 1.0, "connect_link": 0.0},
"same action": {"same": 0.8, "different": 0.2},
}
)
scheduler = Scheduler(
engine=engine,
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={
"skills": {},
"navigation": {"intent_tau": intent_tau},
"category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(tmp_path / "seeds"),
},
trace=TraceLog(str(tmp_path / "runs.jsonl")),
)
def act(ctx, request):
return ActionResult(action_log="read fixture", new_state="read")
scheduler.tree = {
"simplex": [
Skill(name="next_message", category="simplex", description="Read the next SimpleX message.", act=act),
Skill(name="connect_link", category="simplex", description="Show the contact link."),
]
}
queued: list = []
scheduler._queue_draft = lambda request, category, kind, weight: queued.append(
(category, kind)
)
return scheduler, queued
low, queued_low = build(0.5)
assert low.intent_tau == 0.5
ran = low._dispatch(Request("read the next simplex message"))
assert ran.kind == "ran", "guard same=0.8 clears intent_tau=0.5: reuse"
assert not queued_low
high, queued_high = build(0.95)
created = high._dispatch(Request("read the next simplex message"))
assert created.kind == "create_skill", "guard same=0.8 fails intent_tau=0.95: author"
assert queued_high == [("simplex", "skill")]
def test_confirm_skill_fit_returns_true_when_action_matches(tmp_path): def test_confirm_skill_fit_returns_true_when_action_matches(tmp_path):
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))