Files
javis_bot/src/jarvis/reply/planner.spec.md
javis-bot d31d75f18f fix(planner): plan in the query's own writing system only
Live 2026-11-18 '자비 사과랑 배 중에 뭐가 더 달아' was searched as
'사과와 배 중哪个가 더 단가요'. The rule and the user message's closing line
now say to use only the query's letters.

Eval test_search_in_users_language.py, new case fruit (qwen3.6-35b-a3b,
game PC): Han in the search 7/7 before; rule only 3/3, closing line only
3/3, both 0/6; whole file 12/12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:22:17 +09:00

18 KiB

Task-list planner

Purpose

Small chat models (gemma4:e2b class) don't reliably decompose multi-step queries turn-by-turn. They stop after one tool call when a second is needed, echo the raw user utterance into tool arguments, or skip tools entirely and confabulate from training. The planner fixes this by running a single cheap classification-shaped LLM pass at the very front of the reply flow that emits a short ordered list of sub-tasks.

The planner runs after the tool router and before memory search. The router narrows the catalogue first so the planner's tool steps reference concrete chosen names; the planner then gates memory enrichment and drives direct execution for small models.

The engine uses the plan for three things:

  1. Gate memory enrichment — the planner emits an explicit searchMemory topic='<topic>' directive on queries that need past user context; we skip the keyword-extraction LLM call, the diary / graph lookup, and the memory-digest LLM call otherwise.
  2. Confirm the tool allow-list — the router's picks are authoritative; the tool names the planner references are unioned in as a safety net. Feeding the planner the narrowed catalogue (instead of the full 30+ list) stops small planners from paraphrasing ("get the weather") and from defaulting to webSearch when a more specific tool exists.
  3. Drive direct execution for small models, as before — each planned step is resolved to a concrete tool call without round-tripping the chat model for intermediate turns.

Scope

This spec covers src/jarvis/reply/planner.py and the engine integration in src/jarvis/reply/engine.py.

Behaviour

When the planner runs

  • After the dialogue context is assembled, MCP tools are loaded, and the tool router has produced a narrowed catalogue. Memory search runs after the planner so it can be gated on its output.
  • The planner sees the router-narrowed tool catalogue (name + one-line description), not the full 30+ list. It does not see memory content — it decides whether memory is needed, via the searchMemory directive.
  • Only when the query is at least MIN_QUERY_CHARS long (default 4). Pure noise like "hi" / "ok" still short-circuits.
  • Only when cfg.planner_enabled is True (default).
  • Only when an ollama_base_url and a resolvable model are available.

Model resolution

  1. cfg.planner_model (explicit override, for benchmarking)
  2. cfg.ollama_chat_model

The planner must track the chat model. The plan is the scaffolding the chat model follows; a weaker planner on top of a stronger chat model produces bad scaffolding the chat model then fights against. The chat model is also the one the user picked during setup as their quality target, so upgrading it (through the setup wizard or config) must automatically upgrade plan quality without requiring a second choice.

Note: the planner pays a cache miss relative to the tool router, which does ride the warm small model. This is the intended trade-off — plan quality drives everything downstream, router quality only narrows one turn's allow-list.

Prompt contract (plan_query)

The planner's user message also carries a LIVE CONTEXT: line: the engine's live time/location string (_live_time_location_string), passed as plan_query(..., live_context=...). It lets the planner tell a known location from an unknown one without seeing any memory content.

The planner's AVAILABLE TOOLS lines come from planner_tool_catalog(schema): the tool's first description line plus its argument names, e.g. getWeather: Weather only ... (args: location). Without the argument names the planner guessed keys (location= for a city tool, duration=5minutes for minutes), which made concrete steps unparseable.

The planner prompt instructs the model to emit:

  • Short imperative sub-tasks, one per line.
  • At most MAX_STEPS (default 5) steps.
  • As the FIRST step, a searchMemory topic='<topic>' directive only when answering requires information the user shared in prior conversations. Omit otherwise — every extra directive is an avoidable LLM call downstream.
  • The same directive (searchMemory topic='where the user lives') before a tool step that needs a fact about the user themself, such as where they are, when neither the LIVE CONTEXT nor the dialogue gives it (the live context says Location: Unknown or Location: Disabled). When the live context gives a location, a plain weather ask stays memory-free.
  • Tool names from the provided catalog only (exact match), for any concrete tool step.
  • Concrete arguments composed against dialogue context, not the raw utterance. Optional arguments that the user did not supply must be omitted, not fabricated from unrelated words.
  • Angle-bracket placeholders (e.g. <director name from step 1>) for entities the lookup will reveal at runtime.
  • Pronouns and demonstratives in the user query ("he", "his", "her", "their", "it", "that film") must be resolved against the dialogue context before emitting the step. Tools never see prior turns, so the named entity has to appear literally inside the tool argument string — webSearch query='Harry Styles most famous songs', not webSearch query='his most famous songs'.
  • A final synthesis/reply step when any searchMemory or tool step was planned.
  • Steps in the same language the user wrote the query in, the words of search and play arguments too (never translated into English: a search in the user's language finds what people where they are get); the closing line of the user message repeats it, which a small model follows better than the rule alone. Eval evals/test_search_in_users_language.py (qwen3:8b, 3 runs of 3 Korean requests): Korean searches 6/9 before ("요즘 볼 만한 넷플릭스 드라마" searched "best netflix dramas 2026" 3/3), 8/9 after (that one 2/3).
  • Only the writing system of the query, no characters of another script, in the rule and in the closing line ("in its own letters only"). Live 2026-11-18 "자비 사과랑 배 중에 뭐가 더 달아" was searched as "사과와 배 중哪个가 더 단가요". Same eval, case fruit (qwen3.6-35b-a3b): Han in the search 7/7 before; with only the rule 3/3, with only the closing line 3/3, with both 0/6, the other cases unchanged (12/12). webSearch also drops such letters itself (web_search.spec.md).

Parsing and hygiene

  • Numbering (1., 1)), bullets (-, *, •), wrapping quotes, and markdown fences are stripped.
  • Overlong steps (>200 chars) are truncated with an ellipsis.
  • The list is capped at MAX_STEPS.
  • The planner no longer filters out 1-step plans. A single ["Reply to the user."] plan is the planner's positive decision that no memory or tools are needed — the engine uses that to skip the memory extractor, the tool router, and the direct-exec path entirely. Only an empty list means "planner failed / disabled; fall open to legacy safe defaults" (run memory enrichment + tool router). The two states must stay distinguishable.

Engine integration

The engine consumes the plan in two phases.

Phase 1 — preparation gating (before the turn loop starts):

  • plan_requires_memory(plan) — true iff any step is a searchMemory directive. The engine uses it to gate the entire memory-enrichment block (keyword extractor LLM call, diary / graph lookups, digest LLM call). Optional memory_topic_of(step) extracts the directive's topic='...' hint, threaded into the keyword extractor so it anchors on what the planner wanted to look up rather than re-deriving from the raw utterance.
  • tool_names_in_plan(plan, known_names) — ordered de-duped list of tool names the planner referenced. The engine unions this into the router-selected allow-list (never replaces it). stop and toolSearchTool are always added regardless.
  • plan_has_unresolved_tool_steps(plan, known_names) — true when the plan has non-synthesis steps but names no known tool (e.g. the model wrote get the weather instead of getWeather ...). In this state the direct-exec path is skipped — vague step text would otherwise force the resolver LLM to guess arguments (e.g. emitting location='Nowhere' for a bare weather request). The chat model takes the turn instead, using the router-selected allow-list.
  • strip_memory_directives(plan) — the engine strips the searchMemory step from the plan once memory has been fetched, so downstream consumers (system-message injection, direct-exec, progress nudge) see a plan of pure tool + synthesis steps.

