Skip to content

Completes the context-complete tool path - #142

Merged
wpak-ai merged 4 commits into
cppalliance:mainfrom
jonathanMLDev:feat/server-context-phase-3
Jun 9, 2026
Merged

Completes the context-complete tool path#142
wpak-ai merged 4 commits into
cppalliance:mainfrom
jonathanMLDev:feat/server-context-phase-3

Conversation

@jonathanMLDev

@jonathanMLDev jonathanMLDev commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

PR body (paste below the title on GitHub)

Summary

Phase 3 completes the context-complete tool path: formatters and Alliance URL builtins use the injected ServerContext on the instance path, and new .context.test.ts / suggestion-flow.test.ts coverage exercises suggest-flow TTL, degradation, timeouts, and isolated-context URL enrichment without relying on process-default facades.

Issues addressed

Changes

  • formatSearchResultAsRow / formatQueryResultRows accept optional ctx and call ctx.generateUrlForNamespace() when enriching URLs
  • query, keyword_search, and guided_query pass ctx through to formatters
  • registerBuiltinUrlGenerators(ctx?, options?) registers per-context via WeakSet; setupAllianceServer passes the same ctx as tool registration
  • Overloads preserve legacy registerBuiltinUrlGenerators({ reinstallBuiltins: true }) call sites
  • isolateFromDefaultContext() test helper for phase 3 exit criterion
  • Branch coverage threshold raised from 58% to 65%

Acceptance criteria

#120

  • Formatter accepts ctx; tools pass ctx to formatters
  • registerBuiltinUrlGenerators(ctx?) + setupAllianceServer wiring
  • guided_query instance path uses ctx for client, cache, suggest-flow, URL enrichment
  • No new getDefaultServerContext() imports outside facade modules
  • Isolated integration test, zero default context (isolated-context.context.test.ts)
  • Branch scenarios: TTL, cache (existing), hybrid dense/sparse, rerank-skipped, timeout
  • New tests use createTestServerContext() / .context.test.ts, no facade mocks
  • Branch coverage ≥ 65% (measured 74.64%)

#138

  • Double suggest_query_params updates state, not duplicates
  • Re-suggest after expiry → query succeeds, no FLOW_GATE
  • guided_query does not block subsequent explicit suggest_query_params
  • Mode-conditional gating: disableSuggestFlow on query + count instance path
  • suggestion-flow.ts facade fully exercised (suggestion-flow.test.ts; file has no branch points in v8 report)

#133

  • format-query-result uses context-owned URL registry when ctx provided
  • guided-query delegates to ctx suggest-flow / cache / client on instance path
  • URL builtins register on context registry, not global latch
  • Legacy *.test.ts unchanged and still pass

Test plan

  • npm test — 207 tests pass
  • npm run test:coverage — branches 74.64% (gate 65%), suggestion-flow.ts 100% statements
  • npm run build — compiles cleanly
  • Phase 3 exit: guided_query + enrich_urls on isolated ServerContext, zero default context
  • Spot-check legacy CLI / setupAllianceServer default-context path unchanged (manual)

Notes for #133 reviewers

Dual-path facade imports in guided-query-tool.ts remain for the legacy no-ctx path. The instance path is fully context-driven. Legacy *.test.ts files still mock module facades by design; new .context.test.ts files cover the instance path without facade mocks.

Summary by CodeRabbit

  • New Features

    • Query results can be enriched using a specific server context for more accurate URLs
    • Formatting and search tools now use request/server context when shaping results
  • Bug Fixes

    • Degraded, hybrid-failure and degradation-reason fields now surface in query results
    • Improved timeout detection with clearer retry/timeout guidance
  • Tests

    • Expanded test coverage for suggestion flow, URL generators, and query/tool handlers

@jonathanMLDev jonathanMLDev self-assigned this Jun 8, 2026
@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 069c1dbb-d51b-42c5-8773-4e5543970016

📥 Commits

Reviewing files that changed from the base of the PR and between bedc79b and 29a4f96.

📒 Files selected for processing (9)
  • src/alliance/tools/guided-query-tool.context.test.ts
  • src/alliance/tools/isolated-context.context.test.ts
  • src/alliance/tools/suggest-query-params-tool.context.test.ts
  • src/alliance/url-builtins.context.test.ts
  • src/alliance/url-builtins.ts
  • src/core/server/server-context.test.ts
  • src/core/server/suggestion-flow.test.ts
  • src/core/server/tools/query-tool.context.test.ts
  • src/core/server/tools/test-helpers.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/alliance/url-builtins.context.test.ts
  • src/core/server/server-context.test.ts
  • src/alliance/tools/suggest-query-params-tool.context.test.ts
  • src/alliance/tools/isolated-context.context.test.ts
  • src/alliance/url-builtins.ts
  • src/core/server/tools/query-tool.context.test.ts
  • src/core/server/suggestion-flow.test.ts
  • src/alliance/tools/guided-query-tool.context.test.ts

📝 Walkthrough

Walkthrough

This PR threads ServerContext into URL builtins and query-result formatting, updates tool callers to pass ctx, and adds tests covering suggestion-flow (TTL, disable bypass), degradation/timeouts, and context isolation. Vitest branch coverage threshold increased to 65%.

Changes

ServerContext Threading and Test Coverage

Layer / File(s) Summary
ServerContext-aware URL builder registration
src/alliance/url-builtins.ts, src/alliance/setup.ts, src/alliance/url-builtins.context.test.ts
registerBuiltinUrlGenerators now accepts an overload with ctx: ServerContext; per-context registration tracked via WeakSet<ServerContext> plus separate default-context boolean; setup now registers builtins with the initialized ctx; tests verify per-context registration boundaries.
Query result formatting with context-aware URL enrichment
src/core/server/format-query-result.ts, src/core/server/tools/query-tool.ts, src/core/server/tools/keyword-search-tool.ts, src/alliance/tools/guided-query-tool.ts, src/core/server/format-query-result.context.test.ts
Introduces FormatQueryResultOptions with optional ctx; formatSearchResultAsRow and formatQueryResultRows prefer ctx.generateUrlForNamespace when ctx is provided; callers in query/keyword/guided-query now forward ctx; tests verify context-specific URL enrichment.
Suggestion-flow integration and TTL testing
src/core/server/suggestion-flow.test.ts, src/core/server/server-context.test.ts, src/core/server/tools/test-helpers.ts
New tests cover mark/require/reset suggestion-flow behavior, TTL expiry using fake timers, and disableSuggestFlow bypass; server-context tests restore real timers after teardown; isolateFromDefaultContext() helper clears the default context for isolated tests.
Query, count, and guided-query tool handler test coverage
src/core/server/tools/query-tool.context.test.ts, src/core/server/tools/count-tool.context.test.ts, src/alliance/tools/guided-query-tool.context.test.ts, src/alliance/tools/suggest-query-params-tool.context.test.ts, src/alliance/tools/isolated-context.context.test.ts
Adds tests for handler behavior with disableSuggestFlow, forwarding of rerank_skipped_reason, degradation_reason, hybrid_leg_failed, TIMEOUT error handling with retry suggestion, URL enrichment via registered builtins, suggest-flow re-suggest and expiry scenarios, and context isolation; introduces shared fixtures (namespaceMetadata, papersNamespaceClient) for consistency.
Coverage threshold adjustment
vitest.config.ts
Branch coverage threshold increased from 58 to 65.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • AuraMindNest
  • wpak-ai
  • whisper67265

Poem

🐰 A rabbit hops through context lands,
Threading state through helping hands—
Where URLs now ask "whose" registry true?
And timers tick in each context's view.
Tests bloom bright where branches grew,
Coverage climbs to sixty-five, it's true! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Completes the context-complete tool path' accurately and directly summarizes the main objective of this PR, which is completing Phase 3 of the ServerContext refactor by threading context through helper modules.
Linked Issues check ✅ Passed The PR fully addresses all three linked issues: #120 (5+ new test cases with 74.64% branch coverage exceeding 65% goal), #133 (ServerContext threaded through format-query-result, url-builtins, and guided-query), and #138 (suggest-flow edge case tests with comprehensive coverage).
Out of Scope Changes check ✅ Passed All changes are scoped to the three linked issues: context threading (format-query-result.ts, url-builtins.ts, guided-query.ts), test coverage (new .context.test.ts and suggestion-flow.test.ts files), and the coverage threshold bump aligns with #120's acceptance criteria.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
vitest.config.ts (1)

4-19: ⚡ Quick win

Threshold may be too conservative per documented policy.

The comment on lines 4–6 states that thresholds should sit "~2–3% below the last measured…totals" to catch meaningful regressions. However, if the measured branch coverage is 74.64% (per PR objectives), the documented policy would suggest a threshold of approximately 71–72%, not 65%.

The current 65% threshold creates a ~9.6 percentage point gap, allowing branch coverage to drop significantly before CI fails—potentially missing regressions the policy aims to catch.

Consider either:

  • Raising the threshold to ~71–72% to align with the documented policy, or
  • Updating the comment to explain why 65% was chosen (e.g., "Phase 3 milestone threshold; will incrementally raise to measured-minus-slack in future PRs").
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@vitest.config.ts` around lines 4 - 19, The branch coverage threshold in the
vitest config (test.coverage.thresholds.branches) is lower (65) than your
documented policy (~2–3% below measured 74.64%), so either raise
test.coverage.thresholds.branches to ~71–72 to match the policy or update the
nearby comment above defineConfig to justify the 65% "phase" choice; locate the
thresholds object (thresholds: { lines, statements, branches }) and modify the
branches value or the comment accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/alliance/url-builtins.ts`:
- Around line 83-89: isServerContext currently checks getConfig and
generateUrlForNamespace but not registerUrlGenerator, yet code later calls
registerUrlGenerator; strengthen the type guard by adding a function check for
(value as ServerContext).registerUrlGenerator so the guard verifies all methods
you actually call (getConfig, generateUrlForNamespace, registerUrlGenerator)
before narrowing to ServerContext. Update the isServerContext function to
include this additional typeof ... === 'function' check so partially-shaped
objects cannot pass and cause runtime errors.

In `@src/core/server/server-context.test.ts`:
- Around line 150-166: The test "requireSuggested returns expiry message after
TTL on instance context" enables fake timers with vi.useFakeTimers() but only
calls vi.useRealTimers() on the success path; wrap the fake-timer usage in a
try/finally (or add an afterEach that calls vi.useRealTimers()) so
vi.useRealTimers() is always executed even if assertions throw; modify the test
around the ServerContext instantiation/vi.advanceTimersByTime and calls to
ctx.requireSuggested to ensure vi.useRealTimers() is invoked in the finally
block (or configure a global afterEach) to prevent leaking fake timers to other
tests.

---

Nitpick comments:
In `@vitest.config.ts`:
- Around line 4-19: The branch coverage threshold in the vitest config
(test.coverage.thresholds.branches) is lower (65) than your documented policy
(~2–3% below measured 74.64%), so either raise test.coverage.thresholds.branches
to ~71–72 to match the policy or update the nearby comment above defineConfig to
justify the 65% "phase" choice; locate the thresholds object (thresholds: {
lines, statements, branches }) and modify the branches value or the comment
accordingly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4afcd158-3a43-45b1-bcc3-98156082a1e3

📥 Commits

Reviewing files that changed from the base of the PR and between 687a9a6 and bedc79b.

📒 Files selected for processing (17)
  • src/alliance/setup.ts
  • src/alliance/tools/guided-query-tool.context.test.ts
  • src/alliance/tools/guided-query-tool.ts
  • src/alliance/tools/isolated-context.context.test.ts
  • src/alliance/tools/suggest-query-params-tool.context.test.ts
  • src/alliance/url-builtins.context.test.ts
  • src/alliance/url-builtins.ts
  • src/core/server/format-query-result.context.test.ts
  • src/core/server/format-query-result.ts
  • src/core/server/server-context.test.ts
  • src/core/server/suggestion-flow.test.ts
  • src/core/server/tools/count-tool.context.test.ts
  • src/core/server/tools/keyword-search-tool.ts
  • src/core/server/tools/query-tool.context.test.ts
  • src/core/server/tools/query-tool.ts
  • src/core/server/tools/test-helpers.ts
  • vitest.config.ts

Comment thread src/alliance/url-builtins.ts
Comment thread src/core/server/server-context.test.ts
@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.17647% with 3 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@687a9a6). Learn more about missing BASE report.

Files with missing lines Patch % Lines
src/alliance/url-builtins.ts 89.28% 3 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main     #142   +/-   ##
=======================================
  Coverage        ?   85.95%           
=======================================
  Files           ?       39           
  Lines           ?     1445           
  Branches        ?      485           
=======================================
  Hits            ?     1242           
  Misses          ?      201           
  Partials        ?        2           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Comment thread src/core/server/tools/test-helpers.ts Outdated
@jonathanMLDev
jonathanMLDev requested a review from wpak-ai June 9, 2026 14:35
@wpak-ai
wpak-ai merged commit 09efc3c into cppalliance:main Jun 9, 2026
12 checks passed
@jonathanMLDev
jonathanMLDev deleted the feat/server-context-phase-3 branch June 22, 2026 18:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants