Skip to content

feat(flare-docs): npm/TypeScript ecosystem support; rename tool to docs - #342

Merged
getappz merged 2 commits into
masterfrom
task/373
Jul 26, 2026
Merged

feat(flare-docs): npm/TypeScript ecosystem support; rename tool to docs#342
getappz merged 2 commits into
masterfrom
task/373

Conversation

@getappz

@getappz getappz commented Jul 26, 2026

Copy link
Copy Markdown
Owner

Closes agentflare item #373.

Adds npm package documentation to flare-docs alongside the existing docs.rs path, and renames the MCP tool flare_docsdocs (mcp__flare__docs).

Why

flare_docs only knew about Rust crates, so any non-Rust project got nothing. npm has no docs.rs equivalent — nobody publishes machine-readable API docs per package — so the API surface has to be derived from what packages do ship: their TypeScript declarations.

Why tree-sitter and not deno_doc

deno doc --json npm:<pkg> looked like the obvious answer, and a spike confirmed the output shape is a good match for our existing store. Using the deno_doc crate is not, and the numbers are why:

route net-new crates binary module resolution
deno_doc + deno_graph 100 +4.78 MB ✗ caller writes it
tree-sitter (this PR) 4 small ✗ caller writes it
deno doc CLI subprocess 0 35 MB external binary ✓ free

The decisive part is the last column. A probe built from deno's own examples/ddoc shape parses a self-contained .d.ts fine but panics on any multi-file package:

Resolve("Failed resolving '../../hono' from '.../adapter/aws-lambda/handler.d.ts'")

Node-style resolution (extension probing, exports maps, node_modules layout) lives in the deno CLI, not the crate. So deno_doc costs 25× the dependencies and still leaves the hard part to us. Since a .d.ts is fully explicit — every type written out, nothing inferred — a syntactic pass recovers the same surface.

flate2/tar were already vendored, so the tarball path adds nothing.

Design notes

Fetching the whole tarball (rather than file-by-file over unpkg) is deliberate: it's one request per package, and it turns export * from './x' into a local path probe instead of a network round trip.

Ecosystem is an enum, not a trait — two variants, dispatch happens once per request, and the fetch protocols differ enough (one zstd JSON document vs. a manifest plus a tarball) that a shared trait would be a lowest-common-denominator abstraction over two genuinely different things.

Back-compat: omitting ecosystem still means Rust, so every existing call is unaffected. Scoped names (@scope/pkg) infer npm. rule_text::FLARE_DOCS_SUPERSEDED now carries the pre-rename rule body so agentflare init replaces installed rules pointing at the old tool name.

Three things real packages forced that fixtures didn't

An integration test runs over real published tarballs (fixtures in gitignored .refs/npm/; tests skip when absent). It caught all three:

  1. Declaration files spell members differently. .d.ts uses method_signature / property_signature / public_field_definition; implementation files use method_definition. A query written for .ts matches nothing inside a .d.ts class body — every class collapses to one opaque node.
  2. statement_block is the body of both a function and a namespace. Treating it uniformly as an execution scope silently drops all namespace members.
  3. DefinitelyTyped packages have no export keyword at all. They use ambient declare function e() / declare namespace e { var json } plus a trailing export = e. An export-statement-only reachability check discards their entire API — exactly the packages the @types fallback exists to serve. express went from 1 → 32 indexed items once fixed.

Verification

  • cargo test --workspace1495 passed, 0 failed
  • cargo fmt --all — clean
  • clippy — zero findings in any changed file. Note --workspace -D warnings fails on master independently of this PR: five files (agents.rs, gateway_secrets.rs, github/identity.rs, mcp_server/tests/asset_tests.rs, paths.rs) carry pre-existing unsafe_code lints.
  • Live, against the real registries:
    docs refresh hono --version 4.6.3 --ecosystem npm
    docs search "render JSON Content-Type application/json"   → npm/hono/4.6.3/item/Context.json
    docs refresh express --version 4.18.2 --ecosystem npm     → "types from: @types/express (DefinitelyTyped)", 32 items
    
  • Real tarballs: zod 965 items (ships ~0% TSDoc — every one still carries a signature, including .email()), hono >100 members.

Not in scope

JSR. The seam is in place and the extractor query already covers .ts implementation nodes, so it's an addition rather than a rewrite.

Summary by CodeRabbit

  • New Features
    • Added npm documentation support with TypeScript .d.ts extraction (plus DefinitelyTyped fallback when bundled types are missing).
    • Added ecosystem selection for CLI and docs requests (Rust vs npm), including scoped-name inference.
    • Added MCP docs tool updates with ecosystem-aware routing and cache handling.
  • Improvements
    • Improved “not found”/error hints to suggest the other ecosystem.
    • FetchOutcome is now surfaced from the crate root for consistent indexing results.
  • Bug Fixes
    • HTTP 404s are now treated as explicit “not found”.
    • Refresh now properly removes stale indexed items on refetch.
  • Tests
    • Added end-to-end npm extraction coverage with real fixture packages.

…ocs`

Adds npm package documentation alongside the existing docs.rs path, indexed
per exported symbol so search returns the one signature an agent needs rather
than a whole README.

The MCP tool is renamed `flare_docs` -> `docs` (`mcp__flare__docs`). Omitting
`ecosystem` still means Rust, so every call written before this keeps working;
scoped names (`@scope/pkg`) infer npm.

Extraction is tree-sitter over the package's TypeScript declaration files, not
deno_doc. Measured, deno_doc + deno_graph costs 100 net-new crates and +4.78 MB
of binary, and still leaves Node module resolution to the caller -- a probe
built from deno's own examples/ddoc panics with
`Resolve("Failed resolving '../../hono'")` on any multi-file package. This route
costs 4 crates (flate2/tar were already vendored). A .d.ts is fully explicit, so
there is no inference a type-checker would add.

Packages are fetched as a whole tarball rather than file-by-file, which turns
`export * from './x'` into a local path probe instead of a network round trip.

Three things real packages forced that synthetic fixtures did not:

- Declaration files spell members `method_signature` / `property_signature` /
  `public_field_definition`; a query written against implementation files
  (`method_definition`) matches nothing inside a .d.ts class body.
- `statement_block` is the body of both a function and a namespace, so
  namespace members need distinguishing by parent kind or they are dropped.
- DefinitelyTyped packages use ambient `declare` plus a trailing `export = x`
  with no `export` keyword anywhere, so an export-statement-only reachability
  check discards their entire API -- exactly the packages the @types fallback
  exists to serve. express went from 1 to 32 indexed items once fixed.

Verified: 1495 workspace tests pass; live fetches index hono per symbol and
resolve express through @types/express.
@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds npm package documentation support through manifest and tarball processing, TypeScript API extraction, storage reconciliation, ecosystem-aware cache paths, and CLI/MCP routing while retaining Rust documentation behavior.

Changes

Npm documentation integration

Layer / File(s) Summary
Ecosystem and shared result contracts
crates/flare-docs/src/ecosystem.rs, crates/flare-docs/src/lib.rs, crates/flare-docs/src/rustdoc.rs
Defines Rust/npm resolution, ecosystem-specific cache paths, and the shared FetchOutcome contract while preserving rustdoc exports.
Npm declaration and archive processing
crates/flare-docs/Cargo.toml, crates/flare-docs/src/npm/extract.rs, crates/flare-docs/src/npm/fetch.rs, crates/flare-docs/tests/npm_real_package.rs
Adds archive and parser dependencies, extracts exported TypeScript API items, parses npm manifests, retrieves declaration files, and validates extraction behavior.
Npm fetch and store pipeline
crates/flare-docs/src/npm/mod.rs, crates/flare-docs/src/fetch.rs
Fetches bundled or DefinitelyTyped declarations, stores package overviews, indexes exported items, reconciles removed exports, and distinguishes missing resources from other fetch failures.
Ecosystem-aware CLI and MCP routing
src/cli/docs.rs, src/mcp_server/flare_docs.rs, src/mcp_server/types.rs, src/mcp_server.rs, src/rule_text.rs
Adds ecosystem selection to CLI and MCP requests, routes Rust/npm fetches, updates cache and error handling, renames the MCP tool, and updates rule text.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant DocsTool
  participant Ecosystem
  participant NpmRegistry
  participant DocsStore

  Client->>DocsTool: Request package documentation
  DocsTool->>Ecosystem: Resolve registry
  Ecosystem-->>DocsTool: Return Rust or Npm
  DocsTool->>DocsStore: Check ecosystem-specific cache path
  DocsTool->>NpmRegistry: Fetch manifest and tarball
  NpmRegistry-->>DocsTool: Return package metadata and declarations
  DocsTool->>DocsStore: Store overview and reconciled API items
  DocsStore-->>Client: Return documentation result
Loading

Possibly related PRs

  • getappz/agentflare#316: Established the CLI/MCP documentation fetch and store flow extended here with ecosystem routing.
  • getappz/agentflare#325: Updated the documentation rule text and MCP tool target touched by this change.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the PR purpose and verification, but it does not follow the required template sections or include an explicit test plan checklist. Add the required Summary, Test plan checklist, and Notes for reviewers sections, and include the missing risk areas/backwards compatibility details.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: npm/TypeScript ecosystem support and the MCP tool rename.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch task/373

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

@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 (3)
crates/flare-docs/src/npm/mod.rs (1)

1-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Doc comment overstates scope: no JSR support exists in this ecosystem.

The header says "npm (and, by extension, JSR) ecosystem support," but Ecosystem (crates/flare-docs/src/ecosystem.rs) only has Rust/Npm variants, and the PR objectives explicitly note JSR support isn't included. If the intent is "JSR packages that are also mirrored to npm happen to work via this path," consider wording it that way to avoid implying dedicated JSR handling exists.

🤖 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 `@crates/flare-docs/src/npm/mod.rs` around lines 1 - 9, Update the module-level
documentation in the npm module to remove the claim of direct JSR ecosystem
support. Describe this as npm support only, or clarify that JSR packages may
work only when mirrored through npm, while leaving the fetch_package and
store_package API description unchanged.
src/cli/docs.rs (1)

34-36: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Refresh's --ecosystem help text drops the defaulting explanation.

Get's help text (Lines 22-25) explains "Defaults to rust; scoped names (@scope/pkg) imply npm," but Refresh's doesn't, even though the same resolve_ecosystem defaulting logic applies to both. A user running --help on refresh won't see this.

📝 Proposed fix
         /// Registry to look the package up in: rust (docs.rs) or npm.
+        /// Defaults to rust; scoped names (`@scope/pkg`) imply npm.
         #[arg(long, short = 'e')]
         ecosystem: Option<String>,
🤖 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 `@src/cli/docs.rs` around lines 34 - 36, Update the `Refresh` command’s
`ecosystem` argument help text in `src/cli/docs.rs` to match `Get`’s
explanation: state that it defaults to rust and that scoped package names
(`@scope/pkg`) imply npm, while preserving the existing registry description.
src/mcp_server/flare_docs.rs (1)

115-173: 🩺 Stability & Availability | 🔵 Trivial

Timed-out blocking fetches keep running in the background.

tokio::time::timeout around spawn_blocking returns early on timeout, but the underlying blocking task isn't cancelled — a timed-out npm fetch (manifest → possibly @types manifest → tarball, all sequential per the docstring) keeps occupying a blocking-pool thread and outbound connection until it eventually finishes or errors on its own. Under repeated timeouts (e.g. a slow/unreachable registry) this can gradually exhaust the blocking thread pool. Worth keeping in mind for the timeout value and blocking-pool sizing; no change needed if this is already an accepted tradeoff.

🤖 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 `@src/mcp_server/flare_docs.rs` around lines 115 - 173, Update blocking_fetch
to account for spawn_blocking tasks continuing after FETCH_TIMEOUT; avoid
relying on tokio::time::timeout as cancellation, and ensure timed-out registry
work cannot indefinitely occupy the blocking pool or outbound connections.
Preserve the existing timeout error and panic/fetch error reporting behavior.
🤖 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 `@crates/flare-docs/src/npm/extract.rs`:
- Around line 297-322: Update relative_imports to parse import/export
declarations across line boundaries instead of requiring the declaration keyword
and from clause on the same line. Preserve detection of quoted relative
specifiers, deduplication, and skipping non-import/export content while handling
formatted multiline named imports and exports.

In `@crates/flare-docs/src/npm/mod.rs`:
- Around line 64-76: Update the DefinitelyTyped fallback in the manifest-loading
flow to preserve the underlying error from fetcher.fetch instead of mapping
every failure to NpmFetchError::NoTypes. Keep genuine missing-types handling
distinct from transport, timeout, DNS, and other fetch failures, while retaining
the existing types_package_name and manifest parsing flow.

---

Nitpick comments:
In `@crates/flare-docs/src/npm/mod.rs`:
- Around line 1-9: Update the module-level documentation in the npm module to
remove the claim of direct JSR ecosystem support. Describe this as npm support
only, or clarify that JSR packages may work only when mirrored through npm,
while leaving the fetch_package and store_package API description unchanged.

In `@src/cli/docs.rs`:
- Around line 34-36: Update the `Refresh` command’s `ecosystem` argument help
text in `src/cli/docs.rs` to match `Get`’s explanation: state that it defaults
to rust and that scoped package names (`@scope/pkg`) imply npm, while preserving
the existing registry description.

In `@src/mcp_server/flare_docs.rs`:
- Around line 115-173: Update blocking_fetch to account for spawn_blocking tasks
continuing after FETCH_TIMEOUT; avoid relying on tokio::time::timeout as
cancellation, and ensure timed-out registry work cannot indefinitely occupy the
blocking pool or outbound connections. Preserve the existing timeout error and
panic/fetch error reporting behavior.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 727d6b1e-579e-42d9-9e8a-a6e03a85a6ce

📥 Commits

Reviewing files that changed from the base of the PR and between d8f5165 and 85cb280.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • crates/flare-docs/Cargo.toml
  • crates/flare-docs/src/ecosystem.rs
  • crates/flare-docs/src/lib.rs
  • crates/flare-docs/src/npm/extract.rs
  • crates/flare-docs/src/npm/fetch.rs
  • crates/flare-docs/src/npm/mod.rs
  • crates/flare-docs/src/rustdoc.rs
  • crates/flare-docs/tests/npm_real_package.rs
  • src/cli/docs.rs
  • src/mcp_server.rs
  • src/mcp_server/flare_docs.rs
  • src/mcp_server/types.rs
  • src/rule_text.rs

Comment thread crates/flare-docs/src/npm/extract.rs
Comment thread crates/flare-docs/src/npm/mod.rs
…ookup

Two CodeRabbit findings on #342.

The DefinitelyTyped fallback mapped every fetch failure to NoTypes, so a
timeout, DNS failure, or rate limit was reported as "this package ships
no TypeScript types" -- sending a caller to diagnose the wrong thing on
a retryable blip. FetchError gains a NotFound variant, returned only for
a 404, and the fallback maps just that to NoTypes while propagating
everything else as itself.

relative_imports scanned line by line, so a named import whose specifier
list wraps -- the shape formatters produce -- put  on a line that
did not start with import/export and was skipped entirely. Wrapped lines
now accumulate into one logical statement, keeping the keyword anchor so
prose in doc comments still cannot masquerade as an import.

The helper has no production caller yet, so this is a latent bug rather
than a live one; fixing beats deleting because whoever wires it up next
inherits a correct parser instead of a silently lossy one.

@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: 1

🤖 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 `@crates/flare-docs/src/fetch.rs`:
- Around line 86-88: Update the fetch error mapping around the
`call().map_err(...)` expression to detect `ureq::Error::Status(404, _)` and
return `FetchError::NotFound` directly, while preserving existing HTTP error
handling for other failures. Ensure the later status-based `NpmError::NoTypes`
mapping remains reachable for missing packages.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 0c504d70-f7e2-4a1a-9a25-9a3bb806529e

📥 Commits

Reviewing files that changed from the base of the PR and between 85cb280 and 65ba4f6.

📒 Files selected for processing (3)
  • crates/flare-docs/src/fetch.rs
  • crates/flare-docs/src/npm/extract.rs
  • crates/flare-docs/src/npm/mod.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/flare-docs/src/npm/extract.rs
  • crates/flare-docs/src/npm/mod.rs

Comment on lines +86 to +88
if status == 404 {
return Err(FetchError::NotFound);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

set -euo pipefail

sed -n '1,180p' crates/flare-docs/src/fetch.rs

Repository: getappz/agentflare

Length of output: 4883


🏁 Script executed:

set -euo pipefail

nl -ba crates/flare-docs/src/fetch.rs | sed -n '1,220p'

Repository: getappz/agentflare

Length of output: 196


Handle ureq::Error::Status(404, _) in the error mapping
call().map_err(|e| FetchError::Http(e.to_string()))? turns 404s into FetchError::Http before the later status check runs, so missing packages never reach FetchError::NotFound. Match the 404 status in the map_err closure, or otherwise preserve the status for the downstream NpmError::NoTypes mapping.

🤖 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 `@crates/flare-docs/src/fetch.rs` around lines 86 - 88, Update the fetch error
mapping around the `call().map_err(...)` expression to detect
`ureq::Error::Status(404, _)` and return `FetchError::NotFound` directly, while
preserving existing HTTP error handling for other failures. Ensure the later
status-based `NpmError::NoTypes` mapping remains reachable for missing packages.

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