Phase 2 — loop integration (existing behaviour):

  • format_plan_block(steps) renders an ACTION PLAN: block that is appended to the initial system message. Empty plan renders nothing. Single-step reply-only plans are not rendered either — they are noise to the chat model since the plan just says "reply".
  • progress_nudge(steps, tool_results_so_far) produces a remainder hint injected after each tool result, naming the next planned step and reminding the model to substitute discovered entities and avoid duplicate arguments.
  • When use_text_tools is active and the plan still has unexecuted tool steps, the engine runs resolve_next_tool_call to convert the next step into a concrete {name, arguments} JSON and dispatches the tool directly, bypassing the chat model for that turn. This keeps small models on-rails without relying on their native tool-call reliability.
  • The chat model still runs the final synthesis turn so the reply is phrased in the daemon's voice using its own profile and persona.

Skipped-tool guard (native tool calling, all model sizes):

  • Problem: capable native-tool models sometimes answer without calling a tool they were given (M0 on Strata, 2026-11-10: a made-up "24 degrees and sunny" instead of the weather tool, "timer set" without the timer tool; the same on qwen2.5:7b through the engine).
  • When a native-tool model's turn is natural-language content, no tool has run in this reply yet, and named_tool_steps(plan, callable_names) finds plan steps that start with a callable tool name (anything in the allow-list except stop and toolSearchTool), the engine drops that answer from the messages and direct-executes those steps, then lets the chat model synthesise from the real results. named_tool_steps ignores step position, so a lone logMeal meal='banana' or searchMemory ... + getWeather plan still counts (tool_steps_of would read both as reply-only).
  • The guard overrides the model's own decision, so it only runs what the planner literally wrote: parse_concrete_tool_step (the resolver's regex fast path, never the LLM resolver) plus a required/unknown-key check against the tool's input schema. An LLM resolver could "repair" a wrong step into a valid but unwanted call (a timer request planned as setBroadcast duration=5 minutes was turned into starting the broadcast).
  • If the first planned step cannot be run as written, the held-back answer is still never delivered (it was given without the tool, so it may be a guess). The engine records the planned call as a failed tool result ("could not be run, nothing was fetched or done") and the chat model answers from that, which under the tool honesty rules means saying it could not check or do it. The guard fires at most once per reply and never in text-tool mode (that mode already direct-executes every plan).
  • In native mode the direct-exec result is a role=tool message answering the synthetic assistant tool_calls message, and no progress nudge is appended.

Intent judge (v2)

