Skip to content

Add clarification for low-confidence skill matches (closes #1090) - #1128

Merged
malibio merged 2 commits into
mainfrom
feature/issue-1090-clarification-on-low-confidence
May 17, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-1090-clarification-on-low-confidence

Conversation

@malibio

@malibio malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • When the skill pipeline finds no match above the 0.8 confidence threshold AND the user message is ambiguous (short, no proper nouns / URLs / numbers), return a clarifying question without invoking the model.
  • Previously, vague inputs like "help" or "do that thing" fell through to the full 13-tool agent path, overwhelming the model and producing empty/poor responses.
  • Unifies the post-inference empty-response fallback (lines ~269-274) with the new clarification path so there's a single consistent "I need more info" response across the agent.

Implementation

  • Added is_ambiguous(message: &str) -> bool heuristic in packages/agent/src/local_agent/agent_loop.rs:
    • < 10 words AND no proper-noun / URL / digit signals
    • Sentence-initial capitalization is ignored (carries no signal)
  • In LocalAgentLoop::run_turn, the skill match is resolved once into a single Option<SkillMatch>. If skill_match.is_none() and is_ambiguous(user_message), we append a clarifying assistant message and return immediately with zero tool calls / zero token usage.
  • The post-inference empty-response fallback now reuses the same CLARIFYING_QUESTION constant.
  • A handful of existing tests used very short test prompts ("Hi there", "Search", "Hello", etc.) that would now be classified as ambiguous and short-circuited. These were updated to use clearly actionable prompts (with proper nouns or 10+ words) so the ReAct loop is still exercised. This reflects the real behavior change: vague inputs no longer reach inference.

Test plan

  • Unit tests for is_ambiguous cover: short-vague, proper-noun, URL, digit, long-message, and sentence-initial-capitalization carve-outs.
  • ambiguous_message_returns_clarification_without_inference uses a PanicEngine to prove inference is never invoked for "help".
  • actionable_message_proceeds_to_inference_without_skill_match is the counter-example: a message containing a proper noun still hits the model.
  • All existing 296 nodespace-agent lib tests pass.
  • Full bun run test:all passes: 3918 frontend + 1182 Rust = 5100 tests, 0 failures (matches baseline).
  • bun run quality:fix clean (eslint, svelte-check, cargo fmt, cargo clippy -D warnings).

Test results vs baseline

Suite Baseline After
Frontend (vitest) 3918 passed 3918 passed
Rust (cargo test) n/a (warm cache required) 1182 passed
Agent crate (focused) n/a 296 passed (9 new)

When the skill pipeline finds no match above the 0.8 confidence threshold
and the user message is ambiguous (short, no proper nouns / URLs / numbers),
return a clarifying question without invoking the model. Previously this
case fell through to the full 13-tool agent path, which overwhelmed the
model and produced empty/poor responses.

Changes:
- Add `is_ambiguous(msg)` heuristic: < 10 words AND no proper-noun /
  URL / digit signals (sentence-initial capitalization ignored).
- Short-circuit in `LocalAgentLoop::run_turn` before inference when
  no skill matched and the message is ambiguous — appends a clarifying
  assistant message and returns with zero tool calls / zero token usage.
- Unify the post-inference empty-response fallback with the same
  clarifying question for a single consistent "I need more info" path.
- Refactor skill_match resolution so the short-circuit and the
  prompt/tool-scoping branch share one Option.
- Update existing tests to use clearly actionable messages where the
  ReAct loop is being exercised (real product behavior: vague inputs
  now never reach inference).

Tests:
- `is_ambiguous_*` (6 cases): vague-short, proper-noun, URL, digit,
  long-message, sentence-initial-capitalization carve-outs.
- `ambiguous_message_returns_clarification_without_inference`: uses a
  PanicEngine to prove inference is never called for "help".
- `actionable_message_proceeds_to_inference_without_skill_match`:
  counter-example — a message with a proper noun still hits the model.
@malibio

malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Initial review (no prior reviews/comments on PR).

This is a clean, well-scoped change that delivers the requested behavior with strong test coverage. The is_ambiguous heuristic is simple, documented, and the short-circuit correctly bypasses inference for vague messages with no skill match. The empty-response fallback is unified with the new clarification path via a shared CLARIFYING_QUESTION constant. Recommendation: APPROVE with a few minor suggestions noted below.


Requirements Check (Acceptance Criteria from #1090)

# Criterion Status Evidence
1 Low confidence + ambiguous → clarifying question instead of full tools ✅ agent_loop.rs:215-241 short-circuits before inference; ambiguous_message_returns_clarification_without_inference test uses PanicEngine to prove inference is never invoked.
2 Clarifying question returned as normal agent response (visible in UI) ✅ agent_loop.rs:223-228 appends Assistant message to session.messages; agent_loop.rs:233-240 returns it as AgentTurnResult.response.
3 Low confidence + actionable → still proceeds with full tools ✅ is_ambiguous returns false for proper nouns / URLs / digits / messages ≥10 words. actionable_message_proceeds_to_inference_without_skill_match confirms behavior end-to-end.
4 Empty-response fallback unified with clarification path ✅ (partial — see 🟢 below) agent_loop.rs:375-381 reuses CLARIFYING_QUESTION constant. Note: there is a second, separate post-final-inference fallback at agent_loop.rs:545-555 that does not use the constant — it produces tool-summary text or empty response_text. This is a different code path (post-tool-call exhaustion) and was not in scope of the issue's "lines ~269-274", so I consider this acceptable.
5 Unit test covering low-confidence clarification path ✅ 9 new tests: 6 is_ambiguous_* heuristic tests + ambiguous_message_returns_clarification_without_inference + actionable_message_proceeds_to_inference_without_skill_match. All pass locally.
6 bun run quality:fix passes ✅ Per PR description; the schema.rs blank-line removal is cargo fmt output, confirming format was run.
7 bun run test:all passes ✅ Per PR description: 3918 frontend + 1182 Rust = 5100 tests, 0 failures, matches baseline.

All seven acceptance criteria are satisfied.


Findings

🔴 Critical / Blocker

None.

🟡 Improvements

1. agent_loop.rs:256-259 — expect() on an internally-maintained invariant is fragile

let pipeline = self
    .skill_pipeline
    .as_ref()
    .expect(\"skill_match implies skill_pipeline is Some\");

skill_match being Some does imply self.skill_pipeline is Some today (see the match at line 205), but this couples two code locations via a panic message rather than via the type system. A future refactor that introduces another way to populate skill_match (e.g., a fallback skill, a test fixture, a cached result) will silently break this invariant and crash production.

Engineering principle: Make illegal states unrepresentable. Either keep the nested-if-let form from the original code (which had the pipeline-and-match bound together lexically), or carry the pipeline reference inside SkillMatch itself so the invariant is enforced by the type, not by an assertion.

Minimal fix: revert this hunk to the prior nested structure and add the short-circuit as a separate pre-check using pipeline.find_skill(...) results — the diff cost is small, and the resulting code can't drift.

2. agent_loop.rs:68-104 — is_ambiguous false-positives on single-token code-like inputs

The heuristic treats anything ≤9 words with no digit and no non-leading uppercase as ambiguous. That includes inputs like console.log('x'), path/to/file.rs, myFunc(), or any single-token identifier the user pastes for inspection. Those are clearly actionable but would be classified ambiguous and short-circuited to the clarifying question.

Engineering principle: Heuristics should fail open on clearly intentional inputs. Two cheap signals would catch most cases without changing the philosophy:

  • Presence of (, ), /, ., :, _, or - in any word → likely a path/identifier/URL-like reference → not ambiguous.
  • Any non-ASCII-letter character class (existing is_ascii_digit already covers digits).

This is an improvement, not a blocker — the issue explicitly says "start simple" and a short code snippet without context is in fact ambiguous from a response perspective; the worst case is a clarifying question, which is recoverable. Worth a small follow-up.

3. Test prompts updated to bypass is_ambiguous — verify intent is preserved

Nine existing tests had their prompts lengthened or sprinkled with proper nouns (e.g., \"Hi there\" → \"please tell me about the GitHub release pipeline today\", \"Search\" → \"search for any GitHub release notes documents\"). I spot-checked the affected tests:

  • single_turn_no_tools (line 1110) — still exercises one inference round → final text. ✅
  • tool_call_then_final_response (line 1150) — still exercises tool call → final text. ✅
  • multi_step_tool_chain (line 1184) — still exercises 3-round ReAct loop. ✅
  • respects_iteration_cap (line 1748) — still exercises iteration cap. ✅
  • service_propagates_inference_error (line 1664) — still asserts user message recorded. ✅

The renames don't mask regressions; they correctly reflect that vague inputs no longer reach inference (which is the product change). However, the new prompts are now indistinguishable from one another ("GitHub release pipeline", "GitHub release workflow", "GitHub release notes") — a small readability cost. Consider giving each test a prompt that gestures at what the test is about (e.g., the cancellation test could use \"cancel my GitHub release task immediately\").

Engineering principle: Tests should be self-documenting. Right now the prompt is noise; a meaningful prompt costs nothing and helps the next reader.

🟢 Nits / Observations

Nit: agent_loop.rs:75 — let lower = trimmed.to_lowercase(); allocates a String on every call. For chat-rate input this is negligible, but a contains_ignore_ascii_case-style scan over trimmed would avoid the allocation and is idiomatic Rust. Skip unless this becomes a hot path.

Nit: agent_loop.rs:545-555 — the post-final-inference fallback (after tool-call exhaustion with empty text) still produces \"• <tool> completed\" summaries or empty response_text. Not in scope for #1090 (the issue called out lines ~269-274 specifically, which were correctly unified), but a future cleanup could route this through CLARIFYING_QUESTION too when all_tool_executions.is_empty().

Nit: agent_loop.rs:236-239 — InferenceUsage { prompt_tokens: 0, completion_tokens: 0 } is correct (the model wasn't called), but the skill pipeline did run a semantic search whose cost is silently swallowed. Probably fine — there's no existing telemetry for that and other early-return paths behave the same way — but worth a passing note that "zero usage" doesn't mean "zero work".

Nit: schema.rs:1018 — single blank-line removal is cargo fmt output, unrelated to #1090. Harmless, but ideally cargo fmt is run as a separate commit so PR diffs stay topical. Not a blocker; the noise is one line.

Nit: The CLARIFYING_QUESTION string lives in agent_loop.rs. If/when localization or A/B testing of the wording becomes a concern, lift it to a config module. Premature today.


Edge-case sanity check on is_ambiguous (no changes needed)

Input Classification Correct?
\"\", \" \" ambiguous ✅ (short-circuits to clarification)
\"😀\" ambiguous ✅ (one-word, no signal)
\"open Москва\" (Cyrillic proper noun) not ambiguous ✅ (char::is_uppercase is Unicode-aware)
\"URGENT HELP\" not ambiguous ✅ ("HELP" idx=1 uppercase signals intent)
\"١٢٣\" (Arabic-Indic digits) ambiguous ⚠️ is_ascii_digit misses these — negligible in practice
\"console.log('x')\" ambiguous ⚠️ false positive — see Improvement #2
\"check https://example.com\" not ambiguous ✅
Long sentence with no proper nouns not ambiguous ✅ (word count gate)

Standards Compliance

  • ✅ No #[allow(dead_code)] or #[deprecated] introduced.
  • ✅ No lint suppressions in the diff.
  • ✅ No backward-compatibility scaffolding (greenfield-appropriate: the old empty-fallback string is replaced, not kept alongside).
  • ✅ No raw println!/eprintln!; uses tracing::{info,warn}.
  • ✅ Conventional commit message format, references closes #1090.

Recommendation: APPROVE

The change cleanly delivers the issue's intent, the tests prove the short-circuit, and acceptance criteria are met. The improvements listed are quality refinements that can be deferred (or addressed in a follow-up) without blocking merge. The only one I'd encourage the author to consider before merge is the .expect() at agent_loop.rs:259 — a brittle invariant is the kind of thing that gets you woken up at 3 AM.

🤖 Generated with Claude Code

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommendation: APPROVE (cannot self-approve via GitHub; recording as a comment review). All 7 acceptance criteria from #1090 are met, 9 new tests pass, and the PanicEngine test cleanly proves the short-circuit bypasses inference. See full review in PR comment for findings. Two minor improvements suggested (brittle expect() at agent_loop.rs:259 and code-snippet false-positives in is_ambiguous) are non-blocking and can be follow-ups.

… signals, clarify test prompts

- Replace .expect() at agent_loop.rs by carrying the pipeline reference
  alongside the SkillMatch in a tuple. The scoping branch now has a
  locally-provable handle to the pipeline (no runtime invariant check
  required, so a future refactor can't silently break this).
- is_ambiguous now treats tokens containing '(', ')', '/', '.', ':',
  '_', or '-' as specific signals — so single-token code/path-like
  inputs (e.g. `console.log('x')`, `path/to/file.rs`, `my_var`,
  `kebab-case-name`) no longer false-positive as ambiguous. Added
  `is_ambiguous_treats_code_and_paths_as_actionable` unit test.
- Rewrote ~13 test prompts to be self-documenting: each now gestures
  at what the test verifies (e.g. "Keep running search_nodes forever
  — verify the iteration cap stops it" for max_iteration_limit,
  "Trigger an inference error and confirm the GitHub session
  survives intact" for session_persistence_after_inference_error).
  All updated prompts still pass is_ambiguous == false via proper
  noun, digit, or code-token signal.

Skipped green nits (justification):
- to_lowercase() allocation: negligible at chat rates, premature
  optimization.
- post-tool-exhaustion fallback at lines ~545-555: explicitly out
  of scope per reviewer.
- Unrelated schema.rs blank-line removal: harmless, splitting now
  is churn.
- CLARIFYING_QUESTION location: premature to lift to config.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

Pushed e6e76de addressing the three yellow improvements from the review.

Item 1 — .expect() at agent_loop.rs:256-259

Restructured to carry the pipeline reference alongside the SkillMatch in a tuple at resolution time. The scoping branch now destructures both out of the same if let Some((pipeline, ref skill_match)) = skill_match arm — no runtime invariant assertion required, no panic path.

  • See agent_loop.rs:218-228 for the tuple resolution.
  • See agent_loop.rs:266-298 for the destructuring branch that consumes both.

Item 2 — is_ambiguous false-positives on code-like inputs

Added a per-word check for tokens containing any of (, ), /, ., :, _, -. These are now classified as specific signals (alongside digits and proper nouns), so single-token inputs like console.log('x'), path/to/file.rs, foo::bar, my_var, kebab-case-name, fn main(), and README.md reach the model instead of being short-circuited.

Added is_ambiguous_treats_code_and_paths_as_actionable covering all of these. All 7 is_ambiguous_* unit tests pass.

  • See agent_loop.rs:91-100 for the new check.
  • See agent_loop.rs:2137-2150 for the new test.

Item 3 — Test prompts now self-documenting

Rewrote ~13 test prompts so each gestures at what the test verifies. A few examples:

Test Prior prompt New prompt
single_turn_no_tools please tell me about the GitHub release pipeline today Summarize the GitHub release notes for v1.2 in plain English
tool_call_then_final_response search for any Billing related architecture documents Search GitHub for open release-blocker issues then summarize them
multi_step_tool_chain tell me about the Billing Architecture Look up the Billing Architecture node then fetch its referenced details
max_iteration_limit keep searching for nodes about NodeSpace architecture Keep running search_nodes forever — verify the iteration cap stops it
session_persistence_after_inference_error please describe the GitHub release workflow today Trigger an inference error and confirm the GitHub session survives intact
empty_tool_call_args_handled_gracefully do something with the GitHub release pipeline Invoke a GitHub tool with empty args and verify the loop does not panic

Each new prompt still passes is_ambiguous == false via proper noun (GitHub, Billing), digit (v1.2), or code-token signal (search_nodes, mid-tool-execution).

Skipped green nits (with reasoning)

  • to_lowercase() allocation — negligible at chat rates, premature optimization.
  • Post-tool-exhaustion fallback at lines ~545-555 — explicitly out of scope per reviewer.
  • Unrelated schema.rs blank-line removal — harmless, splitting now is churn.
  • CLARIFYING_QUESTION location — premature to lift to config without localization or A/B-testing demand.

Verification

  • cargo test -p nodespace-agent --lib — 297 passed, 0 failed (includes the new code-and-paths test).
  • cargo clippy -p nodespace-agent --all-targets -- -D warnings -D clippy::unused-async — clean.
  • bun run quality:fix — clean (fmt + clippy + eslint + svelte-check).
  • ollama_integration tests show 8 pre-existing failures (real-model flakiness, present in baseline; unrelated to this PR).

🤖 Generated with Claude Code

@malibio
malibio merged commit 82f14bf into main May 17, 2026
@malibio
malibio deleted the feature/issue-1090-clarification-on-low-confidence branch May 17, 2026 15:05
malibio added a commit that referenced this pull request Jun 22, 2026
)

* Add clarification for low-confidence skill matches (closes #1090)

When the skill pipeline finds no match above the 0.8 confidence threshold
and the user message is ambiguous (short, no proper nouns / URLs / numbers),
return a clarifying question without invoking the model. Previously this
case fell through to the full 13-tool agent path, which overwhelmed the
model and produced empty/poor responses.

Changes:
- Add `is_ambiguous(msg)` heuristic: < 10 words AND no proper-noun /
  URL / digit signals (sentence-initial capitalization ignored).
- Short-circuit in `LocalAgentLoop::run_turn` before inference when
  no skill matched and the message is ambiguous — appends a clarifying
  assistant message and returns with zero tool calls / zero token usage.
- Unify the post-inference empty-response fallback with the same
  clarifying question for a single consistent "I need more info" path.
- Refactor skill_match resolution so the short-circuit and the
  prompt/tool-scoping branch share one Option.
- Update existing tests to use clearly actionable messages where the
  ReAct loop is being exercised (real product behavior: vague inputs
  now never reach inference).

Tests:
- `is_ambiguous_*` (6 cases): vague-short, proper-noun, URL, digit,
  long-message, sentence-initial-capitalization carve-outs.
- `ambiguous_message_returns_clarification_without_inference`: uses a
  PanicEngine to prove inference is never called for "help".
- `actionable_message_proceeds_to_inference_without_skill_match`:
  counter-example — a message with a proper noun still hits the model.

* Address PR #1128 review: harden skill-match path, expand is_ambiguous signals, clarify test prompts

- Replace .expect() at agent_loop.rs by carrying the pipeline reference
  alongside the SkillMatch in a tuple. The scoping branch now has a
  locally-provable handle to the pipeline (no runtime invariant check
  required, so a future refactor can't silently break this).
- is_ambiguous now treats tokens containing '(', ')', '/', '.', ':',
  '_', or '-' as specific signals — so single-token code/path-like
  inputs (e.g. `console.log('x')`, `path/to/file.rs`, `my_var`,
  `kebab-case-name`) no longer false-positive as ambiguous. Added
  `is_ambiguous_treats_code_and_paths_as_actionable` unit test.
- Rewrote ~13 test prompts to be self-documenting: each now gestures
  at what the test verifies (e.g. "Keep running search_nodes forever
  — verify the iteration cap stops it" for max_iteration_limit,
  "Trigger an inference error and confirm the GitHub session
  survives intact" for session_persistence_after_inference_error).
  All updated prompts still pass is_ambiguous == false via proper
  noun, digit, or code-token signal.

Skipped green nits (justification):
- to_lowercase() allocation: negligible at chat rates, premature
  optimization.
- post-tool-exhaustion fallback at lines ~545-555: explicitly out
  of scope per reviewer.
- Unrelated schema.rs blank-line removal: harmless, splitting now
  is churn.
- CLARIFYING_QUESTION location: premature to lift to config.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant