chain multi-step requests across known skills

Add the run-ledger chained-run path and make a compound request run its
known skills in order instead of authoring one monolithic skill.

- scheduler/skill: `assess:outcome` gains a `continue` verdict; a continued
  step is re-dispatched with a bounded run ledger (max_reentries + a
  monotonic-progress guard), and the ledger is rendered into the routing and
  assessment state.
- navigation leaf guard (`confirm_skill_fit`) becomes same/part/different and
  is ledger-aware, so the first step of a compound request runs instead of
  being rejected into `create_skill` (a real run picked calculator.calculate
  at 0.99 and was rejected into create_skill).
- results flow forward through `request.run_ledger` (`last_result` helper);
  `simplex.send_message` sends the prior step's result rather than asking the
  LLM bridge to recompute it. Documented in CODEGEN.md.
- `assess:outcome` stays the sole continuation authority: the guard only
  decides whether a skill contributes, never forces a continuation (a forced
  continue on `part` overrode a correct `done` on the final step and authored
  a spurious category).
- verbosity levels, structured SchedulerReply fields, and a send_message
  hermetic test for the chained-result path.
This commit is contained in:
gabby committed 2026-10-10 07:25:17 +00:00
1 parent 9ba14fdab0
commit ab0defca1e
20 files changed
+1030 -308

No files matched your search

+40 -16
View File
@@ -87,8 +87,10 @@ scheduler.py no up-front gate: every input is dispatched
cascade; elicitation asks implementation questions one at a cascade; elicitation asks implementation questions one at a
time (all front ends defer via the question queue, `answer_timeout` time (all front ends defer via the question queue, `answer_timeout`
per question); a per question); a
failed real run triggers a logged SemIf repair choice `failed` step 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,
while a `continue` step is re-dispatched into next-step routing
with a bounded run ledger (the chained multi-step path);
housekeeping meta skills (delete/clear-config/regen/cancel-build) housekeeping meta skills (delete/clear-config/regen/cancel-build)
operate on the tree via `ctx.admin`; new-skill creation is gated by operate on the tree via `ctx.admin`; new-skill creation is gated by
a tri-state mode (`new_skill_creation`: allow/deny/ask) with a a tri-state mode (`new_skill_creation`: allow/deny/ask) with a
@@ -100,9 +102,14 @@ scheduler.py no up-front gate: every input is dispatched
queue.py bounded FIFO request queue (arrival order, max depth) queue.py bounded FIFO request queue (arrival order, max depth)
skills.py tree + registry (hardcoded built-ins: the closed `response` canned skills.py tree + registry (hardcoded built-ins: the closed `response` canned
tree plus the `housekeeping` meta skills), navigation = SemIf tree plus the `housekeeping` meta skills), navigation = SemIf
choices per level (logged; choices per level (logged; the question is "which category/skill
the actionability guard runs first, at the top of navigation, is the logical next step toward satisfying this request?" for the
to arbitrate the response/create boundary), create_category first step AND each continuation, and the run ledger is rendered
into the state, so a chained step sees what was already done;
the actionability guard runs first, at the top of navigation, to
arbitrate the response/create boundary — but ONLY on the first
step, since a continuation is actionable by construction),
create_category
and create_skill author + register stubs via the small `llm` and create_skill author + register stubs via the small `llm`
provider (separate from codegen); SkillStore persists one folder per skill provider (separate from codegen); SkillStore persists one folder per skill
(skill.py, skill.test.py, contract.json, config.json) and (skill.py, skill.test.py, contract.json, config.json) and
@@ -128,16 +135,22 @@ skill.py loop: observe -> act -> observe -> assess; the body is a single
act(ctx, request) phase that returns ActionResult (its own act(ctx, request) phase that returns ActionResult (its own
SemIf sub-decisions ride on ActionResult.decisions and are SemIf sub-decisions ride on ActionResult.decisions and are
logged with the run outcome, phase `act`); logged with the run outcome, phase `act`);
assess is a SemIf decision (`assess:outcome` success/failure at assess is a SemIf decision (`assess:outcome`: is there any
tau; on failure `assess:requeue` complete/retry) and the run additional work to satisfy the request? -> done / continue /
summary is deterministic (no generation), built from failed, at threshold precedence failed > done > continue) and the
run summary is deterministic (no generation), built from
category.skill + ok/failed + action_log — the body writes only the category.skill + ok/failed + action_log — the body writes only the
result, the runner adds the `category.name:` ref; the assess state carries result, the runner adds the `category.name:` ref; the assess state
the skill's declared action, the goal, and the resolved inputs carries the skill's declared action, the goal, the resolved inputs
(secrets redacted), and the requeue state flags a retry that would (secrets redacted), the bounded action log, and the steps already
reproduce the identical observed result as a no-op; a `DETERMINISTIC_CATEGORIES` taken (the run ledger); `continue` re-dispatches the request into
next-step routing with a bounded run-ledger entry (capped by
`max_reentries` + the monotonic-progress guard), `failed` offers a
repair; a `DETERMINISTIC_CATEGORIES`
run (housekeeping) skips assessment/repair — it is an internal run (housekeeping) skips assessment/repair — it is an internal
mechanical action with a known result, not an external run; mechanical action with a known result, not an external run;
every skill's output is truncated to the one shared speakable
budget (`chain.result_chars`);
a run paused for input is resumed by re-invoking act with the a run paused for input is resumed by re-invoking act with the
answer on request.user_input; a answer on request.user_input; a
contract variable the runner cannot satisfy pauses BEFORE contract variable the runner cannot satisfy pauses BEFORE
@@ -394,7 +407,17 @@ CLI, unit tests (24) + integration tests (2).
drift into create on a weak plurality (real runs scored `create_skill` 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 0.585–0.803 on requests a seed skill clearly matched). The reuse-vs-create
decision is the **intent guard** (`confirm_skill_fit`, phase decision is the **intent guard** (`confirm_skill_fit`, phase
`navigate:intent`) at `navigation.intent_tau`. The **actionability guard** `navigate:intent`) at `navigation.intent_tau`: it decides what the softmax
winner does for the request — `same` (performs the next action the request
needs), `part` (the request needs more than one action and this skill performs
one required part), or `different` (author a new leaf). The run ledger is part
of the guard's state so a later step judges against the *remaining* work, not
the whole request; the guard only decides whether the skill contributes —
whether more work remains is `assess:outcome`'s call, so a compound request is
broken into known skills while the final step still stops cleanly (a forced
continue on `part` was tried and rejected: the guard labeled the final send
step `part` 0.85 while assessment correctly said `done` 0.99, and the forced
continue authored a spurious category). The **actionability guard**
(`confirm_non_action`, phase `navigate:actionability`) at (`confirm_non_action`, phase `navigate:actionability`) at
`navigation.action_tau` (default 0.5) runs at the **top** of navigation, `navigation.action_tau` (default 0.5) runs at the **top** of navigation,
before category selection: it decides whether the input is an actionable before category selection: it decides whether the input is an actionable
@@ -989,9 +1012,10 @@ CLI, unit tests (24) + integration tests (2).
asks the next missing variable). An act-driven `needs_input` also accepts an asks the next missing variable). An act-driven `needs_input` also accepts an
empty answer — it is forwarded to `act` as `user_input=""`; a body that then empty answer — it is forwarded to `act` as `user_input=""`; a body that then
fails for lack of the info is assessed/repair-offered normally. fails for lack of the info is assessed/repair-offered normally.
- **Resolved-input observation.** The `assess:outcome` / `assess:requeue` state - **Resolved-input observation.** The `assess:outcome` state includes the
includes the resolved contract values (`resolved inputs:` block) so the resolved contract values (`resolved inputs:` block), the bounded action log, and
decision sees the full query → resolution → action path; secret-named the run ledger (steps already taken) so the decision sees the full query →
resolution → action → chain path; secret-named
variables (pass/token/secret/key/credential/auth) are redacted to `***` so variables (pass/token/secret/key/credential/auth) are redacted to `***` so
credentials never reach the decision log. credentials never reach the decision log.
- **Requirements elicitation (implementation questions, default on).** - **Requirements elicitation (implementation questions, default on).**
+38 -7
View File
@@ -137,9 +137,10 @@ engine/runtime concerns, not body-level tools: a body makes direct typed
decisions and lets the runner own the model. decisions and lets the runner own the model.
Note that the runner's own **assessment** of whether a run succeeded Note that the runner's own **assessment** of whether a run succeeded
(`assess:outcome`) is itself a SemIf decision over the body's `action_log`, the (`assess:outcome`: is there any additional work to be done to satisfy the
goal, and the resolved inputs. The body does not self-assess; it reports request? → done / continue / failed) is itself a SemIf decision over the body's
truthfully and lets SemIf judge. `action_log`, the goal, the resolved inputs, and the steps already taken. The
body does not self-assess; it reports truthfully and lets SemIf judge.
### Choosing between deterministic code, SemIf, and LLM text ### Choosing between deterministic code, SemIf, and LLM text
@@ -451,14 +452,44 @@ Rules:
the result is a broken output. the result is a broken output.
- **Never an empty or placeholder output.** If there is genuinely nothing (empty - **Never an empty or placeholder output.** If there is genuinely nothing (empty
inbox, no matching event), say so explicitly — that is a real result, and a inbox, no matching event), say so explicitly — that is a real result, and a
**successful** run: the `assess:outcome` step treats a definitive "nothing **`done`** run: the `assess:outcome` step treats a definitive "nothing found /
found / nothing to do" result as success. Phrase it as the answer the user nothing to do" result as done. Phrase it as the answer the user asked for
asked for ("checked the inbox: no unread messages"), not as an absence or an ("checked the inbox: no unread messages"), not as an absence or an error, so
error, so the assessment does not read a healthy empty result as a failure. the assessment does not read a healthy empty result as a failure.
- **Keep the result speakable — it is bounded.** A skill's output is read in a
chat message or heard as speech, so the runner truncates `action_log` /
`new_state` to one shared budget (`chain.result_chars`, ~300 characters /
~20 seconds of speech) and feeds the bounded text to the assessment and the
run ledger. A result longer than that is a bad result. When a skill's real
product is long or structured (a file listing, a document body, a full
thread), write it to the service or a file as a **side effect** and return a
short summary plus a pointer (path / id) — never dump the payload into the
result string.
- **Never claim success you did not observe.** If the action failed, put the - **Never claim success you did not observe.** If the action failed, put the
real failure in `action_log` and set `new_state` back to `request.text` (see real failure in `action_log` and set `new_state` back to `request.text` (see
the hard requirements). the hard requirements).
### Multi-step chains
A request can take more than one action ("calculate 2*10 and send the result to
Pepper"). The runner does not ask one body to satisfy the whole request: it runs
the **next** skill, judges the outcome, and if more work remains re-dispatches
the request with a **run ledger** of the steps already taken. A body may
therefore run as a later step of a chain.
- `request.run_ledger` is a list of `{"query", "skill", "outcome"}` entries, one
per step already taken (empty on a first step). The most recent entry's
`outcome` is the previous step's result — the same bounded text the runner
shows the user.
- **If the request depends on the previous step's result, read it — never
recompute or fabricate it.** `from semif_agent.skills import last_result`
returns `run_ledger[-1]["outcome"]` (or `""`). Do not ask the LLM bridge to
redo a calculation or re-fetch a value an earlier step produced; that would
silently invent a working value. Prefer a literal value the user stated, then
the prior step's result, and only then generate novel text.
- A body still returns only its own step's `action_log` / `new_state`; the
runner owns the ledger and decides whether the chain continues.
### Rules (hard requirements) ### Rules (hard requirements)
- **Perform the real action.** If the skill's purpose involves an external - **Perform the real action.** If the skill's purpose involves an external
+20 -11
View File
@@ -127,11 +127,15 @@ choice is logged** (`navigate:category`, `navigate:leaf`, `navigate:response`).
- **Leaf.** The leaf softmax picks only among the existing skills (a create - **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 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** weak plurality). The picked skill then goes through the **intent guard**
(`confirm_skill_fit`, phase `navigate:intent`): an action comparison at (`confirm_skill_fit`, phase `navigate:intent`): at `navigation.intent_tau` it
`navigation.intent_tau` asking whether the skill performs the same action the decides what the skill does for the request, given the steps already taken
request asks for. Same → run it; different → author a new leaf in that (the run ledger is part of its state). `same` (it performs the next action the
category. An empty (or single-skill) category skips the softmax and goes request needs) or `part` (the request needs more than one action and this
straight to the guard. skill performs one required part) → run it; `different` (it does no action the
request asks for) → author a new leaf in that category. The guard only decides
whether the skill contributes; whether more work remains is `assess:outcome`'s
call. 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 - 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 cases score 0.9–1.0, so a borderline over-cover routes into a plausible
category and the leaf guard catches it. category and the leaf guard catches it.
@@ -151,12 +155,18 @@ observe baseline → act → observe outcome → assess
a live candidate set) are returned on `ActionResult.decisions` and logged as a live candidate set) are returned on `ActionResult.decisions` and logged as
training rows with the run outcome. training rows with the run outcome.
- `assess` is a **SemIf decision**, not generation: - `assess` is a **SemIf decision**, not generation:
- `assess:outcome` — success/failure at `tau`; its state includes the resolved - `assess:outcome` — is there any *additional work* to satisfy the request?
inputs (secrets redacted) so a wrong resolution is visible. Three outcomes at threshold precedence `failed > done > continue`: `done`
- `assess:requeue` — on failure, `complete` vs `retry` (bounded by (request satisfied), `continue` (this step worked but more work is needed →
`max_reentries`). the scheduler routes the logical next step with a bounded run ledger),
`failed` (the step errored → the repair path). Its state includes the skill
action, the goal, the resolved inputs (secrets redacted), the bounded action
log, and the steps already taken.
- The run summary is **deterministic** (same inputs ⇒ same string): - The run summary is **deterministic** (same inputs ⇒ same string):
`f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`. `f"{category}.{name}: {'ok'|'failed'} — {action_log or new_state}"`.
- Every skill's output is bounded to one **speakable budget** (`chain.result_chars`,
~300 chars): the result string and its run-ledger entry. A long product belongs
in a file I/O side effect, not the result (see `CODEGEN.md`).
- A skill can pause for human input two ways: `act` returns `needs_input` (act - A skill can pause for human input two ways: `act` returns `needs_input` (act
re-runs on resume, with `request.user_input` set), or — for a contract re-runs on resume, with `request.user_input` set), or — for a contract
variable the runner cannot satisfy — a **pre-act** pause collects config variable the runner cannot satisfy — a **pre-act** pause collects config
@@ -232,8 +242,7 @@ the request, the tree, the elicitation answers, the runtime **bridge catalog**
| `navigate:leaf` | `skills.py:736` | request text + current category | every skill name + description (+ `create_skill`) | | `navigate:leaf` | `skills.py:736` | request text + current category | every skill name + description (+ `create_skill`) |
| `navigate:response` | `skills.py:634` | request text + category | canned reply names + descriptions (catchall last) | | `navigate:response` | `skills.py:634` | request text + category | canned reply names + descriptions (catchall last) |
| `navigate:intent` | `skills.py:811` | `Requested action: <text>` + `Action of the existing skill: <description>` | `same` / `different` | | `navigate:intent` | `skills.py:811` | `Requested action: <text>` + `Action of the existing skill: <description>` | `same` / `different` |
| `assess:outcome` | `skill.py:257` | skill label + goal + action log | `success` / `failure` | | `assess:outcome` | `skill.py:311` | skill label + goal + resolved inputs + bounded action log + steps already taken | `done` / `continue` / `failed` |
| `assess:requeue` | `skill.py:279` | skill label + goal + action log + `outcome: failed` | `complete` / `retry` |
| `config:search` | `scheduler.py:1477` | skill + variable name + its semantic description | each candidate config key (+ `ask`) | | `config:search` | `scheduler.py:1477` | skill + variable name + its semantic description | each candidate config key (+ `ask`) |
| `config:record` | `skill.py:112` | skill + `variable = value` | `record` / `ask_again` | | `config:record` | `skill.py:112` | skill + `variable = value` | `record` / `ask_again` |
| `authoring:fidelity` | `scheduler.py:1311` | skill, request, description, `INTEGRATION` JSON, static findings, first 4000 chars of body | `accept` / `reconsider` | | `authoring:fidelity` | `scheduler.py:1311` | skill, request, description, `INTEGRATION` JSON, static findings, first 4000 chars of body | `accept` / `reconsider` |
+6
View File
@@ -26,6 +26,12 @@ integration, and the agent offers to fix the skill when that real run fails. A
test must never be "fixed" by simulating the action or by weakening an test must never be "fixed" by simulating the action or by weakening an
assertion, and a simulated body is broken even if every test passes. assertion, and a simulated body is broken even if every test passes.
A skill's result is **bounded** to one speakable budget (it is read in a chat
message or spoken aloud; `chain.result_chars`, ~300 characters). Do not assert a
long/detailed payload: a skill whose real product is long or structured writes it
to the service or a file as a side effect and returns a short summary plus a
pointer. Order by the skill's own contract, not the fixture's size.
## contract.json ## contract.json
A **single JSON object**. Each key is the name of a variable the skill needs; A **single JSON object**. Each key is the name of a variable the skill needs;
+12 -1
View File
@@ -4,9 +4,20 @@
"max_reentries": 3, "max_reentries": 3,
"new_skill_creation": "allow", "new_skill_creation": "allow",
"_new_skill_creation_comment": "Global new-skill creation mode: \"allow\" (create without asking), \"deny\" (never author new skills/categories), or \"ask\" (author only after the human approves the proposal). A category can override this in data/skills/<category>/config.json with its own \"new_skill_creation\" value; the built-in housekeeping and response categories are always denied in code.", "_new_skill_creation_comment": "Global new-skill creation mode: \"allow\" (create without asking), \"deny\" (never author new skills/categories), or \"ask\" (author only after the human approves the proposal). A category can override this in data/skills/<category>/config.json with its own \"new_skill_creation\" value; the built-in housekeeping and response categories are always denied in code.",
"verbosity": "result",
"_verbosity_comment": "How much of a completed request to surface. \"result\" (default): only the final answer — an end user does not care which skills ran or which decisions were made. \"query\": also show each intermediate step of a chained request (its query + run-ledger entry). \"decision\": also show every SemIf decision (phase + selected option + probabilities) for a step — a debugging view.",
"chain": {
"_comment": "Chained multi-step completion. When a run's outcome assessment says more work is needed, the request is re-dispatched with a compact run ledger and routed to the logical next skill, until the request is satisfied, fails into repair, or the chain is capped by max_reentries. result_chars is the ONE shared speakable budget applied to every skill's output (its result string and its ledger entry): a result is read in a chat message or heard as speech, so it is truncated to this many characters at a word boundary. A long product of a skill belongs in a file I/O side effect, not the result string (see CODEGEN.md/TESTGEN.md). The voice front end (gateway.voice.max_speak_chars) and the humanizer (gateway.humanize.max_chars) are downstream caps and should not exceed it.",
"result_chars": 300
},
"assess": {
"_comment": "Thresholds for the three-way assess:outcome decision (is there additional work to be done to satisfy the request?): done (request satisfied), continue (the step worked but more work is needed; route the next step), failed (the step errored; offer repair). Verdict precedence is failed > done > continue, so a confident success/failure is honored and continue — the over-trigger — only wins when the model is genuinely unsure. Separate from the top-level tau so completion tuning does not move assessment/fidelity.",
"done_tau": 0.5,
"fail_tau": 0.5
},
"timezone": "", "timezone": "",
"navigation": { "navigation": {
"_comment": "Navigation is two-stage at BOTH levels and the guards are the create doors (no threshold gate). Category: the softmax offers each existing category WITH its description (bare names carried no signal) plus create_category; confirm_category_fit then confirms the winner's scope (phase navigate:category_scope, P(covers) >= category_tau) and a rejected winner authors a new category. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. 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. All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category 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. A **category** softmax winner at or above `softmax_bypass_tau` (default 0.5) skips the scope confirm (traced `category_scope_bypassed`) — `create_category` is one of its options, so a confident winner really did beat authoring a category. The **leaf** intent guard is never bypassed: the leaf softmax offers only existing skills, so a confident winner is \"best of the wrong lot\", not a match, and the guard is the only leaf-level create door.", "_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. The `response` catchall and create_category share a boundary arbitrated by the actionability guard confirm_non_action (phase navigate:actionability, P(non_action) >= action_tau): the closed response tree is reached ONLY when the input is not a request, so a request no skill covers (e.g. \"what is 255 * 12?\") authors instead of getting a canned reply. Leaf: the softmax offers only existing skills; confirm_skill_fit then decides what the winner does for the request — same (it performs the next action the request needs), part (the request needs more than one action and this skill performs one required part), or different (a new leaf is authored) (phase navigate:intent, P(same)+P(part) >= intent_tau). All three taus are separate from the top-level tau so tuning reuse-vs-create or actionability does not move run assessment/fidelity. The category 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. A **category** softmax winner at or above `softmax_bypass_tau` (default 0.5) skips the scope confirm (traced `category_scope_bypassed`) — `create_category` is one of its options, so a confident winner really did beat authoring a category. The **leaf** intent guard is never bypassed: the leaf softmax offers only existing skills, so a confident winner is \"best of the wrong lot\", not a match, and the guard is the only leaf-level create door.",
"intent_tau": 0.6, "intent_tau": 0.6,
"category_tau": 0.75, "category_tau": 0.75,
"action_tau": 0.5, "action_tau": 0.5,
+11 -13
View File
@@ -64,8 +64,8 @@ flowchart TD
%% ---------- reuse vs create ---------- %% ---------- reuse vs create ----------
PICK --> HARD{"hard-locked category?<br/>(housekeeping)"} PICK --> HARD{"hard-locked category?<br/>(housekeeping)"}
HARD -- "yes" --> RUN HARD -- "yes" --> RUN
HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>P same >= intent_tau?"] HARD -- "no" --> INTENT["SemIf choice<br/>phase 'navigate:intent'<br/>same / part / different?<br/>P same+part >= intent_tau"]
INTENT -- "same" --> RUN INTENT -- "same / part" --> RUN
INTENT -- "different" --> CREATESKILL INTENT -- "different" --> CREATESKILL
CREATESKILL --> LOCK{"category locked to<br/>new skills?"} CREATESKILL --> LOCK{"category locked to<br/>new skills?"}
@@ -94,12 +94,11 @@ flowchart TD
ACTNI -- "no" --> ASSESS ACTNI -- "no" --> ASSESS
%% ---------- assessment ---------- %% ---------- assessment ----------
ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>P success >= tau?<br/>a definitive empty result counts as success"] --> OK{"success?"} ASSESS["SemIf choice<br/>phase 'assess:outcome'<br/>additional work to do?<br/>a definitive empty result counts as done"] --> OK{"outcome?"}
OK -- "yes" --> SUMMARY OK -- "done" --> SUMMARY
OK -- "no" --> REQ["SemIf choice<br/>phase 'assess:requeue'<br/>complete vs retry"] OK -- "continue" --> CHAIN["route the logical next step<br/>re-dispatch with the run ledger<br/>bounded by max_reentries + monotonic guard"]
REQ -- "retry" --> REQUEUE["requeue original request<br/>bounded by max_reentries"] CHAIN -.-> PUSH
REQUEUE -.-> PUSH OK -- "failed" --> REPAIR
REQ -- "complete" --> REPAIR
SUMMARY["deterministic summary<br/>category.name: ok/failed - action_log"] --> OUT1["Output: ran<br/>SchedulerReply (run_id, skill_ref, result)<br/>REPL · gateway reply · dashboard trace"] SUMMARY["deterministic summary<br/>category.name: ok/failed - action_log"] --> OUT1["Output: ran<br/>SchedulerReply (run_id, skill_ref, result)<br/>REPL · gateway reply · dashboard trace"]
@@ -112,8 +111,8 @@ flowchart TD
classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px; classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px;
classDef output fill:#fce8e6,stroke:#d93025; classDef output fill:#fce8e6,stroke:#d93025;
classDef author fill:#e6f4ea,stroke:#34a853; classDef author fill:#e6f4ea,stroke:#34a853;
class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REQ,REPAIR,RECORD semfill; class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REPAIR,RECORD semfill;
class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT output; class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT,CHAIN output;
class CREATECAT,CREATESKILL,AUTHORING author; class CREATECAT,CREATESKILL,AUTHORING author;
``` ```
@@ -196,10 +195,9 @@ flowchart TD
| Category scope | does it cover? | `navigate:category_scope` | descend / create (skipped when decisive) | | Category scope | does it cover? | `navigate:category_scope` | descend / create (skipped when decisive) |
| Canned | which reply | `navigate:response` | canned line | | Canned | which reply | `navigate:response` | canned line |
| Leaf | which skill | `navigate:leaf` | skill | | Leaf | which skill | `navigate:leaf` | skill |
| Intent guard | same action? | `navigate:intent` | run / create (never bypassed) | | Intent guard | same / part / different? | `navigate:intent` | run / create (never bypassed) |
| Config record | record or ask? | `config:record` | persisted / per-fire | | Config record | record or ask? | `config:record` | persisted / per-fire |
| Outcome | did it succeed? | `assess:outcome` | ok / failed | | Outcome | additional work? | `assess:outcome` | done / continue / failed |
| Requeue | complete or retry? | `assess:requeue` | done / requeue |
| Repair | how to recover? | `repair:choice` | offer | | Repair | how to recover? | `repair:choice` | offer |
| Fidelity | real action? | `authoring:fidelity` | accept / rewrite | | Fidelity | real action? | `authoring:fidelity` | accept / rewrite |
| Config search | where is the value? | `config:search` | auto-populate | | Config search | where is the value? | `config:search` | auto-populate |
+9 -3
View File
@@ -12,8 +12,11 @@ probability.
description plus `create_category`; `confirm_category_fit` confirms the description plus `create_category`; `confirm_category_fit` confirms the
winner's scope. `navigation.category_tau` is that guard's P(covers) floor. winner's scope. `navigation.category_tau` is that guard's P(covers) floor.
- **Leaf**: the softmax offers only existing skills; `confirm_skill_fit` - **Leaf**: the softmax offers only existing skills; `confirm_skill_fit`
compares the winner's action to the request. `navigation.intent_tau` is that decides what the winner does for the request (`same` / `part` / `different`).
guard's P(same) floor. `navigation.intent_tau` is that guard's P(same or part) floor: `same` or
`part` runs the skill, and only `different` authors a new leaf. The guard
decides contribution only; whether more work remains is `assess:outcome`'s
call.
This replays a hand-labeled eval set through the **real** decision engine and 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 the **real** skill tree, measuring each guard's probability per request so the
@@ -122,7 +125,10 @@ def measure(
confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau) confirm_skill_fit(scheduler.engine, log, trace, request, nav, tau=tau)
events = trace.read()[before:] events = trace.read()[before:]
guard = next((e for e in events if e["kind"] == "intent_guard"), None) 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} # The guard accepts a skill that is the same action OR one required part of a
# compound request, so the "does it contribute" mass is same + part.
p = (guard["probs"]["same"] + guard["probs"]["part"]) if guard else None
return {"picked": f"{nav.category}.{nav.name}", "p": p}
def verdict(measured: dict, tau: float) -> str: def verdict(measured: dict, tau: float) -> str:
+6 -1
View File
@@ -13,7 +13,7 @@ import urllib.error
import urllib.request import urllib.request
from semif_agent.decisions import DecisionRequest, Option from semif_agent.decisions import DecisionRequest, Option
from semif_agent.skills import ActionResult from semif_agent.skills import ActionResult, last_result
INTEGRATION = { INTEGRATION = {
"service": "simplex", "service": "simplex",
@@ -383,9 +383,14 @@ def act(ctx, request) -> ActionResult:
display_name = _display(chosen) or recipient display_name = _display(chosen) or recipient
# --- resolve the message text ----------------------------------------- # --- resolve the message text -----------------------------------------
# Prefer the literal text the user dictated; then the result of the previous
# step of a chain (never re-derive a computed value with the LLM); only then
# ask the LLM bridge for genuinely new text.
message_text = _message_from_query(query) message_text = _message_from_query(query)
if not message_text and user_input and not used_input_for_contact: if not message_text and user_input and not used_input_for_contact:
message_text = user_input message_text = user_input
if not message_text:
message_text = last_result(request)
if not message_text: if not message_text:
written, reason = _llm_message_text(ctx, query) written, reason = _llm_message_text(ctx, query)
if written: if written:
+46 -1
View File
@@ -31,9 +31,10 @@ LLM_REPLY = "a friendly hello"
class FakeRequest: class FakeRequest:
"""Minimal stand-in for the agent's Request object (test-only).""" """Minimal stand-in for the agent's Request object (test-only)."""
def __init__(self, text, user_input=""): def __init__(self, text, user_input="", run_ledger=None):
self.text = text self.text = text
self.user_input = user_input self.user_input = user_input
self.run_ledger = list(run_ledger or [])
class FakeResult: class FakeResult:
@@ -272,6 +273,49 @@ def test_message_written_by_llm_bridge():
llm.server_close() llm.server_close()
def test_chained_result_is_sent():
"""As the later step of a chain, no literal text: send the prior step's result."""
reset()
simplex = start_server(SimplexHandler)
llm = start_server(LlmHandler)
try:
ctx = ActionContext(
engine=FakeEngine(),
config={
"simplex_bridge_url": base_url(simplex),
"simplex_bridge_token": SIMPLEX_TOKEN,
"llm_bridge_url": base_url(llm),
},
)
request = FakeRequest(
"send the result of 22 * 10 to pepper on simplex",
run_ledger=[
{
"query": "send the result of 22 * 10 to pepper on simplex",
"skill": "calculator.calculate",
"outcome": "Twenty-two times ten is two hundred twenty.",
}
],
)
result = skill.act(ctx, request)
assert not result.needs_input, result.action_log
# The prior result is used verbatim; the LLM bridge must NOT be asked to
# recompute it.
assert LlmHandler.seen == [], LlmHandler.seen
posts = [r for r in SimplexHandler.seen if r["method"] == "POST"]
assert len(posts) == 1, SimplexHandler.seen
assert posts[0]["body"] == {
"recipient": "c-pepper",
"text": "Twenty-two times ten is two hundred twenty.",
}, posts[0]
finally:
simplex.shutdown()
simplex.server_close()
llm.shutdown()
llm.server_close()
def test_missing_text_without_llm_asks(): def test_missing_text_without_llm_asks():
"""A clear recipient but no message text and no llm bridge: ask the user.""" """A clear recipient but no message text and no llm bridge: ask the user."""
reset() reset()
@@ -360,6 +404,7 @@ def main():
test_happy_path() test_happy_path()
test_ambiguous_contact_uses_engine() test_ambiguous_contact_uses_engine()
test_message_written_by_llm_bridge() test_message_written_by_llm_bridge()
test_chained_result_is_sent()
test_missing_text_without_llm_asks() test_missing_text_without_llm_asks()
test_unknown_contact_asks() test_unknown_contact_asks()
test_send_refused_is_reported() test_send_refused_is_reported()
+17 -6
View File
@@ -485,16 +485,26 @@ def _print_approvals(scheduler: Scheduler) -> None:
print(f"[approval] {item['id']} new {item['kind']} {target}: {item['description']}") print(f"[approval] {item['id']} new {item['kind']} {target}: {item['description']}")
def _print_reply(reply, show_run_id: bool = False) -> None: def _print_reply(reply, show_run_id: bool = False, verbosity: str = "result") -> None:
"""Print a scheduler reply, optionally keeping its run id visible.""" """Print a scheduler reply, honoring the configured verbosity.
"result" shows only the final answer of a request (an intermediate chain
step is hidden); "query" also shows intermediate steps; "decision"
additionally prints each SemIf decision phase for the run.
"""
if getattr(reply, "intermediate", False) and verbosity == "result":
return
label = f"[{reply.run_id}] " if (show_run_id and reply.run_id) else "" label = f"[{reply.run_id}] " if (show_run_id and reply.run_id) else ""
print(f"[{reply.status}] {label}{reply.text}") print(f"[{reply.status}] {label}{reply.text}")
for line in getattr(reply, "decision_lines", ()) or ():
print(f" {line}")
def _drain_queue(scheduler: Scheduler) -> None: def _drain_queue(scheduler: Scheduler) -> None:
"""Run queued work, printing each outcome with its run id.""" """Run queued work, printing each outcome with its run id."""
verbosity = getattr(scheduler, "verbosity", "result")
for reply in scheduler.run_queue(): for reply in scheduler.run_queue():
_print_reply(reply, show_run_id=True) _print_reply(reply, show_run_id=True, verbosity=verbosity)
def _fatal_exit(scheduler: Scheduler) -> int | None: def _fatal_exit(scheduler: Scheduler) -> int | None:
@@ -646,13 +656,13 @@ def repl(scheduler: Scheduler, config: dict) -> int:
scheduler.busy(line[5:].strip()) scheduler.busy(line[5:].strip())
print("current process set (busy).") print("current process set (busy).")
continue continue
_print_reply(scheduler.submit(line)) _print_reply(scheduler.submit(line), verbosity=scheduler.verbosity)
if _fatal_exit(scheduler) is not None: if _fatal_exit(scheduler) is not None:
return 1 return 1
while scheduler.pending is not None: while scheduler.pending is not None:
hint = "" if scheduler.pending.pre_act else " [leave empty to skip]" hint = "" if scheduler.pending.pre_act else " [leave empty to skip]"
answer = input(f"{scheduler.pending.question}{hint} ") answer = input(f"{scheduler.pending.question}{hint} ")
_print_reply(scheduler.answer(answer)) _print_reply(scheduler.answer(answer), verbosity=scheduler.verbosity)
if _fatal_exit(scheduler) is not None: if _fatal_exit(scheduler) is not None:
return 1 return 1
_drain_queue(scheduler) _drain_queue(scheduler)
@@ -669,7 +679,8 @@ def scripted(scheduler: Scheduler, path: str) -> int:
rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()] rows = [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
for row in rows: for row in rows:
_print_reply( _print_reply(
scheduler.submit(str(row["text"]), source=row.get("source", "scripted")) scheduler.submit(str(row["text"]), source=row.get("source", "scripted")),
verbosity=scheduler.verbosity,
) )
if _fatal_exit(scheduler) is not None: if _fatal_exit(scheduler) is not None:
return 1 return 1
+8
View File
@@ -72,6 +72,13 @@ class Request:
reentries: int = 0 reentries: int = 0
resume: dict[str, Any] = field(default_factory=dict) resume: dict[str, Any] = field(default_factory=dict)
user_input: str | None = None user_input: str | None = None
#: Compact, deterministic record of the chain of skills already run toward
#: this request: one ``{query, skill (category.name), outcome}`` entry per
#: step. It threads through a continuation so the next step's routing and
#: the outcome assessment see what was already done; empty on a first-step
#: request. Bounded by construction (each outcome is bounded to the
#: speakable budget, and the chain is capped).
run_ledger: list[dict[str, Any]] = field(default_factory=list)
def copy_for_requeue(self) -> "Request": def copy_for_requeue(self) -> "Request":
return Request( return Request(
@@ -83,4 +90,5 @@ class Request:
priority=self.priority, priority=self.priority,
reentries=self.reentries + 1, reentries=self.reentries + 1,
resume=dict(self.resume), resume=dict(self.resume),
run_ledger=[dict(entry) for entry in self.run_ledger],
) )
+15
View File
@@ -313,6 +313,7 @@ class GatewayService:
reply = self.scheduler.answer(msg.text) reply = self.scheduler.answer(msg.text)
if self.scheduler.pending is None: if self.scheduler.pending is None:
self._pending_owner = None self._pending_owner = None
if not self._hidden(reply):
self._reply( self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status), *reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result, skill_ref=reply.skill_ref, result=reply.result,
@@ -348,6 +349,7 @@ class GatewayService:
self._owners[reply.run_id] = reply_to self._owners[reply.run_id] = reply_to
if reply.status == "needs_input": if reply.status == "needs_input":
self._pending_owner = reply_to self._pending_owner = reply_to
if not self._hidden(reply):
self._reply( self._reply(
*reply_to, reply.text, kind=_reply_kind(reply.status), *reply_to, reply.text, kind=_reply_kind(reply.status),
skill_ref=reply.skill_ref, result=reply.result, skill_ref=reply.skill_ref, result=reply.result,
@@ -362,6 +364,8 @@ class GatewayService:
if not results: if not results:
break break
for reply in results: for reply in results:
if self._hidden(reply):
continue
owner = self._owner_of(reply.run_id) owner = self._owner_of(reply.run_id)
if reply.status == "needs_input" and owner: if reply.status == "needs_input" and owner:
self._pending_owner = owner self._pending_owner = owner
@@ -372,6 +376,17 @@ class GatewayService:
skill_ref=reply.skill_ref, result=reply.result, skill_ref=reply.skill_ref, result=reply.result,
) )
def _hidden(self, reply) -> bool:
"""Hide an intermediate chain step at `result` verbosity.
The default end-user view is just the final answer; a chained request's
intermediate "continue" steps are only surfaced at `query`/`decision`
verbosity.
"""
if not getattr(reply, "intermediate", False):
return False
return getattr(self.scheduler, "verbosity", "result") == "result"
def surface(self, origin: Target | None = None) -> None: def surface(self, origin: Target | None = None) -> None:
"""Send any newly posted authoring questions / repair offers.""" """Send any newly posted authoring questions / repair offers."""
questions = self.scheduler.pending_questions() questions = self.scheduler.pending_questions()
+164 -16
View File
@@ -90,6 +90,25 @@ def normalize_new_skill_mode(value) -> str | None:
return None return None
#: Output verbosity levels. "result" (default) shows only the final result of a
#: request; "query" also shows each intermediate chain step (query + ledger);
#: "decision" also shows each SemIf decision phase.
VERBOSITY_LEVELS = ("result", "query", "decision")
def normalize_verbosity(value) -> str:
"""Coerce a configured verbosity to one of `VERBOSITY_LEVELS`.
Unrecognized/absent falls back to the "result" default (the end user only
wants the answer, not each decision or query).
"""
if isinstance(value, str):
mode = value.strip().lower()
if mode in VERBOSITY_LEVELS:
return mode
return "result"
@dataclass @dataclass
class Process: class Process:
request: Request request: Request
@@ -223,6 +242,10 @@ class DispatchResult:
#: The skill's own detail (its `action_log`, or `new_state` when empty) — #: The skill's own detail (its `action_log`, or `new_state` when empty) —
#: the unwrapped result a `result_only` front end speaks. #: the unwrapped result a `result_only` front end speaks.
result: str | None = None result: str | None = None
#: True when this step is an intermediate "continue" of a chained request:
#: the request is re-dispatched and the *final* step's reply is the answer.
#: A `result`-verbosity front end hides intermediates.
intermediate: bool = False
@dataclass @dataclass
@@ -240,6 +263,11 @@ class SchedulerReply:
run_id: str = "" run_id: str = ""
skill_ref: str | None = None skill_ref: str | None = None
result: str | None = None result: str | None = None
#: See `DispatchResult.intermediate`.
intermediate: bool = False
#: At `decision` verbosity only: the SemIf decision phases (with the selected
#: option) recorded for this run, for a debugging front end.
decision_lines: list[str] = field(default_factory=list)
class Scheduler: class Scheduler:
@@ -275,6 +303,19 @@ class Scheduler:
#: option, so its confidence carries no match signal). #: option, so its confidence carries no match signal).
self.bypass_tau = float(nav_cfg.get("softmax_bypass_tau", 0.5)) self.bypass_tau = float(nav_cfg.get("softmax_bypass_tau", 0.5))
self.max_reentries = max_reentries self.max_reentries = max_reentries
#: How much of a completed chain to surface. "result" (default): only the
#: final result; "query": also each intermediate step's query + ledger;
#: "decision": also each SemIf decision phase (a debugging view).
self.verbosity = normalize_verbosity(config.get("verbosity"))
#: One shared speakable budget for every skill's output (the result string
#: and its run-ledger entry): a result is read in a chat or spoken, so it
#: is truncated to this many characters at a word boundary.
chain_cfg = config.get("chain", {}) or {}
self.result_chars = int(chain_cfg.get("result_chars", 300))
#: The `assess:outcome` thresholds (precedence failed > done > continue).
assess_cfg = config.get("assess", {}) or {}
self.done_tau = float(assess_cfg.get("done_tau", 0.5))
self.fail_tau = float(assess_cfg.get("fail_tau", 0.5))
self.codegen = codegen self.codegen = codegen
self.degeneration_check_factory = degeneration_check_factory self.degeneration_check_factory = degeneration_check_factory
self.regen_decision_factory = regen_decision_factory self.regen_decision_factory = regen_decision_factory
@@ -329,7 +370,13 @@ class Scheduler:
engine=self.engine, config=config, timers=self.timers, admin=self engine=self.engine, config=config, timers=self.timers, admin=self
) )
self.runner = SkillRunner( self.runner = SkillRunner(
self.ctx, self.log, store=self.body_store, tau=self.tau self.ctx,
self.log,
store=self.body_store,
tau=self.tau,
done_tau=self.done_tau,
fail_tau=self.fail_tau,
result_chars=self.result_chars,
) )
self._fatal: str | None = None self._fatal: str | None = None
self.current: Process | None = None self.current: Process | None = None
@@ -404,11 +451,14 @@ class Scheduler:
return SchedulerReply( return SchedulerReply(
"needs_input", outcome.summary, request.id, "needs_input", outcome.summary, request.id,
outcome.skill_ref, outcome.result, outcome.skill_ref, outcome.result,
decision_lines=self._decision_lines(request.id),
) )
self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary) self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary)
return SchedulerReply( return SchedulerReply(
"running", outcome.summary, request.id, "running", outcome.summary, request.id,
outcome.skill_ref, outcome.result, outcome.skill_ref, outcome.result,
intermediate=outcome.intermediate,
decision_lines=self._decision_lines(request.id),
) )
ok = self.queue.push(request) ok = self.queue.push(request)
@@ -467,6 +517,7 @@ class Scheduler:
SchedulerReply( SchedulerReply(
"needs_input", outcome.summary, request.id, "needs_input", outcome.summary, request.id,
outcome.skill_ref, outcome.result, outcome.skill_ref, outcome.result,
decision_lines=self._decision_lines(request.id),
) )
) )
continue continue
@@ -475,10 +526,31 @@ class Scheduler:
SchedulerReply( SchedulerReply(
"ran", outcome.summary, request.id, "ran", outcome.summary, request.id,
outcome.skill_ref, outcome.result, outcome.skill_ref, outcome.result,
intermediate=outcome.intermediate,
decision_lines=self._decision_lines(request.id),
) )
) )
return results return results
def _decision_lines(self, request_id: str) -> list[str]:
"""The SemIf decision phases recorded for one run.
Only populated at `decision` verbosity (a debugging view); every other
level returns an empty list so a normal front end never sees SemIf
internals.
"""
if self.verbosity != "decision":
return []
lines = []
for row in self.log.read():
extra = row.get("extra") or {}
if extra.get("run_id") != request_id:
continue
probs = row.get("predicted_probs") or {}
rendered = " ".join(f"{k}={v:.2f}" for k, v in probs.items())
lines.append(f"{extra.get('phase', '?')}: {row.get('selected', '?')} [{rendered}]")
return lines
# ---- dispatch ---- # ---- dispatch ----
def _dispatch(self, request: Request) -> DispatchResult: def _dispatch(self, request: Request) -> DispatchResult:
@@ -510,6 +582,11 @@ class Scheduler:
category_tau=self.category_tau, category_tau=self.category_tau,
action_tau=self.action_tau, action_tau=self.action_tau,
bypass_tau=self.bypass_tau, bypass_tau=self.bypass_tau,
# A continuation (a request already carrying a run ledger) is the
# next step of an in-flight request, so it is actionable by
# construction and skips the actionability guard; only a fresh
# first-step input is checked against the closed `response` tree.
skip_actionability=bool(request.run_ledger),
) )
if isinstance(navigation, CreateCategory): if isinstance(navigation, CreateCategory):
if self.new_skill_mode == "deny": if self.new_skill_mode == "deny":
@@ -531,9 +608,10 @@ class Scheduler:
# therefore the sole leaf-level create door and is never bypassed: a # therefore the sole leaf-level create door and is never bypassed: a
# confident softmax winner among only-wrong options must still be # confident softmax winner among only-wrong options must still be
# checked, or codegen can never be reached for an unmatched request. # checked, or codegen can never be reached for an unmatched request.
if not confirm_skill_fit( verdict = confirm_skill_fit(
self.engine, self.log, self.trace, request, navigation, self.intent_tau self.engine, self.log, self.trace, request, navigation, self.intent_tau
): )
if verdict == "different":
self.trace.append( self.trace.append(
"intent_mismatch", "intent_mismatch",
request.id, request.id,
@@ -543,6 +621,10 @@ class Scheduler:
if self._category_locked(navigation.category): if self._category_locked(navigation.category):
return self._blocked_create(request, navigation.category) return self._blocked_create(request, navigation.category)
return self._dispatch_skill(request, navigation.category) return self._dispatch_skill(request, navigation.category)
# `same` or `part` both run the skill: a `part` step is one required part
# of a compound request, and whether more work remains is `assess:outcome`'s
# call — never the guard's. (Forcing a `continue` here overrode a correct
# `done` on the final step and drove the chain into a spurious create.)
return self._run_skill(navigation, request) return self._run_skill(navigation, request)
def _dispatch_create_category(self, request: Request) -> DispatchResult: def _dispatch_create_category(self, request: Request) -> DispatchResult:
@@ -707,12 +789,15 @@ class Scheduler:
return SchedulerReply( return SchedulerReply(
"needs_input", result.summary, pending.request.id, "needs_input", result.summary, pending.request.id,
result.skill_ref, result.result, result.skill_ref, result.result,
decision_lines=self._decision_lines(pending.request.id),
) )
self.current = None self.current = None
self.trace.append("ran", pending.request.id, skill=result.skill, summary=result.summary) self.trace.append("ran", pending.request.id, skill=result.skill, summary=result.summary)
return SchedulerReply( return SchedulerReply(
"ran", f"[resumed] {result.summary}", pending.request.id, "ran", f"[resumed] {result.summary}", pending.request.id,
result.skill_ref, result.result, result.skill_ref, result.result,
intermediate=result.intermediate,
decision_lines=self._decision_lines(pending.request.id),
) )
def _finish_run(self, skill: Skill, request: Request, outcome) -> DispatchResult: def _finish_run(self, skill: Skill, request: Request, outcome) -> DispatchResult:
@@ -741,29 +826,67 @@ class Scheduler:
skill_ref=f"{skill.category}.{skill.name}", skill_ref=f"{skill.category}.{skill.name}",
result=outcome.action_log or outcome.new_state or None, result=outcome.action_log or outcome.new_state or None,
) )
verdict = outcome.outcome or ("done" if outcome.success else "failed")
self.trace.append( self.trace.append(
"assessed", "assessed",
request.id, request.id,
skill=skill.name, skill=skill.name,
outcome=verdict,
success=outcome.success, success=outcome.success,
summary=outcome.summary, summary=outcome.summary,
assessment_summary=outcome.assessment_summary, assessment_summary=outcome.assessment_summary,
action_log=outcome.action_log, action_log=outcome.action_log,
updated_request=outcome.updated_request,
) )
requeued = False if verdict == "continue":
if outcome.updated_request and request.reentries < self.max_reentries: entry = {
child = _requeue(request, outcome.updated_request) "query": request.text,
# Remember what this attempt observed so the next assessment can "skill": f"{skill.category}.{skill.name}",
# tell a genuine retry (the result changed) from a guaranteed "outcome": outcome.action_log or outcome.new_state,
# repeat against unchanged state. }
child.meta["prev_result"] = outcome.action_log or outcome.new_state repeat = self._would_repeat(request, entry)
if request.reentries < self.max_reentries and not repeat:
child = _continue(request, entry)
self.queue.push(child) self.queue.push(child)
self.trace.append("requeued", request.id, text=outcome.updated_request) self.trace.append(
"continued",
request.id,
skill=entry["skill"],
outcome=entry["outcome"],
step=len(child.run_ledger),
)
if self.on_request_requeued is not None: if self.on_request_requeued is not None:
self.on_request_requeued(request.id, child.id) self.on_request_requeued(request.id, child.id)
requeued = True # Intermediate step: the request is re-dispatched, and the final
if not outcome.success and not (outcome.updated_request and requeued): # step's reply is the answer. A `result`-verbosity front end
# hides this reply.
return DispatchResult(
kind="ran",
summary=outcome.summary,
skill=skill.name,
decisions_logged=outcome.decisions_logged,
skill_ref=f"{skill.category}.{skill.name}",
result=(outcome.action_log or outcome.new_state or None),
intermediate=True,
)
# The chain stops here: it worked, but either the step budget is
# spent or the next step would repeat an identical (skill, outcome).
# This is not a failure, so no repair offer — just report what is
# still pending.
self.trace.append(
"chain_halted",
request.id,
skill=entry["skill"],
reason="repeat" if repeat else "budget",
)
return DispatchResult(
kind="ran",
summary=outcome.summary,
skill=skill.name,
decisions_logged=outcome.decisions_logged,
skill_ref=f"{skill.category}.{skill.name}",
result=(outcome.action_log or outcome.new_state or None),
)
if verdict == "failed":
self._propose_repair(skill, request, outcome) self._propose_repair(skill, request, outcome)
return DispatchResult( return DispatchResult(
kind="ran", kind="ran",
@@ -774,6 +897,21 @@ class Scheduler:
result=(outcome.action_log or outcome.new_state or None), result=(outcome.action_log or outcome.new_state or None),
) )
def _would_repeat(self, request: Request, entry: dict) -> bool:
"""Would entering this step repeat an identical (skill, outcome)?
The monotonic-progress guard: each chain step must either select a
*different* skill or produce a *changed* outcome. A repeated pair means
the chain is not making progress (the request and external state are
unchanged), so it must stop instead of looping.
"""
skill = entry.get("skill")
outcome = entry.get("outcome")
return any(
prior.get("skill") == skill and prior.get("outcome") == outcome
for prior in request.run_ledger
)
# ---- repair loop ---- # ---- repair loop ----
def _propose_repair(self, skill: Skill, request: Request, outcome) -> None: def _propose_repair(self, skill: Skill, request: Request, outcome) -> None:
@@ -2305,10 +2443,20 @@ class Scheduler:
return "\n".join(lines) return "\n".join(lines)
def _requeue(request: Request, updated_text: str) -> Request: def _continue(request: Request, entry: dict) -> Request:
updated = Request(updated_text, source="requeue") """Build the next-step request for a chained run.
Deterministic: the *new query* is the original goal re-fed with the run
ledger attached (composed in `compose_state`), never a generated utterance.
Carries the prior ledger plus this step's entry, bumps the step count, and
links the parent run so a front end can route the completion home. `meta` is
intentionally not copied (a later step is a different skill, so per-fire
config answers must not leak forward).
"""
updated = Request(request.text, source="continue")
updated.reentries = request.reentries + 1 updated.reentries = request.reentries + 1
updated.meta["parent_run"] = request.id updated.meta["parent_run"] = request.id
updated.run_ledger = [dict(e) for e in request.run_ledger] + [dict(entry)]
return updated return updated
+91 -81
View File
@@ -7,11 +7,13 @@ the human for anything unresolved), performs the real action, and returns an
`ActionResult.decisions` and are logged by the runner with the run outcome. `ActionResult.decisions` and are logged by the runner with the run outcome.
Assessment is a SemIf decision, not generation: `assess:outcome` decides Assessment is a SemIf decision, not generation: `assess:outcome` decides
success/failure (P(success) >= tau) and, on failure, `assess:requeue` decides whether there is any additional work to do — `done` (request satisfied),
complete/retry. The run summary is deterministic — same inputs, same string — `continue` (the step worked but more work is needed; the scheduler routes the
built from the category, skill, outcome flag, and action log. Every SemIf next step), or `failed` (the step errored → the repair path). The run summary is
decision made during a run is logged as a training row; the assessment outcome deterministic — same inputs, same string — built from the category, skill,
is kept on the row so the dream pass can weigh failed runs. outcome flag, and action log. Every SemIf decision made during a run is logged as
a training row; the assessment outcome is kept on the row so the dream pass can
weigh failed runs.
A skill with a data contract may need variables collected from the human before A skill with a data contract may need variables collected from the human before
it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered
@@ -35,6 +37,8 @@ from .skills import (
ActionContext, ActionContext,
Skill, Skill,
SkillStore, SkillStore,
bound_output,
render_ledger,
resolve_skill_config, resolve_skill_config,
unresolved_variables, unresolved_variables,
) )
@@ -87,7 +91,12 @@ class RunResult:
summary: str summary: str
action_log: str action_log: str
new_state: str new_state: str
updated_request: str | None = None #: The three-way outcome for a chained run: "done" (request satisfied),
#: "continue" (the step worked but more work is needed → the scheduler routes
#: the next step), or "failed" (the step errored → the repair path). None
#: only for a pause for input (needs_input/error), which never reaches the
#: outcome branch.
outcome: str | None = None
decisions_logged: int = 0 decisions_logged: int = 0
assessment_summary: str = "" assessment_summary: str = ""
error: str | None = None error: str | None = None
@@ -102,11 +111,25 @@ class SkillRunner:
log: DecisionLog, log: DecisionLog,
store: SkillStore | None = None, store: SkillStore | None = None,
tau: float = 0.6, tau: float = 0.6,
done_tau: float = 0.5,
fail_tau: float = 0.5,
result_chars: int = 300,
): ):
self.ctx = ctx self.ctx = ctx
self.log = log self.log = log
self.store = store self.store = store
self.tau = tau self.tau = tau
#: Thresholds for the three-way `assess:outcome` decision. Precedence is
#: failed > done > continue: a step is only declared "continue" when the
#: model is genuinely unsure, so a confident success/failure is honored
#: and the chain is not entered needlessly.
self.done_tau = done_tau
self.fail_tau = fail_tau
#: The shared speakable budget: every skill's action_log/new_state is
#: truncated to this many characters (the same bound the voice front end
#: and the humanizer use), so a result fits one message / ~20s of speech
#: and the run ledger stays bounded.
self.result_chars = result_chars
# ---- contract resolution ---- # ---- contract resolution ----
@@ -288,111 +311,98 @@ class SkillRunner:
def _assess( def _assess(
self, skill: Skill, request: Request, ctx: ActionContext, action self, skill: Skill, request: Request, ctx: ActionContext, action
) -> tuple[bool, str | None]: ) -> str:
"""SemIf assessment: did the run succeed, and should it run again? """SemIf assessment: is there any *additional work* to be done?
`assess:outcome` decides success (`P(success) >= tau`); a failure is A single three-way `assess:outcome` decision over the step's own action
then offered to `assess:requeue`, which picks complete/retry. On retry plus the run ledger so far:
the original request text is re-dispatched (the scheduler bounds it by
`max_reentries`). Both are real logged decision rows. The state carries - ``done`` — the request is satisfied (a definitive "nothing found"
the skill's declared action, the goal, and the resolved inputs so the counts as done);
decision sees what the skill was meant to do and how its inputs - ``continue`` — the step worked, but the request is not yet satisfied;
resolved; the requeue state additionally flags a retry that would the scheduler routes the next step (bounded by ``max_reentries`` and
reproduce the identical observed result as a no-op. The engine is always the monotonic-progress guard);
real: EngineUnavailable propagates to the scheduler, which marks the app - ``failed`` — the step errored / did not work → the repair path.
fatal.
The verdict uses thresholds, not argmax, with precedence
``failed > done > continue`` (``fail_tau`` then ``done_tau``), so a
confident success/failure is honored and ``continue`` — the over-trigger
— only wins when the model is genuinely unsure. Real logged decision row
(phase `assess:outcome`). The state carries the skill's declared action,
the goal, the resolved inputs, the (bounded) action log, and the steps
already taken. The engine is always real: EngineUnavailable propagates to
the scheduler, which marks the app fatal.
""" """
label = f"{skill.category}.{skill.name}" label = f"{skill.category}.{skill.name}"
resolved = _resolved_inputs(skill, ctx.config) resolved = _resolved_inputs(skill, ctx.config)
outcome = DecisionRequest( observed = bound_output(action.action_log, self.result_chars)
state=( if not observed:
observed = bound_output(action.new_state, self.result_chars)
state = (
f"skill: {label}\n" f"skill: {label}\n"
f"skill action: {skill.description}\n" f"skill action: {skill.description}\n"
f"goal: {request.text}\n" f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n" f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}" f"action log:\n{observed}"
), )
question="Did the skill achieve the user's goal?", ledger = render_ledger(request.run_ledger)
if ledger:
state += f"\nsteps already taken:\n{ledger}"
decision = DecisionRequest(
state=state,
question="Is there any additional work to be done to satisfy the request?",
options=[ options=[
Option( Option(
"success", "done",
"Yes — the skill carried out the request and produced a " "No — the request is satisfied. A definitive 'nothing found' "
"truthful result. A definitive 'nothing found' or 'nothing " "or 'nothing to do' result (empty inbox, no unread messages, "
"to do' result (empty inbox, no unread messages, no " "no matching event) counts as done.",
"matching event) counts as success.",
), ),
Option( Option(
"failure", "continue",
"No — the request was not carried out, or the result is an " "Yes — this step worked, but the request is not yet satisfied; "
"error, a refusal, or an unresolved action.", "another skill should run next toward the same request.",
),
Option(
"failed",
"The step did not work: the result is an error, a refusal, or "
"an unresolved action.",
), ),
], ],
) )
result = self.ctx.engine.call(outcome) result = self.ctx.engine.call(decision)
self.log.append( self.log.append(
outcome, decision,
result, result,
extra={"phase": "assess:outcome", "run_id": request.id, "skill": label}, extra={"phase": "assess:outcome", "run_id": request.id, "skill": label},
) )
success = result.prob("success") >= self.tau probs = result.probs
if success: if probs.get("failed", 0.0) >= self.fail_tau:
return True, None return "failed"
if probs.get("done", 0.0) >= self.done_tau:
# A retry that would reproduce the identical observed result is a return "done"
# guaranteed no-op run (the request, config, and external state are return "continue"
# unchanged), so the requeue decision is told before it can pick
# `retry` again — otherwise a deterministic failure loops through the
# reentry ladder and ends in a repair offer for a working skill.
observed = action.action_log or action.new_state
prev = request.meta.get("prev_result")
no_progress = ""
if prev is not None and prev == observed:
no_progress = (
"\nAttempts so far produced the identical result; retrying "
"would repeat the same run against unchanged state."
)
requeue = DecisionRequest(
state=(
f"skill: {label}\n"
f"skill action: {skill.description}\n"
f"goal: {request.text}\n"
f"resolved inputs:\n{resolved}\n"
f"action log:\n{action.action_log}\n"
"outcome: failed"
f"{no_progress}"
),
question="Is the request complete, or should it run again?",
options=[
Option("complete", "It is complete; do nothing further."),
Option("retry", "Run the original request again."),
],
)
requeue_result = self.ctx.engine.call(requeue)
self.log.append(
requeue,
requeue_result,
extra={"phase": "assess:requeue", "run_id": request.id, "skill": label},
)
updated = request.text if requeue_result.prob("retry") >= self.tau else None
return False, updated
def _finish( def _finish(
self, skill: Skill, request: Request, ctx: ActionContext, action self, skill: Skill, request: Request, ctx: ActionContext, action
) -> RunResult: ) -> RunResult:
observed = action.new_state action_log = bound_output(action.action_log, self.result_chars)
observed = bound_output(action.new_state, self.result_chars)
if skill.category in CANNED_CATEGORIES or skill.category in DETERMINISTIC_CATEGORIES: if skill.category in CANNED_CATEGORIES or skill.category in DETERMINISTIC_CATEGORIES:
summary = deterministic_summary( summary = deterministic_summary(
skill.category, skill.name, True, action.action_log, observed skill.category, skill.name, True, action_log, observed
) )
return RunResult( return RunResult(
skill=skill.name, skill=skill.name,
success=True, success=True,
summary=summary, summary=summary,
action_log=action.action_log, action_log=action_log,
new_state=observed, new_state=observed,
assessment_summary=summary, assessment_summary=summary,
outcome="done",
) )
success, updated_request = self._assess(skill, request, ctx, action) verdict = self._assess(skill, request, ctx, action)
success = verdict != "failed"
decisions = getattr(action, "decisions", []) decisions = getattr(action, "decisions", [])
for decision, result in decisions: for decision, result in decisions:
@@ -408,15 +418,15 @@ class SkillRunner:
) )
summary = deterministic_summary( summary = deterministic_summary(
skill.category, skill.name, success, action.action_log, observed skill.category, skill.name, success, action_log, observed
) )
return RunResult( return RunResult(
skill=skill.name, skill=skill.name,
success=success, success=success,
summary=summary, summary=summary,
action_log=action.action_log, action_log=action_log,
new_state=observed, new_state=observed,
updated_request=updated_request, outcome=verdict,
decisions_logged=len(decisions), decisions_logged=len(decisions),
assessment_summary=summary, assessment_summary=summary,
) )
+122 -29
View File
@@ -575,11 +575,61 @@ def unresolved_variables(
return [name for name in (skill.contract or {}) if name not in merged] return [name for name in (skill.contract or {}) if name not in merged]
def bound_output(text: str, limit: int) -> str:
"""Truncate a skill's output to the speakable budget.
A skill result is read in a text message or heard as speech, so a long
result is a bad result: the budget is the one shared bound (the same one the
voice front end and the humanizer use). Truncation is at a word boundary and
marked with an ellipsis; a non-positive limit disables it. A long *product*
of a skill belongs in a file I/O side effect, not in the result string (see
CODEGEN.md / TESTGEN.md).
"""
if limit <= 0 or len(text) <= limit:
return text
clipped = text[:limit].rsplit(" ", 1)[0] or text[:limit]
return clipped + "…"
def render_ledger(entries: list[dict]) -> str:
"""Render the run ledger as a compact, deterministic block.
One line per step: ``N. <category.skill> -> <outcome>``. Same entries, same
string. Threaded into the routing/assessment state so a continuation sees
what was already done toward the request.
"""
lines = []
for index, entry in enumerate(entries, 1):
skill = entry.get("skill") or "?"
outcome = (entry.get("outcome") or "").strip()
lines.append(f" {index}. {skill} -> {outcome}" if outcome else f" {index}. {skill}")
return "\n".join(lines)
def last_result(request: Request) -> str:
"""The most recent chained step's result, or "" on a first-step request.
A body that runs as a later step of a chain reads this to use what the
previous step produced (e.g. a computed value to send) instead of
recomputing or fabricating it. The value is the prior step's bounded outcome
(its ``action_log`` or ``new_state``) — the same text the run ledger carries
and renders into the routing/assessment state.
"""
ledger = getattr(request, "run_ledger", None) or []
if not ledger:
return ""
return str(ledger[-1].get("outcome") or "")
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 additional_context: if additional_context:
parts.append(f"({additional_context})") parts.append(f"({additional_context})")
return " ".join(parts) state = " ".join(parts)
ledger = render_ledger(request.run_ledger)
if ledger:
state = f"{state}\nsteps already taken:\n{ledger}"
return state
def _canned_response(name: str, message: str): def _canned_response(name: str, message: str):
@@ -1174,6 +1224,7 @@ def navigate(
category_tau: float = 0.75, category_tau: float = 0.75,
action_tau: float = 0.5, action_tau: float = 0.5,
bypass_tau: float = 0.5, bypass_tau: float = 0.5,
skip_actionability: bool = False,
) -> 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.
@@ -1226,7 +1277,7 @@ def navigate(
"create_category", "create_category",
request.id, request.id,
state=compose_state(request), state=compose_state(request),
question="Which top-level category handles this request?", question="Which category is the logical next step toward satisfying this request?",
options=[], options=[],
selected="create_category", selected="create_category",
probs={}, probs={},
@@ -1236,8 +1287,10 @@ def navigate(
# Actionability first: is this input a request at all? A non-request goes to # Actionability first: is this input a request at all? A non-request goes to
# the closed `response` tree (a canned reply) and never reaches the category # the closed `response` tree (a canned reply) and never reaches the category
# softmax; a request always proceeds to category selection, so it can never # softmax; a request always proceeds to category selection, so it can never
# be canned. # be canned. A **continuation** (a request already carrying a run ledger) is
if confirm_non_action(engine, log, trace, request, action_tau): # actionable by construction — it is the next step of an in-flight request —
# so it skips this guard; only a fresh first-step input is checked.
if not skip_actionability and confirm_non_action(engine, log, trace, request, action_tau):
response_skills = tree.get("response") response_skills = tree.get("response")
if response_skills: if response_skills:
return _navigate_canned( return _navigate_canned(
@@ -1247,7 +1300,7 @@ def navigate(
"create_category", "create_category",
request.id, request.id,
state=compose_state(request), state=compose_state(request),
question="Which top-level category handles this request?", question="Which category is the logical next step toward satisfying this request?",
options=[], options=[],
selected="create_category", selected="create_category",
probs={}, probs={},
@@ -1263,7 +1316,7 @@ def navigate(
) )
top = DecisionRequest( top = DecisionRequest(
state=compose_state(request), state=compose_state(request),
question="Which top-level category handles this request?", question="Which category is the logical next step toward satisfying this request?",
options=[Option(c, descriptions.get(c, c)) for c in categories] options=[Option(c, descriptions.get(c, c)) for c in categories]
+ [create_category], + [create_category],
) )
@@ -1338,7 +1391,7 @@ def navigate(
request, request,
additional_context=f"all choices are within the {category} category", additional_context=f"all choices are within the {category} category",
), ),
question=f"Which {category} skill performs the action this request asks for?", question=f"Which {category} skill should run next to help satisfy this request?",
options=[Option(s.name, s.description) for s in skills], options=[Option(s.name, s.description) for s in skills],
) )
leaf_result = engine.call(leaf) leaf_result = engine.call(leaf)
@@ -1482,36 +1535,67 @@ def confirm_skill_fit(
request: Request, request: Request,
skill: Skill, skill: Skill,
tau: float = 0.6, tau: float = 0.6,
) -> bool: ) -> str:
"""Does this skill's action actually match what the request asks for? """What does this skill do for the request? "same" | "part" | "different".
Navigation picks the closest existing leaf; this guard is now the **sole** Navigation picks the closest existing leaf; this guard is the **sole**
leaf-level reuse-vs-create decision (create_skill is no longer an option in leaf-level reuse-vs-create decision (create_skill is no longer an option in
the leaf softmax). If the skill's action is not the same action the request the leaf softmax). It answers three ways:
asks for, dispatch authors a new leaf instead. The threshold is
`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* - ``same`` — the skill performs the next action the request needs (running it
("different action") is unambiguous where "can this serve the request" was can satisfy the request, or is its final step);
not — e.g. "message Sam" (an implicit send in instant-messaging syntax) - ``part`` — the request needs more than one action and this skill performs
reads as a different action from "read the next message". Do not add an one required part of it;
instant-messaging context hint: it over-fires and pulls read phrasings to - ``different`` — the skill does not do any action the request asks for;
the send side. The comparison is over-permissive on near-synonyms (read vs dispatch authors a new leaf instead.
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. ``same``/``part`` run the skill; ``different`` is the create door. The guard
only decides whether the skill *contributes* — whether more work remains is
``assess:outcome``'s call (the guard must never force a continuation: in a
real run it labeled the final send step ``part`` 0.85 while the assessment
correctly said ``done`` 0.99, and a forced continue drove the chain into a
spurious new category). The **run ledger is part of the state** so a later
step judges against the *remaining* work, not the whole request. Without the
ledger a compound request has no single skill that is ``same``, so the guard
would author a monolithic skill for every one of them — the bug this fixes (a
real run picked ``calculator.calculate`` at 0.99 and was rejected into
create_skill).
The threshold is ``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* is unambiguous where "can this serve the request" was not.
Do not add an instant-messaging context hint: it over-fires and pulls read
phrasings to the send side.
""" """
decision = DecisionRequest( state = (
state=(
f"Requested action: {request.text}\n" f"Requested action: {request.text}\n"
f"Action of the existing skill: {skill.description}" f"Action of the existing skill: {skill.description}"
)
ledger = render_ledger(request.run_ledger)
if ledger:
state += f"\nsteps already taken:\n{ledger}"
decision = DecisionRequest(
state=state,
question=(
"Given the steps already taken, what does this skill do for the "
"request?"
), ),
question="Compare the requested action and the skill's action. Are they the same action?",
options=[ options=[
Option("same", "Same action."), Option(
"same",
"It performs the next action the request needs and can satisfy "
"the request (or is its final step).",
),
Option(
"part",
"The request needs more than one action; this skill performs one "
"required part of it, and more steps remain after it.",
),
Option( Option(
"different", "different",
"Different action: the skill does not do what the user asks.", "It does not do any action the request asks for; a new skill is "
"needed.",
), ),
], ],
) )
@@ -1525,7 +1609,15 @@ def confirm_skill_fit(
"skill": f"{skill.category}.{skill.name}", "skill": f"{skill.category}.{skill.name}",
}, },
) )
fits = result.prob("same") >= tau same = result.prob("same")
part = result.prob("part")
fits = (same + part) >= tau
if not fits:
verdict = "different"
elif same >= part:
verdict = "same"
else:
verdict = "part"
trace.append( trace.append(
"intent_guard", "intent_guard",
request.id, request.id,
@@ -1533,9 +1625,10 @@ def confirm_skill_fit(
skill=skill.name, skill=skill.name,
selected=result.selected, selected=result.selected,
probs=result.probs, probs=result.probs,
verdict=verdict,
fits=fits, fits=fits,
) )
return fits return verdict
def tree_summary(tree: dict[str, list[Skill]]) -> str: def tree_summary(tree: dict[str, list[Skill]]) -> str:
+8 -6
View File
@@ -413,12 +413,14 @@ function eventNode(evt) {
body.className = "node-question"; body.className = "node-question";
if (evt.kind === "assessed") { if (evt.kind === "assessed") {
body.textContent = evt.summary || ""; body.textContent = evt.summary || "";
if (evt.updated_request) { } else if (evt.kind === "continued") {
const req = document.createElement("div"); body.textContent = `→ next step: ${evt.skill || ""}`;
req.className = "muted"; const outcome = document.createElement("div");
req.textContent = `→ requeued: ${evt.updated_request}`; outcome.className = "muted";
node.appendChild(req); outcome.textContent = `outcome: ${evt.outcome || ""}`;
} node.appendChild(outcome);
} else if (evt.kind === "chain_halted") {
body.textContent = `chain halted (${evt.reason || ""})`;
} else if (evt.kind === "queued") { } else if (evt.kind === "queued") {
body.textContent = "queued"; body.textContent = "queued";
} else if (evt.kind === "dropped") { } else if (evt.kind === "dropped") {
+1 -1
View File
@@ -2,7 +2,7 @@
scheduler. scheduler.
Decision rows live in `decisions.jsonl` (SemIf-compatible). Lifecycle events Decision rows live in `decisions.jsonl` (SemIf-compatible). Lifecycle events
(submit, dropped, queued, dequeued, assessed, requeued, ...) live here in (submit, dropped, queued, dequeued, assessed, continued, ...) live here in
`runs.jsonl`, keyed by `run_id` (the request id) so the dashboard can rebuild `runs.jsonl`, keyed by `run_id` (the request id) so the dashboard can rebuild
each run's flow without touching the decision-log contract. Both files are each run's flow without touching the decision-log contract. Both files are
append-only; replays read them in order. append-only; replays read them in order.
+9 -15
View File
@@ -720,24 +720,21 @@ def test_empty_result_is_assessed_as_success(tmp_path):
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
runner = SkillRunner(ActionContext(engine=engine, config={}), log) runner = SkillRunner(ActionContext(engine=engine, config={}), log)
outcome = runner.run(skill, Request("What's my next simplex message?")) outcome = runner.run(skill, Request("What's my next simplex message?"))
print(f"[{outcome.success}] {outcome.summary}") print(f"[{outcome.outcome}] {outcome.summary}")
assert outcome.success is True, outcome.summary assert outcome.outcome == "done", outcome.summary
phases = [row["extra"]["phase"] for row in log.read()] phases = [row["extra"]["phase"] for row in log.read()]
assert "assess:outcome" in phases assert "assess:outcome" in phases
assert "assess:requeue" not in phases, (
"an empty discovery must not be retried or repaired"
)
def test_read_result_is_assessed_as_success(tmp_path): def test_read_result_is_assessed_as_done(tmp_path):
"""A correctly-read result is a successful run, not a failure. """A correctly-read result is a satisfied request, not a failure.
The assessment must see the skill's declared action; with only the skill The assessment must see the skill's declared action; with only the skill
label the real model marked a truthful read failed for ambiguous phrasings label the real model marked a truthful read failed for ambiguous phrasings
(e.g. "What's my next simplex message?"), which then looped the retry ladder (e.g. "What's my next simplex message?"), which then looped into repair of a
and offered to repair a working skill. This exercises the real engine, since working skill. This exercises the real engine, since only it produces the
only it produces the probabilities. probabilities.
""" """
config = load_config() config = load_config()
require_real(config) require_real(config)
@@ -758,11 +755,8 @@ def test_read_result_is_assessed_as_success(tmp_path):
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
runner = SkillRunner(ActionContext(engine=engine, config={}), log) runner = SkillRunner(ActionContext(engine=engine, config={}), log)
outcome = runner.run(skill, Request("What's my next simplex message?")) outcome = runner.run(skill, Request("What's my next simplex message?"))
print(f"[{outcome.success}] {outcome.summary}") print(f"[{outcome.outcome}] {outcome.summary}")
assert outcome.success is True, outcome.summary assert outcome.outcome == "done", outcome.summary
phases = [row["extra"]["phase"] for row in log.read()] phases = [row["extra"]["phase"] for row in log.read()]
assert "assess:outcome" in phases assert "assess:outcome" in phases
assert "assess:requeue" not in phases, (
"a truthful read must not be retried or repaired"
)
+3 -2
View File
@@ -107,7 +107,7 @@ def test_act_decisions_logged_on_completion(tmp_path):
skill = Skill(name="t.x", category="t", description="", act=act) skill = Skill(name="t.x", category="t", description="", act=act)
scheduler = build_scheduler( scheduler = build_scheduler(
tmp_path, tmp_path,
choices={"achieve the user's goal": "failure", "complete, or should it run again": "complete"}, choices={"additional work to be done": "failed"},
) )
scheduler._run_skill(skill, Request("x")) scheduler._run_skill(skill, Request("x"))
@@ -119,7 +119,8 @@ def test_act_decisions_logged_on_completion(tmp_path):
assert len(act_rows) == 1 assert len(act_rows) == 1
assert act_rows[0]["extra"]["run_ok"] is False assert act_rows[0]["extra"]["run_ok"] is False
phases = [r.get("extra", {}).get("phase") for r in rows] phases = [r.get("extra", {}).get("phase") for r in rows]
assert "assess:outcome" in phases and "assess:requeue" in phases assert "assess:outcome" in phases
assert "assess:requeue" not in phases
def test_busy_abandons_pending(tmp_path): def test_busy_abandons_pending(tmp_path):
+404 -99
View File
@@ -28,6 +28,7 @@ from semif_agent.scheduler import (
PendingQuestion, PendingQuestion,
RepairOffer, RepairOffer,
Scheduler, Scheduler,
SchedulerReply,
SkillWrite, SkillWrite,
) )
from semif_agent.skills import ( from semif_agent.skills import (
@@ -129,20 +130,23 @@ def _pipeline_codegen_server(replies: list) -> tuple[ThreadingHTTPServer, str]:
return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1" return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/v1"
def _scheduler(tmp_path, codegen=None, choices=None, default="success"): def _scheduler(tmp_path, codegen=None, choices=None, default="success", verbosity=None):
"""A scheduler driven by the deterministic scripted engine (conftest) so """A scheduler driven by the deterministic scripted engine (conftest) so
scheduling/authoring mechanics are testable without a GGUF. Assessment is a scheduling/authoring mechanics are testable without a GGUF. Assessment is a
SemIf decision now, so a run needs the engine to answer `assess:*`.""" SemIf decision now, so a run needs the engine to answer `assess:*`."""
return Scheduler( config = {
engine=ScriptedEngine(choices=choices, default=default),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={
"skills": {}, "skills": {},
"category_registry": str(tmp_path / "categories.json"), "category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"), "skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(tmp_path / "seeds"), "skill_seeds": str(tmp_path / "seeds"),
}, }
if verbosity is not None:
config["verbosity"] = verbosity
return Scheduler(
engine=ScriptedEngine(choices=choices, default=default),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config=config,
trace=TraceLog(str(tmp_path / "runs.jsonl")), trace=TraceLog(str(tmp_path / "runs.jsonl")),
codegen=codegen, codegen=codegen,
) )
@@ -188,8 +192,7 @@ def test_run_summary_is_deterministic_and_surfaces_action_log(tmp_path):
def test_run_summary_failure_uses_new_state_when_no_action_log(tmp_path): def test_run_summary_failure_uses_new_state_when_no_action_log(tmp_path):
"""A failed run with an empty action log falls back to the new state.""" """A failed run with an empty action log falls back to the new state."""
scheduler = _scheduler( scheduler = _scheduler(
tmp_path, choices={"achieve the user's goal": "failure", tmp_path, choices={"additional work to be done": "failed"}
"complete, or should it run again": "complete"}
) )
def act(ctx, request): def act(ctx, request):
@@ -200,6 +203,7 @@ def test_run_summary_failure_uses_new_state_when_no_action_log(tmp_path):
scheduler._run_skill(skill, Request("probe it")) scheduler._run_skill(skill, Request("probe it"))
assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"] assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"]
assert assessed[-1]["success"] is False assert assessed[-1]["success"] is False
assert assessed[-1]["outcome"] == "failed"
assert assessed[-1]["summary"] == "tracking.probe: failed — service unreachable" assert assessed[-1]["summary"] == "tracking.probe: failed — service unreachable"
@@ -615,16 +619,15 @@ def test_canned_response_runs_without_assessment(tmp_path):
def test_assessment_state_carries_skill_action(tmp_path): def test_assessment_state_carries_skill_action(tmp_path):
"""The assessment decision must see what the skill was meant to do. """The assessment decision must see what the skill was meant to do.
Regression: with only `skill: <label>` in the state, the decision model The state carries the skill's declared action, the goal, and the resolved
misfired on a correctly-read result for an ambiguous phrasing, marked a inputs so the decision can judge whether more work is needed toward the
truthful read failed, and looped the retry ladder until a repair offer. The request. One three-way decision (done/continue/failed), no second call.
skill's declared action now rides in both assessment states.
""" """
from semif_agent.skill import SkillRunner from semif_agent.skill import SkillRunner
from semif_agent.skills import ActionContext from semif_agent.skills import ActionContext
engine = ScriptedEngine( engine = ScriptedEngine(
choices={"Did the skill achieve": "failure"}, default="success" choices={"additional work to be done": "done"}
) )
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
@@ -638,52 +641,63 @@ def test_assessment_state_carries_skill_action(tmp_path):
act=act, act=act,
) )
runner = SkillRunner(ActionContext(engine=engine, config={}), log) runner = SkillRunner(ActionContext(engine=engine, config={}), log)
runner.run(skill, Request("What's my next simplex message?")) outcome = runner.run(skill, Request("What's my next simplex message?"))
outcome_state = engine.calls[0].state assert len(engine.calls) == 1
assert "skill action: Read the next unread SimpleX message." in outcome_state state = engine.calls[0].state
assert "goal: What's my next simplex message?" in outcome_state assert "skill action: Read the next unread SimpleX message." in state
requeue_state = engine.calls[1].state assert "goal: What's my next simplex message?" in state
assert "skill action: Read the next unread SimpleX message." in requeue_state assert outcome.outcome == "done"
def test_requeue_state_flags_identical_repeat(tmp_path): def test_assessment_three_way_verdict(tmp_path):
"""A retry that would reproduce the identical result is flagged as a no-op """The one `assess:outcome` decision yields done / continue / failed by
so the requeue decision can choose `complete` instead of looping.""" threshold precedence (failed > done > continue)."""
from semif_agent.skill import SkillRunner from semif_agent.skill import SkillRunner
from semif_agent.skills import ActionContext from semif_agent.skills import ActionContext
engine = ScriptedEngine( skill = Skill(
choices={"Did the skill achieve": "failure"}, default="success" name="next_message",
category="simplex",
description="Read the next unread SimpleX message.",
act=lambda ctx, request: ActionResult(action_log="did it", new_state="x"),
) )
def verdict_for(selected):
engine = ScriptedEngine(choices={"additional work to be done": selected})
log = DecisionLog(str(tmp_path / f"{selected}.jsonl"))
runner = SkillRunner(ActionContext(engine=engine, config={}), log)
return runner.run(skill, Request("go")).outcome
assert verdict_for("done") == "done"
assert verdict_for("continue") == "continue"
assert verdict_for("failed") == "failed"
def test_assessment_state_includes_run_ledger(tmp_path):
"""A continuation's assessment sees the steps already taken, so it can tell
whether the request is satisfied or more work is needed."""
from semif_agent.skill import SkillRunner
from semif_agent.skills import ActionContext
engine = ScriptedEngine(choices={"additional work to be done": "done"})
log = DecisionLog(str(tmp_path / "decisions.jsonl")) log = DecisionLog(str(tmp_path / "decisions.jsonl"))
skill = Skill( skill = Skill(
name="next_message", name="next_message",
category="simplex", category="simplex",
description="Read the next unread SimpleX message.", description="Read the next unread SimpleX message.",
act=lambda ctx, request: ActionResult( act=lambda ctx, request: ActionResult(action_log="second step", new_state="read"),
action_log="SimpleX message from pepper: hello", new_state="read"
),
) )
runner = SkillRunner(ActionContext(engine=engine, config={}), log) runner = SkillRunner(ActionContext(engine=engine, config={}), log)
request = Request("do the thing")
request.run_ledger = [
{"query": "do the thing", "skill": "simplex.other", "outcome": "already ran"}
]
runner.run(skill, request)
# First attempt: no prior result, so no no-progress note. state = engine.calls[0].state
runner.run(skill, Request("What's my next simplex message?")) assert "steps already taken:" in state
assert "identical result" not in engine.calls[1].state assert "simplex.other -> already ran" in state
# Same observed result as the previous attempt: flagged as a no-op retry.
engine.calls.clear()
repeat = Request("What's my next simplex message?")
repeat.meta["prev_result"] = "SimpleX message from pepper: hello"
runner.run(skill, repeat)
assert "identical result" in engine.calls[1].state
# A changed result is progress: not flagged.
engine.calls.clear()
progress = Request("What's my next simplex message?")
progress.meta["prev_result"] = "a different previous result"
runner.run(skill, progress)
assert "identical result" not in engine.calls[1].state
@@ -778,9 +792,9 @@ def test_navigate_leaf_returns_best_existing_skill(tmp_path):
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 1.0}, "logical next step": {"simplex": 1.0},
"Does the scope": {"covers": 1.0}, "Does the scope": {"covers": 1.0},
"skill performs": {"next_message": 0.45, "connect_link": 0.55}, "skill should run next": {"next_message": 0.45, "connect_link": 0.55},
} }
) )
result = navigate( result = navigate(
@@ -796,7 +810,7 @@ def test_navigate_single_skill_category_skips_the_softmax(tmp_path):
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}, "Does the scope": {"covers": 1.0}} {"logical next step": {"simplex": 1.0}, "Does the scope": {"covers": 1.0}}
) )
tree = { tree = {
"simplex": [ "simplex": [
@@ -812,7 +826,7 @@ def test_navigate_single_skill_category_skips_the_softmax(tmp_path):
def test_navigate_empty_category_short_circuits_to_create(tmp_path): def test_navigate_empty_category_short_circuits_to_create(tmp_path):
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({"top-level category": {"simplex": 1.0}}) engine = _ProbEngine({"logical next step": {"simplex": 1.0}})
result = navigate(engine, log, trace, Request("anything"), {"simplex": []}) result = navigate(engine, log, trace, Request("anything"), {"simplex": []})
assert isinstance(result, CreateSkill) assert isinstance(result, CreateSkill)
assert result.category == "simplex" assert result.category == "simplex"
@@ -822,7 +836,7 @@ def test_navigate_empty_category_short_circuits_to_create(tmp_path):
def test_navigate_category_options_carry_descriptions(tmp_path): def test_navigate_category_options_carry_descriptions(tmp_path):
"""The category softmax must offer each category WITH its description — bare """The category softmax must offer each category WITH its description — bare
names carry no signal (the misroute bug).""" names carry no signal (the misroute bug)."""
engine = _ProbEngine({"top-level category": {"simplex": 1.0}}) engine = _ProbEngine({"logical next step": {"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 = { tree = {
@@ -836,7 +850,7 @@ def test_navigate_category_options_carry_descriptions(tmp_path):
] ]
} }
navigate(engine, log, trace, Request("read the next message"), tree) 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) cat_decision = next(c for c in engine.calls if "logical next step" in c.question)
by_id = {o.id: o.description for o in cat_decision.options} by_id = {o.id: o.description for o in cat_decision.options}
assert by_id["simplex"] == "SimpleX messaging: read/send messages." assert by_id["simplex"] == "SimpleX messaging: read/send messages."
assert "new top-level category is needed" in by_id["create_category"] assert "new top-level category is needed" in by_id["create_category"]
@@ -851,7 +865,7 @@ def test_navigate_category_rejected_scope_authors_category(tmp_path):
tree = _leaf_tree() tree = _leaf_tree()
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 0.45}, "logical next step": {"simplex": 0.45},
"Does the scope": {"none": 1.0}, "Does the scope": {"none": 1.0},
} }
) )
@@ -867,9 +881,9 @@ def test_navigate_category_confirmed_scope_descends(tmp_path):
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 0.45}, "logical next step": {"simplex": 0.45},
"Does the scope": {"covers": 1.0}, "Does the scope": {"covers": 1.0},
"skill performs": {"next_message": 1.0, "connect_link": 0.0}, "skill should run next": {"next_message": 1.0, "connect_link": 0.0},
} }
) )
result = navigate(engine, log, trace, Request("read a message"), _leaf_tree()) result = navigate(engine, log, trace, Request("read a message"), _leaf_tree())
@@ -885,8 +899,8 @@ def test_navigate_confident_category_winner_skips_scope_confirm(tmp_path):
trace = TraceLog(str(tmp_path / "runs.jsonl")) trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 0.9}, "logical next step": {"simplex": 0.9},
"skill performs": {"next_message": 1.0, "connect_link": 0.0}, "skill should run next": {"next_message": 1.0, "connect_link": 0.0},
} }
) )
result = navigate(engine, log, trace, Request("read a message"), _leaf_tree()) result = navigate(engine, log, trace, Request("read a message"), _leaf_tree())
@@ -948,7 +962,7 @@ def test_navigate_actionability_sends_a_request_to_create(tmp_path):
tree = build_tree(build_skills({"skills": {}})) tree = build_tree(build_skills({"skills": {}}))
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"response": 1.0}, "logical next step": {"response": 1.0},
"non-request input": {"action": 1.0}, "non-request input": {"action": 1.0},
} }
) )
@@ -968,7 +982,7 @@ def test_navigate_actionability_keeps_a_statement_in_response(tmp_path):
tree = build_tree(build_skills({"skills": {}})) tree = build_tree(build_skills({"skills": {}}))
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"create_category": 1.0}, "logical next step": {"create_category": 1.0},
"non-request input": {"non_action": 1.0}, "non-request input": {"non_action": 1.0},
} }
) )
@@ -998,14 +1012,14 @@ def test_navigate_actionability_gate_precedes_category_selection(tmp_path):
{ {
"non-request input": {"non_action": 1.0}, "non-request input": {"non_action": 1.0},
# If the category softmax ran it would route to simplex, not response. # If the category softmax ran it would route to simplex, not response.
"top-level category": {"simplex": 1.0}, "logical next step": {"simplex": 1.0},
"canned response": {"response.greeting": 1.0}, "canned response": {"response.greeting": 1.0},
} }
) )
result = navigate(engine, log, trace, Request("the sky is blue"), tree) result = navigate(engine, log, trace, Request("the sky is blue"), tree)
assert getattr(result, "category", None) == "response" assert getattr(result, "category", None) == "response"
assert all( assert all(
"top-level category" not in c.question for c in engine.calls "logical next step" not in c.question for c in engine.calls
), "the category softmax must not run for non-request input" ), "the category softmax must not run for non-request input"
phases = [r["extra"]["phase"] for r in log.read()] phases = [r["extra"]["phase"] for r in log.read()]
assert "navigate:actionability" in phases assert "navigate:actionability" in phases
@@ -1029,13 +1043,13 @@ def test_navigate_category_softmax_excludes_the_canned_response_tree(tmp_path):
] ]
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 1.0}, "logical next step": {"simplex": 1.0},
"Does the scope": {"covers": 1.0}, "Does the scope": {"covers": 1.0},
} }
) )
navigate(engine, log, trace, Request("read the next simplex message"), tree) navigate(engine, log, trace, Request("read the next simplex message"), tree)
cat_decision = next( cat_decision = next(
c for c in engine.calls if "top-level category" in c.question c for c in engine.calls if "logical next step" in c.question
) )
ids = [o.id for o in cat_decision.options] ids = [o.id for o in cat_decision.options]
assert "response" not in ids assert "response" not in ids
@@ -1051,7 +1065,7 @@ def test_dispatch_action_tau_controls_catchall_routing(tmp_path):
scheduler = Scheduler( scheduler = Scheduler(
engine=_ProbEngine( engine=_ProbEngine(
{ {
"top-level category": {"response": 1.0}, "logical next step": {"response": 1.0},
"non-request input": {"non_action": 0.6, "action": 0.4}, "non-request input": {"non_action": 0.6, "action": 0.4},
} }
), ),
@@ -1089,12 +1103,12 @@ def test_dispatch_intent_tau_controls_reuse_vs_create(tmp_path):
def build(intent_tau: float): def build(intent_tau: float):
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 1.0}, "logical next step": {"simplex": 1.0},
"Does the scope": {"covers": 1.0}, "Does the scope": {"covers": 1.0},
# The leaf softmax offers only existing skills, so the intent # The leaf softmax offers only existing skills, so the intent
# guard always runs (it is the create door). # guard always runs (it is the create door).
"skill performs": {"next_message": 0.45, "connect_link": 0.3}, "skill should run next": {"next_message": 0.45, "connect_link": 0.3},
"same action": {"same": 0.8, "different": 0.2}, "what does this skill do": {"same": 0.8, "different": 0.2},
} }
) )
scheduler = Scheduler( scheduler = Scheduler(
@@ -1138,32 +1152,48 @@ def test_dispatch_intent_tau_controls_reuse_vs_create(tmp_path):
assert queued_high == [("simplex", "skill")] assert queued_high == [("simplex", "skill")]
def test_confirm_skill_fit_returns_true_when_action_matches(tmp_path): def test_confirm_skill_fit_returns_same_when_action_matches(tmp_path):
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 = ScriptedEngine(choices={"same action": "same"}) engine = ScriptedEngine(choices={"what does this skill do": "same"})
skill = Skill(name="next_message", category="simplex", description="Read the next SimpleX message.") skill = Skill(name="next_message", category="simplex", description="Read the next SimpleX message.")
assert confirm_skill_fit(engine, log, trace, Request("read the next simplex message"), skill) is True assert confirm_skill_fit(engine, log, trace, Request("read the next simplex message"), skill) == "same"
row = log.read()[-1] row = log.read()[-1]
assert row["extra"]["phase"] == "navigate:intent" assert row["extra"]["phase"] == "navigate:intent"
assert row["selected"] == "same" assert row["selected"] == "same"
def test_confirm_skill_fit_returns_false_on_mismatch(tmp_path): def test_confirm_skill_fit_returns_different_on_mismatch(tmp_path):
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 = ScriptedEngine(choices={"same action": "different"}) engine = ScriptedEngine(choices={"what does this skill do": "different"})
skill = Skill(name="next_message", category="simplex", description="Read the next SimpleX message.") skill = Skill(name="next_message", category="simplex", description="Read the next SimpleX message.")
assert confirm_skill_fit(engine, log, trace, Request("send a simplex message"), skill) is False assert confirm_skill_fit(engine, log, trace, Request("send a simplex message"), skill) == "different"
assert any(e["kind"] == "intent_guard" and e["fits"] is False for e in trace.read()) assert any(e["kind"] == "intent_guard" and e["fits"] is False for e in trace.read())
def test_confirm_skill_fit_returns_part_for_a_compound_request(tmp_path):
"""A skill that performs one required part of a compound request is accepted
as `part` (not rejected into create), and the ledger is in the state."""
log = DecisionLog(str(tmp_path / "decisions.jsonl"))
trace = TraceLog(str(tmp_path / "runs.jsonl"))
engine = ScriptedEngine(choices={"what does this skill do": "part"})
skill = Skill(name="calculate", category="calculator", description="Do arithmetic.")
request = Request("send the result of 22 * 10 to pepper on simplex")
request.run_ledger = [
{"query": "x", "skill": "calculator.calculate", "outcome": "done"}
]
assert confirm_skill_fit(engine, log, trace, request, skill) == "part"
guard = next(e for e in trace.read() if e["kind"] == "intent_guard")
assert guard["verdict"] == "part" and guard["fits"] is True
def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path): def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
"""A routed skill whose action doesn't match the request must not run: the """A routed skill whose action doesn't match the request must not run: the
guard sends dispatch to create_skill in the same category instead.""" guard sends dispatch to create_skill in the same category instead."""
scheduler = _scheduler( scheduler = _scheduler(
tmp_path, tmp_path,
choices={"top-level category": "simplex", "same action": "different"}, choices={"logical next step": "simplex", "what does this skill do": "different"},
) )
scheduler.tree.pop("response", None) scheduler.tree.pop("response", None)
scheduler.tree["simplex"] = [ scheduler.tree["simplex"] = [
@@ -1183,7 +1213,7 @@ def test_dispatch_intent_mismatch_authorizes_new_skill(tmp_path):
def test_dispatch_intent_match_runs_skill(tmp_path): def test_dispatch_intent_match_runs_skill(tmp_path):
scheduler = _scheduler( scheduler = _scheduler(
tmp_path, choices={"top-level category": "simplex", "same action": "same"} tmp_path, choices={"logical next step": "simplex", "what does this skill do": "same"}
) )
def act(ctx, request): def act(ctx, request):
@@ -1215,9 +1245,9 @@ def test_dispatch_confident_leaf_winner_still_runs_intent_guard(tmp_path):
and codegen was never reached.""" and codegen was never reached."""
engine = _ProbEngine( engine = _ProbEngine(
{ {
"top-level category": {"simplex": 1.0}, "logical next step": {"simplex": 1.0},
"skill performs": {"next_message": 0.9, "connect_link": 0.1}, "skill should run next": {"next_message": 0.9, "connect_link": 0.1},
"same action": {"different": 1.0}, "what does this skill do": {"different": 1.0},
} }
) )
scheduler = Scheduler( scheduler = Scheduler(
@@ -2113,15 +2143,15 @@ def test_resolve_repair_unknown_offer_errors(tmp_path):
assert "no repair offer" in detail assert "no repair offer" in detail
def test_exhausted_reentry_offers_repair(tmp_path): def test_failed_run_offers_repair(tmp_path):
"""A failure whose retry is refused because the reentry budget is spent must """A `failed` outcome offers a repair, regardless of the reentry budget: it
still surface a repair offer. Before, `updated_request` stayed truthy so the is a broken step, not a "more work" step."""
offer was skipped and the failure vanished after the retry ladder."""
scheduler = _scheduler(tmp_path) scheduler = _scheduler(tmp_path)
_install_tracking_stub(scheduler) skill = Skill(
skill = scheduler.tree["tracking"][0] name="check",
skill.act = lambda ctx, request: ActionResult( category="tracking",
action_log="connection refused", new_state="unchanged" description="Check the delivery status of a package.",
act=lambda ctx, request: ActionResult(action_log="boom", new_state="x"),
) )
request = Request("track my package") request = Request("track my package")
request.reentries = scheduler.max_reentries request.reentries = scheduler.max_reentries
@@ -2131,30 +2161,305 @@ def test_exhausted_reentry_offers_repair(tmp_path):
summary="failed", summary="failed",
action_log="connection refused", action_log="connection refused",
new_state="unchanged", new_state="unchanged",
updated_request="track my package", outcome="failed",
) )
scheduler._finish_run(skill, request, outcome) scheduler._finish_run(skill, request, outcome)
assert not any(e["kind"] == "requeued" for e in scheduler.trace.read()) assert not any(e["kind"] == "continued" for e in scheduler.trace.read())
assert any(e["kind"] == "repair_offered" for e in scheduler.trace.read()) assert any(e["kind"] == "repair_offered" for e in scheduler.trace.read())
def test_requeue_remembers_previous_result(tmp_path): def test_continue_routes_next_step_carries_ledger(tmp_path):
"""A requeued retry carries the observed result forward so the next """A `continue` outcome re-dispatches the request with a run-ledger entry and
assessment can detect a guaranteed no-op repeat.""" a parent-run link; the next step's ledger leads back to the original query."""
scheduler = _scheduler(tmp_path) scheduler = _scheduler(tmp_path)
_install_tracking_stub(scheduler) skill = Skill(
skill = scheduler.tree["tracking"][0] name="check",
category="tracking",
description="Check the delivery status of a package.",
act=lambda ctx, request: ActionResult(action_log="boom", new_state="x"),
)
request = Request("track my package") request = Request("track my package")
outcome = RunResult( outcome = RunResult(
skill="tracking.check", skill="tracking.check",
success=False, success=True,
summary="failed", summary="ok",
action_log="connection refused", action_log="tracking opened",
new_state="unchanged", new_state="opened",
updated_request="track my package", outcome="continue",
) )
scheduler._finish_run(skill, request, outcome) scheduler._finish_run(skill, request, outcome)
child = scheduler.queue.pop() child = scheduler.queue.pop()
assert child is not None assert child is not None
assert child.meta["prev_result"] == "connection refused" assert child.source == "continue"
assert any(e["kind"] == "requeued" for e in scheduler.trace.read()) assert child.text == "track my package"
assert child.meta["parent_run"] == request.id
assert child.run_ledger == [
{"query": "track my package", "skill": "tracking.check", "outcome": "tracking opened"}
]
assert any(e["kind"] == "continued" for e in scheduler.trace.read())
def test_capped_continue_halts_chain_not_repair(tmp_path):
"""A `continue` with the step budget spent stops the chain (it worked, so no
repair offer) rather than looping."""
scheduler = _scheduler(tmp_path)
skill = Skill(
name="check",
category="tracking",
description="Check the delivery status of a package.",
act=lambda ctx, request: ActionResult(action_log="boom", new_state="x"),
)
request = Request("track my package")
request.reentries = scheduler.max_reentries
outcome = RunResult(
skill="tracking.check",
success=True,
summary="ok",
action_log="not done yet",
new_state="partial",
outcome="continue",
)
scheduler._finish_run(skill, request, outcome)
assert scheduler.queue.pop() is None
assert not any(e["kind"] == "repair_offered" for e in scheduler.trace.read())
halted = [e for e in scheduler.trace.read() if e["kind"] == "chain_halted"]
assert halted and halted[-1]["reason"] == "budget"
def test_repeat_continue_halts_chain(tmp_path):
"""The monotonic guard: a `continue` whose (skill, outcome) already appears in
the ledger makes no progress, so the chain stops."""
scheduler = _scheduler(tmp_path)
skill = Skill(
name="check",
category="tracking",
description="Check the delivery status of a package.",
act=lambda ctx, request: ActionResult(action_log="boom", new_state="x"),
)
request = Request("track my package")
request.run_ledger = [
{"query": "track my package", "skill": "tracking.check", "outcome": "unchanged"}
]
outcome = RunResult(
skill="tracking.check",
success=True,
summary="ok",
action_log="unchanged",
new_state="unchanged",
outcome="continue",
)
scheduler._finish_run(skill, request, outcome)
assert scheduler.queue.pop() is None
halted = [e for e in scheduler.trace.read() if e["kind"] == "chain_halted"]
assert halted and halted[-1]["reason"] == "repeat"
def test_chain_continues_then_completes(tmp_path):
"""End-to-end: a `continue` step is re-dispatched into next-step routing with
the ledger attached, and the chain ends when the second step reports `done`.
The first (intermediate) reply is marked so a `result` front end hides it."""
from semif_agent.decisions import DecisionResult
class ChainEngine:
"""Deterministic two-step chain: step 1 -> continue, step 2 -> done."""
def __init__(self):
self.assessments = iter(["continue", "done"])
def call(self, request):
ids = [o.id for o in request.options]
q = request.question
if "additional work to be done" in q:
selected = next(self.assessments, "done")
elif "logical next step" in q:
selected = "demo"
elif "what does this skill do" in q:
selected = "same"
elif "Is this input a request" in q:
selected = "action"
else:
selected = ids[0]
if selected not in ids:
selected = ids[0]
return DecisionResult(
request=request,
option_ids=ids,
probabilities=[1.0 if i == selected else 0.0 for i in ids],
)
counter = {"n": 0}
def act(ctx, request):
counter["n"] += 1
return ActionResult(action_log=f"step {counter['n']} done", new_state="x")
from semif_agent.llm import LLMClient
scheduler = Scheduler(
engine=ChainEngine(),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={
"skills": {},
"category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(tmp_path / "seeds"),
},
trace=TraceLog(str(tmp_path / "runs.jsonl")),
)
scheduler.tree["demo"] = [
Skill(name="step", category="demo", description="Do a demo step.", act=act)
]
first = scheduler.submit_request("do the thing")
assert first.intermediate is True
replies = scheduler.run_queue()
assert len(replies) == 1
assert replies[0].intermediate is False
assert "step 2 done" in replies[0].text
events = scheduler.trace.read()
assert any(e["kind"] == "continued" for e in events)
# The re-dispatched step carried the ledger and the parent link.
child = next(
e for e in events if e["kind"] == "continued"
)
assert child["step"] == 1
def test_compound_request_runs_part_step_then_chains(tmp_path):
"""End-to-end compound request: the leaf guard accepts the first skill as
`part` (not a create), the step runs, assessment says more work remains so
the chain continues, and the next step completes the request with the prior
result in its ledger. The guard does NOT force continuation — `assess:outcome`
is the authority, so a `part` step whose work is actually done stops cleanly."""
from semif_agent.decisions import DecisionResult
from semif_agent.llm import LLMClient
class CompoundEngine:
def __init__(self):
# Assessment is the continuation authority: step 1 has more work,
# step 2 (calculation already done) finishes the request.
self.assessments = iter(["continue", "done"])
def call(self, request):
ids = [o.id for o in request.options]
q = request.question
# The run ledger is rendered as a "steps already taken:" block only
# once a step has run, so it is the discriminator between step 1 and
# step 2 for the routing decisions.
after = "steps already taken" in request.state
if "Is this input a request" in q:
selected = "action"
elif "logical next step" in q:
selected = "simplex" if after else "calculator"
elif "what does this skill do" in q:
selected = "same" if after else "part"
elif "additional work to be done" in q:
selected = next(self.assessments, "done")
else:
selected = ids[0]
if selected not in ids:
selected = ids[0]
return DecisionResult(
request=request,
option_ids=ids,
probabilities=[1.0 if i == selected else 0.0 for i in ids],
)
ran = []
def calc_act(ctx, request):
ran.append("calculate")
return ActionResult(
action_log="Twenty-two times ten is two hundred twenty.",
new_state="220",
)
def send_act(ctx, request):
ran.append(("send", request.run_ledger[-1]["outcome"]))
return ActionResult(action_log="sent to pepper", new_state="sent")
scheduler = Scheduler(
engine=CompoundEngine(),
llm=LLMClient(base_url="http://localhost:1/v1", model="test"),
log=DecisionLog(str(tmp_path / "decisions.jsonl")),
config={
"skills": {},
"category_registry": str(tmp_path / "categories.json"),
"skill_bodies": str(tmp_path / "skills"),
"skill_seeds": str(tmp_path / "seeds"),
},
trace=TraceLog(str(tmp_path / "runs.jsonl")),
)
scheduler.tree = {
"calculator": [
Skill(
name="calculate",
category="calculator",
description="Do arithmetic.",
act=calc_act,
)
],
"simplex": [
Skill(
name="send_message",
category="simplex",
description="Send a SimpleX message.",
act=send_act,
)
],
}
first = scheduler.submit_request("send the result of 22 * 10 to pepper on simplex")
assert first.intermediate is True
assert ran == ["calculate"], ran
replies = scheduler.run_queue()
assert len(replies) == 1
assert replies[0].intermediate is False
# The second step saw the first step's result in its ledger.
assert ran[-1] == ("send", "Twenty-two times ten is two hundred twenty."), ran
events = scheduler.trace.read()
assert any(e["kind"] == "continued" for e in events)
guards = [e for e in events if e["kind"] == "intent_guard"]
assert [g["verdict"] for g in guards] == ["part", "same"], guards
def test_verbosity_defaults_and_decision_lines(tmp_path):
"""Verbosity defaults to `result`; `decision` attaches the SemIf decision
phases (and only then)."""
from semif_agent.scheduler import normalize_verbosity
assert normalize_verbosity(None) == "result"
assert normalize_verbosity("query") == "query"
assert normalize_verbosity("bogus") == "result"
sched = _scheduler(tmp_path, verbosity="decision")
assert sched.verbosity == "decision"
skill = Skill(
name="probe",
category="tracking",
description="Probe.",
act=lambda ctx, request: ActionResult(action_log="ok", new_state="x"),
)
request = Request("probe it")
sched._run_skill(skill, request)
lines = sched._decision_lines(request.id)
assert any(line.startswith("assess:outcome") for line in lines)
quiet = _scheduler(tmp_path)
assert quiet.verbosity == "result"
assert quiet._decision_lines(request.id) == []
def test_result_verbosity_hides_intermediate_reply(capsys):
from semif_agent.cli import _print_reply
reply = SchedulerReply("ran", "demo.step: ok — step 1", intermediate=True)
_print_reply(reply, verbosity="result")
assert capsys.readouterr().out == ""
_print_reply(reply, verbosity="query")
assert "step 1" in capsys.readouterr().out