The v2 brain (src/voice_worker/voice_worker.spec.md, "History and brain") judges each turn once before the answer: run_reply_engine(intent_judge=True) runs the tool router as usual (the harness's judgement of whether the turn needs a tool and which ones) and runs the planner only when the router picked a tool other than the sentinels (stop, toolSearchTool; the router adds stop to almost every pick). A chatChannels the router picked counts ("post this in the schedule channel" needs the planner to name the channel); its every-turn offer, added after the router, does not. A turn without a tool (greetings, small talk, facts the model knows) goes straight to its answer with one LLM call before it; a tool turn keeps the planner's ordered steps, which multi-step asks need ("who directed Possessor, and what else did they make").

One-step turns. When the router's only pick (sentinels aside) is a tool that does its job in one call, _ONE_STEP_TOOLS in engine.py (getWeather, logMeal, fetchMeals, screenView), and the chat model calls tools natively, the planner does not run: its steps would only repeat the one call the chat model makes itself. The rule reads the router's pick, never the words, so it is language- agnostic. Tools a request may use several times or chain stay planned: search and page fetches, the browsers, schedule and personalNotes (a list before a change), chatChannels. Two or more picked tools are planned as before. Text-tool mode (small non-native models) always plans, since its direct execution runs the plan.

Without a plan the skipped-tool guard above has nothing to run, so these turns get a nudge instead: when the chat model answers in words before any tool ran in this reply, the answer is dropped (no later turn sees it) and a note asks the model to call that tool first, or to ask the user for a missing detail. The nudge is sent at most once per reply. When the model answers without the tool again, that turn falls back to the planned path: the planner runs then (one extra planner call, only on this failure), and the skipped-tool guard above treats the second answer as on any planned turn. A plan naming the tool runs it and the made-up answer never goes out; a plan that needs no tool (a question back to the user, say) lets the answer go out, the planner judging that as before.

Measured on Strata (Qwen3.6, 2026-11-16 16:45-16:58, the engine log): the planner averaged 2.5 s (9 calls), one after the other before the answer on every tool turn, while the router runs during speech (prepare_intent). A planner call that does not run also leaves the engine's second session to the chat model, whose prompt read is the largest cost.

Measured on Strata (Qwen3.6, 2026-11-12): the router took 0.42 s and the planner 0.49-0.94 s, one after the other, before every answer; each call costs at least one full prompt read. Tried first and dropped: the planner alone over the whole catalogue (one call) planned "reply with the weather" without a tool step and lost the weather tool (20 eval failures against 4), and the router alone without a planner failed the chained Possessor research 3 of 3 times. With this rule the whole eval suite passes as with v1's flow (EVAL_COMPACT_PROMPT=1 EVAL_INTENT_JUDGE=1).

prepare_intent(cfg, text, dialogue_memory, chat_available) runs the same router pick ahead of time, with the inputs the reply would give it (the catalogue with chatChannels when a chat backend will be there, the context hint from the asker's dialogue memory); None when the router gave up (its fall-open to the whole catalogue is not a pick). The pick is passed back as run_reply_engine(prepared_tools=...) and the router is not run again. The brain calls it on a partial transcript while the user is still talking.

resolve_next_tool_call

  • Fast path: if the step text is fully concrete (tool name in the allow-list + key='value' / key="value" pairs matching the tool's declared property keys, and no <placeholder>), parse it deterministically and return without any LLM call. This removes the resolver LLM as a failure surface for the common case — small models occasionally flake (timeout, empty, spurious null) even on trivially-concrete steps like webSearch query='foo', which used to fall back to the chat model and produce a refusal instead of the search. The fast path is purely regex-driven, language-agnostic, and never calls the model.
  • LLM path: when the step contains a <placeholder>, uses unknown argument keys, or doesn't fit the key=value shape, the step is passed to the LLM resolver which can substitute entities from prior results and remap names.
  • Returns None for synthesis steps (the LLM emits the literal null), unknown tools, or invalid JSON. All None paths fall back to the normal chat-model turn.
  • Validates the tool name against the provided schema's allow-list.
  • Filters the returned arguments against the tool's declared JSON-schema property keys; unknown keys are dropped before dispatch. Tools that declare no properties keep the args as-is (they are free-form by design).
  • Tolerates markdown fences the model may add despite instructions.
  • Both planner LLM calls (plan_query and resolve_next_tool_call) request num_ctx=8192 from Ollama so enriched memory and tool catalogue don't silently truncate in the 4096-token default window.

Fail-open invariants

  • Timeout, empty response, or exception in the planner LLM call → return [].
  • Invalid JSON in the step resolver → return None and let the chat model handle the turn normally.
  • No plan never worsens the baseline; the engine behaves exactly as it did pre-planner.

Configuration

Key Default Purpose
planner_enabled True Feature gate.
planner_model "" Explicit planner model override.
planner_timeout_sec 6.0 Timeout for plan and step-resolver LLM calls.

Non-goals

  • The planner does not re-plan mid-turn. If the emitted plan is wrong, the engine still progresses via the chat model's native tool calls. When the chat model produces natural-language content the loop terminates immediately.
  • The planner does not validate semantic correctness of the plan; it trusts the model to produce sensible steps and relies on the resolver's schema-level guard to reject unknown tools.
  • Plans are not cached across turns. Each user utterance gets its own plan because the dialogue state and entity references change.