Skip to content

Log every retrieved skill's score, not just the winner's - #2529

Merged
malibio merged 2 commits into
mainfrom
issue-2276-skill-retrieval-investigation
Sep 9, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2276-skill-retrieval-investigation

Conversation

@malibio

@malibio malibio commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

Investigation for #2276 (skill retrieval / routing safety). Full findings posted as a comment on the issue: #2276 (comment)

The short version: this issue's measurements were taken at d393ad19, but the destructive-tool-leak defect it describes (delete_node offered on turns with no deletion intent) was already fixed before that commit, by b5c892b0 (#2244/#2240) — an ancestor of d393ad19. Since then, ADR-038's two-stage routing pipeline (packages/agent/src/local_agent/routing.rs) has landed in full: risk-tiered score bars (read/mutating/destructive), destructive tools scoped to only the retrieval winner, a structural test requiring every write tool to have ≥2 owning skills (so a retrieval miss on one skill degrades rather than strands the turn), and --runs/pass^k repetition in the eval runner for exactly the "is this routing flip stable across reps" check the issue asks for.

Almost every acceptance criterion in #2276 is already satisfied by work already on main. The one real, mechanical gap: route() (agent_loop.rs) and find_skills (skill_ops.rs) logged only the winning candidate's score (top_score), never the full set of retrieved candidates' scores. That makes two different failure modes indistinguishable from ordinary logs:

  • A tiebreak — the runner-up scored 0.81 against the winner's 0.82.
  • A skill scoring badly on its own core use case (0.3, no close competitor) — a description problem, not a ranking problem.

This PR adds that missing piece:

  • routing::all_candidate_scores — every retrieved candidate's name and score, unfiltered by the score gate (unlike the existing routed_skill_names, which only lists gate-clearing candidates).
  • Wired into agent_loop::route()'s "two-stage routing overhead" log line as all_scores.
  • The equivalent all_scores field added to find_skills's "find_skills executed" log line in skill_ops.rs, for the same reason on that path.

Test plan

  • cargo test -p nodespace-agent --lib local_agent::routing — 64 passed, including 2 new tests for all_candidate_scores
  • cargo test -p nodespace-core --lib ops::skill_ops — 24 passed
  • cargo build -p nodespace-agent -p nodespace-core — clean
  • bun run quality:fix — no issues (clippy, eslint, svelte-check, tsc all clean)
  • bun run test:all — full suite green, no new failures vs. baseline (4929 frontend tests + full Rust workspace)
  • Pre-push gate (test:all + cargo build --bin nodespaced + e2e) passed

🤖 Generated with Claude Code

Investigation into #2276 found the bulk of its acceptance criteria
already satisfied by ADR-038's two-stage routing (risk-tiered score
bars, destructive-tool winner-only scoping, structural write-tool
redundancy, pass^k repetition in the eval runner). The one real gap:
`route()` and `find_skills` logged only the winning candidate's score,
so a tiebreak (a near-tied runner-up) was indistinguishable from a
skill scoring badly on its own core use case with no close competitor
— two different defects needing different fixes.

Adds `routing::all_candidate_scores`, unfiltered by the score gate, and
wires it into both log sites alongside the existing top_score/
routed_skills fields.

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

malibio commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2529

Review Type: Initial Review (no prior review comments found)

Requirements Check

This PR targets exactly one item from issue #2276's acceptance criteria: "Per-skill retrieval scores observable for a turn" — the issue's own "prerequisite for any of them" section, which explicitly calls for logging every skill's score, not just top_score, to distinguish a tiebreak (two close scores) from a skill scoring badly in isolation.

  • ✅ Criterion met. routing::all_candidate_scores (packages/agent/src/local_agent/routing.rs:394) renders every retrieved candidate's name=score, unfiltered by clears_score_gate — verified by diffing its implementation against routed_skill_names (routing.rs:370), which is identical except for the .filter(|c| clears_score_gate(c)) step. The omission is real, not just asserted in a doc comment.
  • ✅ Both call sites wire the field correctly: agent_loop.rs:3170 passes &outcome.candidates (the same slice passed to routed_skill_names one line above) into all_scores = %routing::all_candidate_scores(...); skill_ops.rs builds all_scores from skill_results (the same tuple vec top_score and the skills JSON are built from, skill_ops.rs:376-380) and logs it as all_scores = %all_scores in the same tracing::info! call as top_score. No stale variables, no shadowing.
  • ✅ Ordering claim verified: agent_loop.rs:3131 explicitly sort_bys merged descending by score before assigning to outcome.candidates, so the "preserves retrieval's score-descending order" doc comment on all_candidate_scores (routing.rs:391) is accurate, not aspirational.
  • ✅ The PR's claim that the other acceptance criteria of Investigate how skills are surfaced to a turn: retrieval can make a turn unwinnable #2276 were already satisfied by ADR-038's routing work (risk-tiered score bars via score_bar_for/clears_score_gate, destructive-tool winner-only scoping via stage2_tools/destructive_tools_withheld) is consistent with what's actually in routing.rs today — clears_score_gate checks destructive-tier bars most-restrictive-first, and stage2_tools/destructive_candidates_below_bar exist and are exercised by tests. I did not attempt to re-verify every remaining Investigate how skills are surfaced to a turn: retrieval can make a turn unwinnable #2276 criterion (repeated-rep stability, scenario 6/13 re-verification) end-to-end — that's investigation/measurement work already reported separately per the PR description, and out of scope for re-litigating in this mechanical-logging PR.
  • Scope is appropriately atomic: this PR does not attempt options A/B/C/D from Investigate how skills are surfaced to a turn: retrieval can make a turn unwinnable #2276 (always-on tools, structured intent, etc.) — correctly deferred as separate decisions pending the observability this PR adds.

Code Review Findings

Critical Issues

None.

Suggested Improvements

  • 🟡 packages/agent/src/local_agent/agent_loop.rs:3170 / packages/core/src/ops/skill_ops.rs:391 — tracing::info! field arguments (including all_candidate_scores(&outcome.candidates) and the all_scores local) are evaluated eagerly as ordinary function-call arguments before the macro decides whether the info level is enabled. This means every route() call and every find_skills call now does an extra O(n) allocation-and-format pass even when info-level tracing is filtered out. This is a real, common tracing pitfall — but it is not a regression introduced by this PR: the adjacent routed_skills = %routing::routed_skill_names(...) field already pays the identical cost at the same call sites. Given candidate lists are capped at RETRIEVAL_TOP_K (small, single-digit) and MAX_SKILL_LIMIT (≤10), the actual per-call cost is negligible; flagging for awareness rather than blocking. If this ever becomes worth addressing, it'd be a follow-up refactor of both fields together (e.g. wrapping in tracing::enabled!(Level::INFO) or a lazy field::debug), not something to bolt onto just the new field.

Nitpicks

  • Nit: packages/agent/src/local_agent/routing.rs:394 and packages/core/src/ops/skill_ops.rs:388-391 — the formatting logic (format!("{}={:.3}", name, score) joined with ", ") is duplicated across the two crates rather than shared. This is defensible as-is: agent and core are separate crates with separate candidate/result types (SkillCandidate vs (Node, f32) tuples), so sharing would require either a new shared trait/type or a dependency direction that doesn't currently exist. Not worth the abstraction for two ~5-line call sites: correctly judged as YAGNI-appropriate for a small PR, per the doc comments' own cross-references pointing each implementation at its sibling for context. Not a blocker.
  • Nit: No test explicitly exercises a duplicate-name-in-candidates case for all_candidate_scores (e.g. two candidates with the same name but different scores/ids). Extremely unlikely in practice (skill names are effectively unique by convention) and low value to add given the two existing tests already cover the two behaviors that matter (unfiltered-by-gate inclusion, empty-list formatting).
  • Nit: Very large candidate lists aren't a real concern here — both call sites truncate to small bounds (RETRIEVAL_TOP_K, MAX_SKILL_LIMIT ≤ 10) before this function runs, so log-line bloat isn't reachable in practice.

Test Coverage

Two new unit tests in routing.rs:

  • all_candidate_scores_includes_every_candidate_regardless_of_the_gate — includes a candidate (Below The Bar, score 0.01) that would fail every score bar in clears_score_gate, and asserts it still appears in the output. This directly tests the unfiltered behavior that is the entire point of the function, not just formatting.
  • all_candidate_scores_is_empty_when_retrieval_returned_nothing — covers the empty-list edge case.

Both are well-isolated (no external state, pure function over a constructed Vec<SkillCandidate>). No equivalent new test was added in skill_ops.rs for the all_scores local there, since it's a straightforward inline .map().join() over data already covered by existing find_skills tests — reasonable given the logic is a 4-line direct mirror of the already-tested routing.rs function.

Verified locally:

  • cargo test -p nodespace-agent --lib local_agent::routing::tests::all_candidate_scores → 2 passed
  • cargo test -p nodespace-core --lib ops::skill_ops → 24 passed
  • No GitHub Actions CI configured on this repo (gh pr checks 2529 reports no checks) — consistent with this project's local-pre-push-gate-only CI model. The PR description attests the full test:all (4929 frontend + full Rust workspace) and pre-push gate (test:all + cargo build --bin nodespaced + e2e) already passed before push.
  • Did not re-run the full workspace test:all in this review (multi-minute cold build); the targeted new tests plus the PR's own attested full-suite run are sufficient evidence for a change of this size and blast radius (pure logging addition, no behavior change to routing decisions).

Security & Performance

  • Security: Skill names/descriptions originate from internal skill-registry nodes (system-seeded or user-authored via create_schema/skill creation flows), not arbitrary end-user request bodies. routed_skill_names already logs these same names unfiltered today; all_candidate_scores doesn't introduce a new class of untrusted input into logs. No escaping/injection concern beyond what already exists.
  • Performance: See the 🟡 above — real but pre-existing pattern, negligible given small, already-capped candidate-list sizes at both call sites.

Style/Consistency

New code matches routing.rs conventions closely: same doc-comment structure as routed_skill_names (explains the log field name, the reasoning as a comparison against the winner-only field it complements, and a note on why order/format was chosen), same .iter().map().collect::<Vec<_>>().join(", ") idiom, same placement (directly after the function it's meant to be read alongside). skill_ops.rs's version cross-references the routing.rs version by fully-qualified path in its comment, which is a nice touch for a reader who only has one file open.

Recommendation: APPROVE

Small, correctly-scoped, mechanical observability addition that does exactly what issue #2276 asked for as a prerequisite. The "unfiltered by score gate" distinction — the entire reason this function exists rather than just reusing routed_skill_names — is verified correct both by code comparison and by a test that specifically exercises a below-bar candidate. No security, correctness, or architectural concerns. The one performance note (eager field evaluation in tracing::info!) is a pre-existing pattern shared with the adjacent routed_skills field, not something this PR should be blocked on introducing.

@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.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Small, well-scoped observability follow-up from the #2276 investigation. It adds an all_candidate_scores helper in routing.rs and wires an all_scores log field into both retrieval log sites (agent_loop.rs's Stage-2 route() and skill_ops.rs's find_skills). The change is additive-only (new field alongside existing ones), narrowly targeted, and directly satisfies acceptance criterion 1 of #2276 ("Per-skill retrieval scores observable for a turn"). Verified the diff builds clean, cargo clippy -p nodespace-agent --lib is warning-free, cargo fmt --check is clean on both touched crates, and the two new unit tests pass. This is a net positive and low-risk; no blocking issues found.

Findings

Critical Issues

None.

Suggested Improvements

  • packages/core/src/ops/skill_ops.rs:387-391: The all_scores construction here duplicates the exact formatting logic (format!("{}={:.3}", name, score), comma-joined) that all_candidate_scores in routing.rs already implements and unit-tests. Since core cannot depend on agent (dependency direction goes the other way — agent is presumably the consumer of core), a shared helper isn't trivially available across the crate boundary here, so the duplication is understandable rather than careless. If a shared nodespace-core-side (or a lower, shared utility crate) location for this formatting exists or is easy to introduce, consider hoisting it to avoid the two implementations drifting (e.g., one changes its float precision and the other doesn't). Not a blocker given the current crate layout — flagging for awareness now while the duplication is small (one line, two call sites) rather than after a third copy appears.

  • packages/core/src/ops/skill_ops.rs: No test asserts on the new all_scores field's content (e.g., that a below-threshold-would-be-filtered candidate still appears, mirroring the routing.rs all_candidate_scores_includes_every_candidate_regardless_of_the_gate test's intent). I checked, and this is consistent with existing convention — find_skills's tracing::info! line has no dedicated test for top_score either, so this isn't a regression in test discipline the PR introduces. Still, since the whole point of this field is to make gate-filtered candidates visible (per the Investigate how skills are surfaced to a turn: retrieval can make a turn unwinnable #2276 investigation), a short test asserting the skill_ops.rs copy also includes below-threshold results would directly de-risk against the two implementations silently diverging (e.g., if skill_ops.rs's were ever accidentally reordered before .truncate(limit), or filtered before formatting). Suggested rather than required, since the underlying logic is a one-line iterator map already covered in spirit by the routing.rs tests.

Nitpicks

  • Nit: packages/agent/src/local_agent/routing.rs:394-400 / packages/core/src/ops/skill_ops.rs:387-391: Skill names are free text (e.g., "Research & Search") and are joined with , without escaping. If a skill name ever legitimately contained a literal comma, the log line would be ambiguous to a scraper splitting on , . This mirrors the pre-existing routed_skill_names convention exactly (same doc comment even calls out that the scraper "parses to end of line" and shape is a contract), so it's not a new risk introduced by this PR — just noting the same latent fragility now exists in two log fields instead of one. No action needed unless skill naming conventions change.

  • Nit: packages/agent/src/local_agent/agent_loop.rs:3160-3165: The new doc comment block above the tracing::info! call is fairly long (6 lines) relative to the one-line field addition it explains. It's good "why" documentation per the file's existing style (the surrounding comments are similarly dense), but consider whether a shorter comment pointing to all_candidate_scores's own doc comment (which already carries the full rationale) would suffice, since the rationale is now stated in full in two places (routing.rs's doc comment and this one). Purely stylistic — the existing file already leans toward this level of inline explanation, so this is consistent with local convention rather than an outlier.

Verification performed

  • git diff origin/main...HEAD reviewed in full (3 files, ~65 lines).
  • cargo test -p nodespace-agent --lib routing::tests::all_candidate_scores — both new tests pass.
  • cargo clippy -p nodespace-agent --lib — clean.
  • cargo fmt -p nodespace-agent -- --check and cargo fmt -p nodespace-core -- --check — clean.
  • Confirmed node.content (used in skill_ops.rs's new all_scores line) matches the existing convention at line 370 ("name": node.content) for skill display name.
  • Confirmed SkillCandidate.score is f32 and .name is String, matching the {:.3} formatting used.
  • Confirmed this satisfies Investigate how skills are surfaced to a turn: retrieval can make a turn unwinnable #2276 acceptance criterion 1 ("Per-skill retrieval scores observable for a turn") — every retrieved candidate's score is now logged at both retrieval call sites, unfiltered by the score gate, which is exactly what's needed to distinguish a tiebreak from a lone low scorer per the issue's stated prerequisite.

Recommendation: APPROVE. The two "Suggested Improvements" are worth a follow-up look but do not block this narrow, well-tested, net-positive change.

@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.

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval on this self-authored PR). Full findings in the review comment above.

Both PR #2529 reviews suggested a dedicated test for the all_scores
field's unfiltered-by-threshold behavior in skill_ops.rs, mirroring
the existing coverage on routing.rs's all_candidate_scores. Extracted
the inline formatting into format_all_scores so it's testable without
find_skills's live NodeService/NodeEmbeddingService dependencies, and
added two tests: inclusion of a low-scoring result, and empty input.

Other review suggestions (eager tracing::info! field evaluation,
duplicated formatting logic across the agent/core crate boundary,
comma-escaping in skill names, doc comment length) were left as-is —
all pre-existing patterns already shared by the adjacent
routed_skills field, not regressions this PR introduces, and not
worth new abstraction for two five-line call sites.

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

malibio commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary

Both reviews reached APPROVE with zero critical findings. Triaged the suggestions:

Addressed:

  • Added dedicated test coverage for skill_ops.rs's all_scores formatting (both reviews flagged this as the one gap worth closing): extracted the inline formatting into format_all_scores, now independently testable without find_skills's live NodeService/NodeEmbeddingService dependencies. Added format_all_scores_includes_a_low_scoring_result_a_threshold_would_filter and format_all_scores_is_empty_when_retrieval_returned_nothing, mirroring routing.rs's existing all_candidate_scores test pattern.

Skipped (with reasoning):

  • 🟡 Eager tracing::info! field evaluation cost — pre-existing pattern already shared by the adjacent routed_skills/routed_skill_names field at both call sites; not a regression this PR introduces, and negligible given candidate lists are capped at RETRIEVAL_TOP_K/MAX_SKILL_LIMIT (≤10).
  • Duplicated formatting logic between agent/core crates — both reviews independently judged this as YAGNI-appropriate given the crate dependency direction (core cannot depend on agent) and the small size (2 five-line call sites). Revisit if a third copy appears.
  • Comma-escaping fragility in skill names — pre-existing pattern identical to routed_skill_names's own documented tradeoff; not new risk.
  • Doc comment length in agent_loop.rs — consistent with the file's existing documentation density; stylistic only.
  • No test for duplicate-name candidates — extremely unlikely given skill-naming conventions, low value.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The only change made was additive test coverage plus an extract-function refactor with no behavior change (the formatting logic is byte-for-byte identical to what was inline before, just now named and testable). All 26 skill_ops tests pass, quality:fix is clean, and the full test:all suite is green with no new failures. This is exactly the "trivial, low-risk, straightforward" case the address-review process itself defines as not needing another review pass.

@malibio
malibio merged commit c635f8c into main Sep 9, 2026
@malibio
malibio deleted the issue-2276-skill-retrieval-investigation branch September 9, 2026 08:35
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