From ab0defca1e8f5abdbb9b70164c3616bca5b140c5 Mon Sep 17 00:00:00 2001 From: Gabby Morgan Date: Sat, 10 Oct 2026 07:25:17 +0000 Subject: [PATCH] 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. --- AGENTS.md | 56 ++- CODEGEN.md | 45 +- README.md | 31 +- TESTGEN.md | 6 + config.example.json | 13 +- docs/flow.md | 24 +- scripts/tune_navigation.py | 12 +- seeds/simplex/send_message/skill.py | 7 +- seeds/simplex/send_message/skill.test.py | 47 ++- semif_agent/cli.py | 23 +- semif_agent/decisions.py | 8 + semif_agent/gateway/service.py | 31 +- semif_agent/scheduler.py | 186 ++++++++- semif_agent/skill.py | 180 ++++---- semif_agent/skills.py | 153 +++++-- semif_agent/static/app.js | 14 +- semif_agent/trace.py | 2 +- tests/integration/test_pipeline.py | 24 +- tests/test_input_channel.py | 5 +- tests/test_skills.py | 503 ++++++++++++++++++----- 20 files changed, 1046 insertions(+), 324 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fdc7421..fab0b01 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,8 +87,10 @@ scheduler.py no up-front gate: every input is dispatched cascade; elicitation asks implementation questions one at a time (all front ends defer via the question queue, `answer_timeout` per question); a - failed real run triggers a logged SemIf repair choice - (retry/repair_skill/ask_user/no_repair) surfaced to the user; + `failed` step triggers a logged SemIf repair choice + (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) 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 @@ -100,9 +102,14 @@ scheduler.py no up-front gate: every input is dispatched queue.py bounded FIFO request queue (arrival order, max depth) skills.py tree + registry (hardcoded built-ins: the closed `response` canned tree plus the `housekeeping` meta skills), navigation = SemIf - choices per level (logged; - the actionability guard runs first, at the top of navigation, - to arbitrate the response/create boundary), create_category + choices per level (logged; the question is "which category/skill + is the logical next step toward satisfying this request?" for the + 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` provider (separate from codegen); SkillStore persists one folder per skill (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 SemIf sub-decisions ride on ActionResult.decisions and are logged with the run outcome, phase `act`); - assess is a SemIf decision (`assess:outcome` success/failure at - tau; on failure `assess:requeue` complete/retry) and the run - summary is deterministic (no generation), built from + assess is a SemIf decision (`assess:outcome`: is there any + additional work to satisfy the request? -> done / continue / + 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 - result, the runner adds the `category.name:` ref; the assess state carries - the skill's declared action, the goal, and the resolved inputs - (secrets redacted), and the requeue state flags a retry that would - reproduce the identical observed result as a no-op; a `DETERMINISTIC_CATEGORIES` + result, the runner adds the `category.name:` ref; the assess state + carries the skill's declared action, the goal, the resolved inputs + (secrets redacted), the bounded action log, and the steps already + 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 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 answer on request.user_input; a 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` 0.585–0.803 on requests a seed skill clearly matched). The reuse-vs-create decision is the **intent guard** (`confirm_skill_fit`, phase - `navigate:intent`) at `navigation.intent_tau`. 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 `navigation.action_tau` (default 0.5) runs at the **top** of navigation, 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 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. -- **Resolved-input observation.** The `assess:outcome` / `assess:requeue` state - includes the resolved contract values (`resolved inputs:` block) so the - decision sees the full query → resolution → action path; secret-named +- **Resolved-input observation.** The `assess:outcome` state includes the + resolved contract values (`resolved inputs:` block), the bounded action log, and + 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 credentials never reach the decision log. - **Requirements elicitation (implementation questions, default on).** diff --git a/CODEGEN.md b/CODEGEN.md index 4b505ab..6abca60 100644 --- a/CODEGEN.md +++ b/CODEGEN.md @@ -137,9 +137,10 @@ engine/runtime concerns, not body-level tools: a body makes direct typed decisions and lets the runner own the model. 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 -goal, and the resolved inputs. The body does not self-assess; it reports -truthfully and lets SemIf judge. +(`assess:outcome`: is there any additional work to be done to satisfy the +request? → done / continue / failed) is itself a SemIf decision over the body's +`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 @@ -451,14 +452,44 @@ Rules: the result is a broken output. - **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 - **successful** run: the `assess:outcome` step treats a definitive "nothing - found / nothing to do" result as success. Phrase it as the answer the user - asked for ("checked the inbox: no unread messages"), not as an absence or an - error, so the assessment does not read a healthy empty result as a failure. + **`done`** run: the `assess:outcome` step treats a definitive "nothing found / + nothing to do" result as done. Phrase it as the answer the user asked for + ("checked the inbox: no unread messages"), not as an absence or an error, so + 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 real failure in `action_log` and set `new_state` back to `request.text` (see 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) - **Perform the real action.** If the skill's purpose involves an external diff --git a/README.md b/README.md index 2c48d2c..5324206 100644 --- a/README.md +++ b/README.md @@ -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 option diluted its probability and let a crowded tree drift into create on a weak plurality). The picked skill then goes through the **intent guard** - (`confirm_skill_fit`, phase `navigate:intent`): an action comparison at - `navigation.intent_tau` asking whether the skill performs the same action the - request asks for. Same → run it; different → author a new leaf in that - category. An empty (or single-skill) category skips the softmax and goes - straight to the guard. + (`confirm_skill_fit`, phase `navigate:intent`): at `navigation.intent_tau` it + decides what the skill does for the request, given the steps already taken + (the run ledger is part of its state). `same` (it performs the next action the + request needs) or `part` (the request needs more than one action and this + 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 cases score 0.9–1.0, so a borderline over-cover routes into a plausible 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 training rows with the run outcome. - `assess` is a **SemIf decision**, not generation: - - `assess:outcome` — success/failure at `tau`; its state includes the resolved - inputs (secrets redacted) so a wrong resolution is visible. - - `assess:requeue` — on failure, `complete` vs `retry` (bounded by - `max_reentries`). + - `assess:outcome` — is there any *additional work* to satisfy the request? + Three outcomes at threshold precedence `failed > done > continue`: `done` + (request satisfied), `continue` (this step worked but more work is needed → + 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): `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 re-runs on resume, with `request.user_input` set), or — for a contract 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:response` | `skills.py:634` | request text + category | canned reply names + descriptions (catchall last) | | `navigate:intent` | `skills.py:811` | `Requested action: ` + `Action of the existing skill: ` | `same` / `different` | -| `assess:outcome` | `skill.py:257` | skill label + goal + action log | `success` / `failure` | -| `assess:requeue` | `skill.py:279` | skill label + goal + action log + `outcome: failed` | `complete` / `retry` | +| `assess:outcome` | `skill.py:311` | skill label + goal + resolved inputs + bounded action log + steps already taken | `done` / `continue` / `failed` | | `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` | | `authoring:fidelity` | `scheduler.py:1311` | skill, request, description, `INTEGRATION` JSON, static findings, first 4000 chars of body | `accept` / `reconsider` | diff --git a/TESTGEN.md b/TESTGEN.md index 95db1d2..244e1d1 100644 --- a/TESTGEN.md +++ b/TESTGEN.md @@ -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 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 A **single JSON object**. Each key is the name of a variable the skill needs; diff --git a/config.example.json b/config.example.json index e352c64..bb69284 100644 --- a/config.example.json +++ b/config.example.json @@ -4,9 +4,20 @@ "max_reentries": 3, "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//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": "", "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, "category_tau": 0.75, "action_tau": 0.5, diff --git a/docs/flow.md b/docs/flow.md index a968c96..223e2c8 100644 --- a/docs/flow.md +++ b/docs/flow.md @@ -64,8 +64,8 @@ flowchart TD %% ---------- reuse vs create ---------- PICK --> HARD{"hard-locked category?
(housekeeping)"} HARD -- "yes" --> RUN - HARD -- "no" --> INTENT["SemIf choice
phase 'navigate:intent'
P same >= intent_tau?"] - INTENT -- "same" --> RUN + HARD -- "no" --> INTENT["SemIf choice
phase 'navigate:intent'
same / part / different?
P same+part >= intent_tau"] + INTENT -- "same / part" --> RUN INTENT -- "different" --> CREATESKILL CREATESKILL --> LOCK{"category locked to
new skills?"} @@ -94,12 +94,11 @@ flowchart TD ACTNI -- "no" --> ASSESS %% ---------- assessment ---------- - ASSESS["SemIf choice
phase 'assess:outcome'
P success >= tau?
a definitive empty result counts as success"] --> OK{"success?"} - OK -- "yes" --> SUMMARY - OK -- "no" --> REQ["SemIf choice
phase 'assess:requeue'
complete vs retry"] - REQ -- "retry" --> REQUEUE["requeue original request
bounded by max_reentries"] - REQUEUE -.-> PUSH - REQ -- "complete" --> REPAIR + ASSESS["SemIf choice
phase 'assess:outcome'
additional work to do?
a definitive empty result counts as done"] --> OK{"outcome?"} + OK -- "done" --> SUMMARY + OK -- "continue" --> CHAIN["route the logical next step
re-dispatch with the run ledger
bounded by max_reentries + monotonic guard"] + CHAIN -.-> PUSH + OK -- "failed" --> REPAIR SUMMARY["deterministic summary
category.name: ok/failed - action_log"] --> OUT1["Output: ran
SchedulerReply (run_id, skill_ref, result)
REPL · gateway reply · dashboard trace"] @@ -112,8 +111,8 @@ flowchart TD classDef semfill fill:#e8f0fe,stroke:#4285f4,stroke-width:2px; classDef output fill:#fce8e6,stroke:#d93025; classDef author fill:#e6f4ea,stroke:#34a853; - class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REQ,REPAIR,RECORD semfill; - class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT output; + class CAT,CATFIT,ACTG,LEAF,INTENT,ASSESS,REPAIR,RECORD semfill; + class REJECT,QUEUED,PENDING,NOOP,PENDINGW,BLOCKED,PAUSE1,PAUSE2,OUT1,REPAIROUT,CHAIN output; class CREATECAT,CREATESKILL,AUTHORING author; ``` @@ -196,10 +195,9 @@ flowchart TD | Category scope | does it cover? | `navigate:category_scope` | descend / create (skipped when decisive) | | Canned | which reply | `navigate:response` | canned line | | 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 | -| Outcome | did it succeed? | `assess:outcome` | ok / failed | -| Requeue | complete or retry? | `assess:requeue` | done / requeue | +| Outcome | additional work? | `assess:outcome` | done / continue / failed | | Repair | how to recover? | `repair:choice` | offer | | Fidelity | real action? | `authoring:fidelity` | accept / rewrite | | Config search | where is the value? | `config:search` | auto-populate | diff --git a/scripts/tune_navigation.py b/scripts/tune_navigation.py index eb4bfe5..4e3e2fe 100644 --- a/scripts/tune_navigation.py +++ b/scripts/tune_navigation.py @@ -12,8 +12,11 @@ probability. description plus `create_category`; `confirm_category_fit` confirms the winner's scope. `navigation.category_tau` is that guard's P(covers) floor. - **Leaf**: the softmax offers only existing skills; `confirm_skill_fit` - compares the winner's action to the request. `navigation.intent_tau` is that - guard's P(same) floor. + decides what the winner does for the request (`same` / `part` / `different`). + `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 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) events = trace.read()[before:] guard = next((e for e in events if e["kind"] == "intent_guard"), None) - return {"picked": f"{nav.category}.{nav.name}", "p": guard["probs"]["same"] if guard else None} + # 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: diff --git a/seeds/simplex/send_message/skill.py b/seeds/simplex/send_message/skill.py index 77bdae0..291089b 100644 --- a/seeds/simplex/send_message/skill.py +++ b/seeds/simplex/send_message/skill.py @@ -13,7 +13,7 @@ import urllib.error import urllib.request from semif_agent.decisions import DecisionRequest, Option -from semif_agent.skills import ActionResult +from semif_agent.skills import ActionResult, last_result INTEGRATION = { "service": "simplex", @@ -383,9 +383,14 @@ def act(ctx, request) -> ActionResult: display_name = _display(chosen) or recipient # --- 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) if not message_text and user_input and not used_input_for_contact: message_text = user_input + if not message_text: + message_text = last_result(request) if not message_text: written, reason = _llm_message_text(ctx, query) if written: diff --git a/seeds/simplex/send_message/skill.test.py b/seeds/simplex/send_message/skill.test.py index fc3fddb..275b112 100644 --- a/seeds/simplex/send_message/skill.test.py +++ b/seeds/simplex/send_message/skill.test.py @@ -31,9 +31,10 @@ LLM_REPLY = "a friendly hello" class FakeRequest: """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.user_input = user_input + self.run_ledger = list(run_ledger or []) class FakeResult: @@ -272,6 +273,49 @@ def test_message_written_by_llm_bridge(): 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(): """A clear recipient but no message text and no llm bridge: ask the user.""" reset() @@ -360,6 +404,7 @@ def main(): test_happy_path() test_ambiguous_contact_uses_engine() test_message_written_by_llm_bridge() + test_chained_result_is_sent() test_missing_text_without_llm_asks() test_unknown_contact_asks() test_send_refused_is_reported() diff --git a/semif_agent/cli.py b/semif_agent/cli.py index 1d6b5e1..ac0e947 100644 --- a/semif_agent/cli.py +++ b/semif_agent/cli.py @@ -485,16 +485,26 @@ def _print_approvals(scheduler: Scheduler) -> None: print(f"[approval] {item['id']} new {item['kind']} {target}: {item['description']}") -def _print_reply(reply, show_run_id: bool = False) -> None: - """Print a scheduler reply, optionally keeping its run id visible.""" +def _print_reply(reply, show_run_id: bool = False, verbosity: str = "result") -> None: + """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 "" print(f"[{reply.status}] {label}{reply.text}") + for line in getattr(reply, "decision_lines", ()) or (): + print(f" {line}") def _drain_queue(scheduler: Scheduler) -> None: """Run queued work, printing each outcome with its run id.""" + verbosity = getattr(scheduler, "verbosity", "result") 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: @@ -646,13 +656,13 @@ def repl(scheduler: Scheduler, config: dict) -> int: scheduler.busy(line[5:].strip()) print("current process set (busy).") continue - _print_reply(scheduler.submit(line)) + _print_reply(scheduler.submit(line), verbosity=scheduler.verbosity) if _fatal_exit(scheduler) is not None: return 1 while scheduler.pending is not None: hint = "" if scheduler.pending.pre_act else " [leave empty to skip]" 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: return 1 _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()] for row in rows: _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: return 1 diff --git a/semif_agent/decisions.py b/semif_agent/decisions.py index 687a71b..adae0dc 100644 --- a/semif_agent/decisions.py +++ b/semif_agent/decisions.py @@ -72,6 +72,13 @@ class Request: reentries: int = 0 resume: dict[str, Any] = field(default_factory=dict) 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": return Request( @@ -83,4 +90,5 @@ class Request: priority=self.priority, reentries=self.reentries + 1, resume=dict(self.resume), + run_ledger=[dict(entry) for entry in self.run_ledger], ) diff --git a/semif_agent/gateway/service.py b/semif_agent/gateway/service.py index b273279..e2f87e5 100644 --- a/semif_agent/gateway/service.py +++ b/semif_agent/gateway/service.py @@ -313,10 +313,11 @@ class GatewayService: reply = self.scheduler.answer(msg.text) if self.scheduler.pending is None: self._pending_owner = None - self._reply( - *reply_to, reply.text, kind=_reply_kind(reply.status), - skill_ref=reply.skill_ref, result=reply.result, - ) + if not self._hidden(reply): + self._reply( + *reply_to, reply.text, kind=_reply_kind(reply.status), + skill_ref=reply.skill_ref, result=reply.result, + ) elif pending is not None and self._pending_owner not in (None, reply_to): self._reply( *reply_to, @@ -348,10 +349,11 @@ class GatewayService: self._owners[reply.run_id] = reply_to if reply.status == "needs_input": self._pending_owner = reply_to - self._reply( - *reply_to, reply.text, kind=_reply_kind(reply.status), - skill_ref=reply.skill_ref, result=reply.result, - ) + if not self._hidden(reply): + self._reply( + *reply_to, reply.text, kind=_reply_kind(reply.status), + skill_ref=reply.skill_ref, result=reply.result, + ) self.drain() self.surface(origin=reply_to) @@ -362,6 +364,8 @@ class GatewayService: if not results: break for reply in results: + if self._hidden(reply): + continue owner = self._owner_of(reply.run_id) if reply.status == "needs_input" and owner: self._pending_owner = owner @@ -372,6 +376,17 @@ class GatewayService: 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: """Send any newly posted authoring questions / repair offers.""" questions = self.scheduler.pending_questions() diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index c4e5c2f..7be44b4 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -90,6 +90,25 @@ def normalize_new_skill_mode(value) -> str | 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 class Process: request: Request @@ -223,6 +242,10 @@ class DispatchResult: #: The skill's own detail (its `action_log`, or `new_state` when empty) — #: the unwrapped result a `result_only` front end speaks. 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 @@ -240,6 +263,11 @@ class SchedulerReply: run_id: str = "" skill_ref: 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: @@ -275,6 +303,19 @@ class Scheduler: #: option, so its confidence carries no match signal). self.bypass_tau = float(nav_cfg.get("softmax_bypass_tau", 0.5)) 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.degeneration_check_factory = degeneration_check_factory self.regen_decision_factory = regen_decision_factory @@ -329,7 +370,13 @@ class Scheduler: engine=self.engine, config=config, timers=self.timers, admin=self ) 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.current: Process | None = None @@ -404,11 +451,14 @@ class Scheduler: return SchedulerReply( "needs_input", outcome.summary, request.id, outcome.skill_ref, outcome.result, + decision_lines=self._decision_lines(request.id), ) self.trace.append("ran", request.id, skill=outcome.skill, summary=outcome.summary) return SchedulerReply( "running", outcome.summary, request.id, outcome.skill_ref, outcome.result, + intermediate=outcome.intermediate, + decision_lines=self._decision_lines(request.id), ) ok = self.queue.push(request) @@ -467,6 +517,7 @@ class Scheduler: SchedulerReply( "needs_input", outcome.summary, request.id, outcome.skill_ref, outcome.result, + decision_lines=self._decision_lines(request.id), ) ) continue @@ -475,10 +526,31 @@ class Scheduler: SchedulerReply( "ran", outcome.summary, request.id, outcome.skill_ref, outcome.result, + intermediate=outcome.intermediate, + decision_lines=self._decision_lines(request.id), ) ) 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 ---- def _dispatch(self, request: Request) -> DispatchResult: @@ -510,6 +582,11 @@ class Scheduler: category_tau=self.category_tau, action_tau=self.action_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 self.new_skill_mode == "deny": @@ -531,9 +608,10 @@ class Scheduler: # therefore the sole leaf-level create door and is never bypassed: a # confident softmax winner among only-wrong options must still be # 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 - ): + ) + if verdict == "different": self.trace.append( "intent_mismatch", request.id, @@ -543,6 +621,10 @@ class Scheduler: if self._category_locked(navigation.category): return self._blocked_create(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) def _dispatch_create_category(self, request: Request) -> DispatchResult: @@ -707,12 +789,15 @@ class Scheduler: return SchedulerReply( "needs_input", result.summary, pending.request.id, result.skill_ref, result.result, + decision_lines=self._decision_lines(pending.request.id), ) self.current = None self.trace.append("ran", pending.request.id, skill=result.skill, summary=result.summary) return SchedulerReply( "ran", f"[resumed] {result.summary}", pending.request.id, 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: @@ -741,29 +826,67 @@ class Scheduler: skill_ref=f"{skill.category}.{skill.name}", result=outcome.action_log or outcome.new_state or None, ) + verdict = outcome.outcome or ("done" if outcome.success else "failed") self.trace.append( "assessed", request.id, skill=skill.name, + outcome=verdict, success=outcome.success, summary=outcome.summary, assessment_summary=outcome.assessment_summary, action_log=outcome.action_log, - updated_request=outcome.updated_request, ) - requeued = False - if outcome.updated_request and request.reentries < self.max_reentries: - child = _requeue(request, outcome.updated_request) - # Remember what this attempt observed so the next assessment can - # tell a genuine retry (the result changed) from a guaranteed - # repeat against unchanged state. - child.meta["prev_result"] = outcome.action_log or outcome.new_state - self.queue.push(child) - self.trace.append("requeued", request.id, text=outcome.updated_request) - if self.on_request_requeued is not None: - self.on_request_requeued(request.id, child.id) - requeued = True - if not outcome.success and not (outcome.updated_request and requeued): + if verdict == "continue": + entry = { + "query": request.text, + "skill": f"{skill.category}.{skill.name}", + "outcome": 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.trace.append( + "continued", + request.id, + skill=entry["skill"], + outcome=entry["outcome"], + step=len(child.run_ledger), + ) + if self.on_request_requeued is not None: + self.on_request_requeued(request.id, child.id) + # Intermediate step: the request is re-dispatched, and the final + # 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) return DispatchResult( kind="ran", @@ -774,6 +897,21 @@ class Scheduler: 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 ---- def _propose_repair(self, skill: Skill, request: Request, outcome) -> None: @@ -2305,10 +2443,20 @@ class Scheduler: return "\n".join(lines) -def _requeue(request: Request, updated_text: str) -> Request: - updated = Request(updated_text, source="requeue") +def _continue(request: Request, entry: dict) -> Request: + """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.meta["parent_run"] = request.id + updated.run_ledger = [dict(e) for e in request.run_ledger] + [dict(entry)] return updated diff --git a/semif_agent/skill.py b/semif_agent/skill.py index ae291e7..928eb95 100644 --- a/semif_agent/skill.py +++ b/semif_agent/skill.py @@ -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. Assessment is a SemIf decision, not generation: `assess:outcome` decides -success/failure (P(success) >= tau) and, on failure, `assess:requeue` decides -complete/retry. The run summary is deterministic — same inputs, same string — -built from the category, skill, 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. +whether there is any additional work to do — `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). The run summary is +deterministic — same inputs, same string — built from the category, skill, +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 it runs. Those are asked pre-act, runner-driven: `run` resolves the tiered @@ -35,6 +37,8 @@ from .skills import ( ActionContext, Skill, SkillStore, + bound_output, + render_ledger, resolve_skill_config, unresolved_variables, ) @@ -87,7 +91,12 @@ class RunResult: summary: str action_log: 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 assessment_summary: str = "" error: str | None = None @@ -102,11 +111,25 @@ class SkillRunner: log: DecisionLog, store: SkillStore | None = None, tau: float = 0.6, + done_tau: float = 0.5, + fail_tau: float = 0.5, + result_chars: int = 300, ): self.ctx = ctx self.log = log self.store = store 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 ---- @@ -288,111 +311,98 @@ class SkillRunner: def _assess( self, skill: Skill, request: Request, ctx: ActionContext, action - ) -> tuple[bool, str | None]: - """SemIf assessment: did the run succeed, and should it run again? + ) -> str: + """SemIf assessment: is there any *additional work* to be done? - `assess:outcome` decides success (`P(success) >= tau`); a failure is - then offered to `assess:requeue`, which picks complete/retry. On retry - the original request text is re-dispatched (the scheduler bounds it by - `max_reentries`). Both are real logged decision rows. The state carries - the skill's declared action, the goal, and the resolved inputs so the - decision sees what the skill was meant to do and how its inputs - resolved; the requeue state additionally flags a retry that would - reproduce the identical observed result as a no-op. The engine is always - real: EngineUnavailable propagates to the scheduler, which marks the app - fatal. + A single three-way `assess:outcome` decision over the step's own action + plus the run ledger so far: + + - ``done`` — the request is satisfied (a definitive "nothing found" + counts as done); + - ``continue`` — the step worked, but the request is not yet satisfied; + the scheduler routes the next step (bounded by ``max_reentries`` and + the monotonic-progress guard); + - ``failed`` — the step errored / did not work → the repair path. + + 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}" resolved = _resolved_inputs(skill, ctx.config) - outcome = 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}" - ), - question="Did the skill achieve the user's goal?", + observed = bound_output(action.action_log, self.result_chars) + if not observed: + observed = bound_output(action.new_state, self.result_chars) + 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{observed}" + ) + 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=[ Option( - "success", - "Yes — the skill carried out the request and produced a " - "truthful result. A definitive 'nothing found' or 'nothing " - "to do' result (empty inbox, no unread messages, no " - "matching event) counts as success.", + "done", + "No — the request is satisfied. A definitive 'nothing found' " + "or 'nothing to do' result (empty inbox, no unread messages, " + "no matching event) counts as done.", ), Option( - "failure", - "No — the request was not carried out, or the result is an " - "error, a refusal, or an unresolved action.", + "continue", + "Yes — this step worked, but the request is not yet satisfied; " + "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( - outcome, + decision, result, extra={"phase": "assess:outcome", "run_id": request.id, "skill": label}, ) - success = result.prob("success") >= self.tau - if success: - return True, None - - # A retry that would reproduce the identical observed result is a - # guaranteed no-op run (the request, config, and external state are - # 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 + probs = result.probs + if probs.get("failed", 0.0) >= self.fail_tau: + return "failed" + if probs.get("done", 0.0) >= self.done_tau: + return "done" + return "continue" def _finish( self, skill: Skill, request: Request, ctx: ActionContext, action ) -> 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: summary = deterministic_summary( - skill.category, skill.name, True, action.action_log, observed + skill.category, skill.name, True, action_log, observed ) return RunResult( skill=skill.name, success=True, summary=summary, - action_log=action.action_log, + action_log=action_log, new_state=observed, 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", []) for decision, result in decisions: @@ -408,15 +418,15 @@ class SkillRunner: ) summary = deterministic_summary( - skill.category, skill.name, success, action.action_log, observed + skill.category, skill.name, success, action_log, observed ) return RunResult( skill=skill.name, success=success, summary=summary, - action_log=action.action_log, + action_log=action_log, new_state=observed, - updated_request=updated_request, + outcome=verdict, decisions_logged=len(decisions), assessment_summary=summary, ) \ No newline at end of file diff --git a/semif_agent/skills.py b/semif_agent/skills.py index 7b8eb30..9686162 100644 --- a/semif_agent/skills.py +++ b/semif_agent/skills.py @@ -575,11 +575,61 @@ def unresolved_variables( 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. -> ``. 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: parts = [request.text] if 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): @@ -1174,6 +1224,7 @@ def navigate( category_tau: float = 0.75, action_tau: float = 0.5, bypass_tau: float = 0.5, + skip_actionability: bool = False, ) -> Skill | CreateCategory | CreateSkill: """Descend the tree one SemIf choice per level. Every choice is logged. @@ -1226,7 +1277,7 @@ def navigate( "create_category", request.id, 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=[], selected="create_category", probs={}, @@ -1236,8 +1287,10 @@ def navigate( # 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 # softmax; a request always proceeds to category selection, so it can never - # be canned. - if confirm_non_action(engine, log, trace, request, action_tau): + # be canned. A **continuation** (a request already carrying a run ledger) is + # 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") if response_skills: return _navigate_canned( @@ -1247,7 +1300,7 @@ def navigate( "create_category", request.id, 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=[], selected="create_category", probs={}, @@ -1263,7 +1316,7 @@ def navigate( ) top = DecisionRequest( 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] + [create_category], ) @@ -1338,7 +1391,7 @@ def navigate( request, 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], ) leaf_result = engine.call(leaf) @@ -1482,36 +1535,67 @@ def confirm_skill_fit( request: Request, skill: Skill, tau: float = 0.6, -) -> bool: - """Does this skill's action actually match what the request asks for? +) -> str: + """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 - the leaf softmax). If the skill's action is not the same action the request - 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). + the leaf softmax). It answers three ways: - Wording tuned against the real model: comparing the two *actions* - ("different action") is unambiguous where "can this serve the request" was - not — e.g. "message Sam" (an implicit send in instant-messaging syntax) - reads as a different action from "read the next message". Do not add an - instant-messaging context hint: it over-fires and pulls read phrasings to - the send side. The comparison is over-permissive on near-synonyms (read vs - send score "same" ~0.74-0.78), so it is paired with the softmax that - disambiguates them — the guard only ever sees the softmax winner. + - ``same`` — the skill performs the next action the request needs (running it + can satisfy the request, or is its final step); + - ``part`` — the request needs more than one action and this skill performs + one required part of it; + - ``different`` — the skill does not do any action the request asks for; + dispatch authors a new leaf instead. + + ``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. """ + state = ( + f"Requested action: {request.text}\n" + 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=( - f"Requested action: {request.text}\n" - f"Action of the existing skill: {skill.description}" + 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=[ - 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( "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}", }, ) - 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( "intent_guard", request.id, @@ -1533,9 +1625,10 @@ def confirm_skill_fit( skill=skill.name, selected=result.selected, probs=result.probs, + verdict=verdict, fits=fits, ) - return fits + return verdict def tree_summary(tree: dict[str, list[Skill]]) -> str: diff --git a/semif_agent/static/app.js b/semif_agent/static/app.js index 7c1c95e..b43e1c5 100644 --- a/semif_agent/static/app.js +++ b/semif_agent/static/app.js @@ -413,12 +413,14 @@ function eventNode(evt) { body.className = "node-question"; if (evt.kind === "assessed") { body.textContent = evt.summary || ""; - if (evt.updated_request) { - const req = document.createElement("div"); - req.className = "muted"; - req.textContent = `→ requeued: ${evt.updated_request}`; - node.appendChild(req); - } + } else if (evt.kind === "continued") { + body.textContent = `→ next step: ${evt.skill || ""}`; + const outcome = document.createElement("div"); + outcome.className = "muted"; + 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") { body.textContent = "queued"; } else if (evt.kind === "dropped") { diff --git a/semif_agent/trace.py b/semif_agent/trace.py index e66a7d8..b5ccd44 100644 --- a/semif_agent/trace.py +++ b/semif_agent/trace.py @@ -2,7 +2,7 @@ scheduler. 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 each run's flow without touching the decision-log contract. Both files are append-only; replays read them in order. diff --git a/tests/integration/test_pipeline.py b/tests/integration/test_pipeline.py index 44c9a1e..86443fe 100644 --- a/tests/integration/test_pipeline.py +++ b/tests/integration/test_pipeline.py @@ -720,24 +720,21 @@ def test_empty_result_is_assessed_as_success(tmp_path): log = DecisionLog(str(tmp_path / "decisions.jsonl")) runner = SkillRunner(ActionContext(engine=engine, config={}), log) 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()] 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): - """A correctly-read result is a successful run, not a failure. +def test_read_result_is_assessed_as_done(tmp_path): + """A correctly-read result is a satisfied request, not a failure. 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 - (e.g. "What's my next simplex message?"), which then looped the retry ladder - and offered to repair a working skill. This exercises the real engine, since - only it produces the probabilities. + (e.g. "What's my next simplex message?"), which then looped into repair of a + working skill. This exercises the real engine, since only it produces the + probabilities. """ config = load_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")) runner = SkillRunner(ActionContext(engine=engine, config={}), log) 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()] assert "assess:outcome" in phases - assert "assess:requeue" not in phases, ( - "a truthful read must not be retried or repaired" - ) diff --git a/tests/test_input_channel.py b/tests/test_input_channel.py index 6bfe649..54d9635 100644 --- a/tests/test_input_channel.py +++ b/tests/test_input_channel.py @@ -107,7 +107,7 @@ def test_act_decisions_logged_on_completion(tmp_path): skill = Skill(name="t.x", category="t", description="", act=act) scheduler = build_scheduler( 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")) @@ -119,7 +119,8 @@ def test_act_decisions_logged_on_completion(tmp_path): assert len(act_rows) == 1 assert act_rows[0]["extra"]["run_ok"] is False 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): diff --git a/tests/test_skills.py b/tests/test_skills.py index 2ce06e0..5458914 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -28,6 +28,7 @@ from semif_agent.scheduler import ( PendingQuestion, RepairOffer, Scheduler, + SchedulerReply, SkillWrite, ) 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" -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 scheduling/authoring mechanics are testable without a GGUF. Assessment is a SemIf decision now, so a run needs the engine to answer `assess:*`.""" + config = { + "skills": {}, + "category_registry": str(tmp_path / "categories.json"), + "skill_bodies": str(tmp_path / "skills"), + "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={ - "skills": {}, - "category_registry": str(tmp_path / "categories.json"), - "skill_bodies": str(tmp_path / "skills"), - "skill_seeds": str(tmp_path / "seeds"), - }, + config=config, trace=TraceLog(str(tmp_path / "runs.jsonl")), 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): """A failed run with an empty action log falls back to the new state.""" scheduler = _scheduler( - tmp_path, choices={"achieve the user's goal": "failure", - "complete, or should it run again": "complete"} + tmp_path, choices={"additional work to be done": "failed"} ) 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")) assessed = [e for e in scheduler.trace.read() if e["kind"] == "assessed"] assert assessed[-1]["success"] is False + assert assessed[-1]["outcome"] == "failed" 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): """The assessment decision must see what the skill was meant to do. - Regression: with only `skill: