← Catalog

pi-agentic-search

Ranked code search and diff context packs for coding agents, as a CLI and Pi tools

Package

Install

Install with PiG

pig install npm:pi-agentic-search

Install with Pi

pi install npm:pi-agentic-search
Review before installing

Packages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.

Pi manifest JSON

The pi field of package.json.

{
  "skills": [
    "./skills"
  ],
  "extensions": [
    "./index.ts"
  ]
}

README

Written by the package's publisher, shown as published in version 0.8.0 (README.md). PiG does not review it.

pi-agentic-search finds code with fewer tool round-trips. Use its CLI from any coding harness with shell access, or its native tools in Pi.

I built it to avoid the repeated searches and file reads an agent goes through before reaching the right place in a codebase. It ranks search results and collects related code in one call, so the agent doesn't have to fetch each file separately.

Finding code

agentic_search ranks ripgrep matches, suggests which file to read first, and includes source snippets. It can look for definitions, references, or tests. When the same name appears in several parts of the codebase, context helps rank the relevant matches.

For example, searching for remaining_value with context actual goal progress helps separate goal-related code from unrelated financial calculations. The search pattern stays the same; the context changes how matches are ranked.

The search can also follow supported Ruby mixins and JavaScript/TypeScript imports into other files and packages. That lets the agent find the definition behind an imported name without opening every file along the way. Directory and partial-path searches follow relationships from a limited set of ranked matches, with the selected and omitted files reported in the results.

A tests search (intent: tests) for a Rails entry point also returns the tests that drive it, under details.entryTests. The query names a controller action or a job (OrdersController#create, Admin::OrdersController, ReceiptJob), or is a method name with path set to its file. The class must be a controller or job by its declared ancestors, which the search reads by Rails file naming. Each test hit says how it was found: path (a test file named after the class, such as test/controllers/orders_controller_test.rb or spec/requests/orders_spec.rb), class (a test class or describe names it), route (a request through a URL helper or a quoted path of a route to the action, with a verb the route accepts, when config/routes.rb parses), and for a job enqueue or perform (a line naming the job with perform_later, assert_enqueued_with, perform_now and the like). Whether a test executes particular lines is not a search fact; coverage decides that.

Following calls and reviewing changes

The context tools collect definitions, calls, callers, and related tests for Ruby, JavaScript, and TypeScript.

sparsity_collect takes a file and line number, finds the enclosing definition, and follows its calls up to the requested depth. The result includes source snippets, the file lines above and below the definition (vicinity above/vicinity below, as many as vicinity_check), static callers, and calls it couldn't resolve.

sparsity_scan collects context for a whole diff, including removed definitions that still have callers. It accepts commits, Git ranges, or uncommitted changes with untracked files.

A manifest lists the pack's contents and points to sections in pack.md. The agent can read the section it needs without loading the whole pack into the conversation. Each changed definition comes with its vicinity (the file lines above and below it) and three lines around every caller's call site. Schemas, configuration, and files without a parser include their changed hunks and the surrounding file lines without call expansion, with a note that callers, tests and sibling definitions must be read by hand. Additional test definitions are grouped by file.

Anchors in pack.json also carry facts that a review tool can check without re-reading the diff. status is added or modified: whether the base revision of the file defines the same symbol. Statements and declarations are identified by their text, so an edited one reads as added. whitespaceOnly lists the changed lines that git diff -w does not report, and signatureChanged says the base defines the symbol with a different parameter list. Explicit --anchor scans have no base and omit these fields.

Nodes and anchors carry semanticFingerprint beside fingerprint. fingerprint hashes the definition's lines as written; semanticFingerprint hashes its syntax tree, which has no comments or layout, so a comment edit, re-indentation or re-wrapping leaves it the same while fingerprint changes. String contents are part of the tree. It is absent when no parser read the file.

Changed files are classed as code, test, migration, config, dependency, schema, generated or other. Migrations and configuration that Ruby or JS/TS can parse are still anchored; dependency manifests, lockfiles and schema dumps get hunk sections. Anchors that run when their file loads carry loadTime: true: top-level statements, declarations, constants and objects, and Ruby class-body calls such as has_many or validates (a block passed to one is not separated from it). scope and define_method bodies run when called and are not marked.

An anchor's guards lists its changed lines that run under a condition, each with the conditions that dominate it, outermost first. A condition is reported as written: if x, elsif x, unless x and TypeScript if (x) keep their keyword; a ternary condition or the left side of && or || is the expression alone. Its branch is then (inside the branch taken when that text holds), else, or after-return (after an early return, next, break, raise or throw taken when it holds). Call edges carry the guards of their call site. Method and class bodies start with no guards, and the tool does not interpret any condition.

An anchor's callerCount gives the production call sites the search found (total), how many callers lists (shown), and whether that list is all of them (complete). The list is cut by its limit of six, by keeping one call site per file, and by ripgrep's per-file match cap; scan --callers all (allCallers in scanSparsity) lists every call site. Names too common to search by name alone (call, perform, create, names under four characters…) are not searched without a Ruby index. With one, only call sites whose receiver type the index knows are kept, so the list is incomplete when a call site of that name has an unknown receiver type; Job.perform_later and the other enqueues count as call sites of Job#perform. Each caller lists the guards of its call site, as its called_by edge does (absent on the edge when there are none). A JavaScript or TypeScript caller is the definition that holds the call, also when the call sits in a function written in place: an argument, or the value of an object literal's property. For a property, the caller gives its key as written in key: review.prepare for 'review.prepare': ({ id }) => reviews.prepare(id), and also when the property's value is the name itself ({ sync }, again: sync). When functions nest, the nearest one that is a property's value names the key. The edge is exact, with via saying how the receiver type was known, when the index's receiver type dispatches to the anchor, or when the TypeScript checker resolved the call to it, which needs the caller in the TypeScript program (a changed file or one it imports). Test call sites are listed as tests and not counted. A line that declares, imports or re-exports the name is not a call site; a call on an assignment or export line (const x = name()) is.

scan --tests all (allTests in scanSparsity) adds testDefinitions: every test definition that references an anchor by name, without the usual cap of eight per anchor. Each lists the anchors and lines it references, changed when the diff changes it, and setup: the setup blocks that run before it, outermost first, with up to 60 of their lines (Ruby setup, before and def setup; JS/TS beforeEach, beforeAll, before and setup, in the scopes around the test). Flags are often turned on there. Each test definition is expanded one hop, so its own calls are the calls edges from its node; that needs --max-depth 2 or more, the default. With a Ruby index, names too common to search are filtered by receiver type, as callers are.

With a Ruby index, nodes and anchors that the framework calls carry entry: { kind, exact }. kind is job for the perform of a class whose declared ancestors include ApplicationJob, ActiveJob::Base, Sidekiq::Job or Sidekiq::Worker, and controller for a public method of a class under ApplicationController, ActionController::Base or ActionController::API. mailer is a public method of a class under ApplicationMailer or ActionMailer::Base, and channel one of a class under ApplicationCable::Channel or ActionCable::Channel::Base: the framework calls each by its name (ReportMailer.daily(user), a client's perform("speak"), subscribed), so both are exact. task is a task block of a rake file (*.rake, Rakefile), a definition of kind task named as rake runs it, with the names of the namespace blocks around it first (reports:daily); what it calls has it as a caller, and no call to it is searched for. exact is true for jobs, mailers, channels, tasks and actions that a route in the root's config/routes.rb names. Routes are read from the file's syntax tree: root, the HTTP verbs and match, resources and resource with only and except, member, collection and nested routes, and namespace, scope and controller blocks. Statements it does not read, such as draw or concern, are named in a coverage note, and actions only they route stay exact: false.

A routed action's entry lists its routes, each { verbs, path, file, line, text } with the line of config/routes.rb that draws it, as written. The action config.exceptions_app names in config/application.rb, such as ErrorsController.action(:show), is exact too, and its entry's exceptionsApp gives those lines. JavaScript and TypeScript definitions their package exposes carry entry: { kind, exact: true, doors }: command for the statements of a bin file, extension for the default export of a module pi.extensions lists, and export for the names the main, module or exports modules export, followed through re-exports. Each door is the package.json line that says so, { kind, title, file, line, text }.

A JavaScript or TypeScript caller record also says the way in its call site belongs to, when the caller's code registers one: entry: { kind, exact, doors }, each door the line that registers it, as above, titled by the name it is reached by. An anchor that such a caller registers by name, as the registered value itself, carries that entry too, unless it has one of its own. Any other caller record carries its caller's own entry. handler is a property of a map of handlers by name, titled by its key (review.prepare). A map is one when every value is a function or names one, and the same file reads the map by a key it is given (commands[name](id), this.handlers[type]); then it is exact. With no such read, a map is one, not exact, when every value is a function written in place and at least one key has to be quoted because it is no name ('review.prepare', 'user:created'): it is sent by key from another file, or not at all. An object of options, or of methods under plain names, holds no handler.

listener is a function a call registers for an event, titled by the event, which has to be written as a string: the second or a later argument of on, once, addListener, prependListener, prependOnceListener or addEventListener, of Electron's handle and handleOnce on what electron gives (ipcMain.handle('review.sync', fn)), and of Tauri's listen and once from a @tauri-apps/ module. The door is the line of the call. What it is called on decides the rest. It is exact on a known event source: process (also imported from node:process), window, document, globalThis or self where the file declares no such name, a bare addEventListener, and anything Electron's or Tauri's modules give. It is a listener, not exact, on a name the module declares at its top or imports from elsewhere (bus.on('sync', fn)), or on a global it does not declare, and for addEventListener on any other value. On a parameter, a local or a member (this.x) of the code around it, or on what a call returns, on and the other emitter methods register no listener: a stream's data inside the function that opened it is that function's own work, and the tool cannot tell it from an emitter of the app.

route is a function a call registers for a path: R.get('/path', ...fns) and post, put, patch, delete, head, options and all, or Hono's R.on(verbs, '/path', ...fns), with the path written as a string that starts with / (or is *) and the function after it, as handler or middleware. Its entry has routes in the shape a Rails action's have, { verbs, path, file, line, text } with the line of the call; all takes the verbs via: :all does. It is exact when R is an app or a router that Express, Hono, Fastify, Koa's router or Elysia made: a variable made by express(), express.Router(), new Hono() or Fastify(), or a parameter written with one of their types (app: Express). It is not exact when R is only named like one (app, api, router, server, this.app, adminRouter), and no route otherwise, so a store's get('/key', load) is none. Fastify's route({ method, url, handler }) and Express's app.route('/path').get(fn) are not read.

ui-handler is the function a JSX element's event prop is given, a prop named on and a capital (onClick={save}, onClick={() => save(id)}), titled by the element and the prop (button onClick) at the prop's line. It is never exact: an element's prop says the interface may call it, and a component's on prop is a callback it is handed, which may not come from the user at all.

A script with no file ending, such as bin/production-errors, is read in the language its first line names: #!/usr/bin/env ruby (or another Ruby) as Ruby, node, tsx, ts-node, bun or deno as JavaScript, through env and its flags. Its definitions are anchors and nodes like those of any .rb or .js file, the Ruby index reads it, and searches for callers and tests include it. A shell script, or any other, stays plain text. A script's top-level statements that run, such as exit Report.run(ARGV) if $PROGRAM_NAME == __FILE__, Worker.new.call or main below its def main, are definitions of kind statement with entry: { kind: "command", exact: true }, and callers of what they call; a require is none. A Node script's caller outside the TypeScript programs is exact via import when it imports the name from the anchor's module. With a Ruby index, a call to new is a call site of the class's initialize too.

Rails view templates under app/views (ERB, Haml, Slim, Jbuilder and Builder; layouts aside) are definitions of kind template: the whole file, named by its path under app/views, in language ruby. A changed template is one anchor. A template whose Ruby calls a helper or a model method by name (inside ERB tags, after Haml and Slim code markers, anywhere in Jbuilder) is one of its callers: exact via self for a method of app/helpers called with no receiver, which runs on the view, and otherwise a static_candidate. A template's callers are what renders it: a render call that names its path, or its name from a file of its own folder, is exact via render, with the name as written in the caller's name; a render of an object or collection named after its model is a static_candidate; and the action of the template's name in its folder's controller or mailer renders it by convention, exact via convention, with convention: true on the caller.

In Ruby, Job.perform_later, Job.set(...).perform_later and Sidekiq's perform_async, perform_in, perform_at and perform_bulk produce an enqueues edge to Job#perform, and Mailer.action(...).deliver_later one to the mailer action. Expanded Ruby definitions list effects: calls named like a write (save, update!, destroy, update_all…), an enqueue, or a cache operation on a receiver ending in cache (Rails.cache.fetch…), each with its line and call text. They are collected before common methods are dropped, so a call that produces no edge still appears. Anchors list the effects on their changed lines.

Installation

You need Node.js 22+ and rg (ripgrep) on your PATH. Diff context also uses Git. The package includes its Ruby parser and TypeScript dependency. The CLI does not need Pi or a TypeScript loader.

CLI and other harnesses

pnpm add -g pi-agentic-search
agentic-search --help

From a source checkout with dependencies already present, run the build script, then node bin/agentic-search.mjs --help. Published packages include the compiled CLI.

The portable skill explains when to search, collect or scan without listing every option. Copy its agentic-search directory into a skill location supported by your harness, or point the harness at the file as instructions. Installation does not edit harness configuration.

Pi

pi install npm:pi-agentic-search

Then run /reload in Pi. To try the published package for one session without saving it to your package settings:

pi -e npm:pi-agentic-search

Usage

CLI

agentic-search search 'remaining_value' --intent definition --context 'actual goal progress'
agentic-search search 'calculateTotal' --path src/cart.ts --expand-related
agentic-search collect app/models/goal.rb:42 --max-depth 3
agentic-search scan --diff main..HEAD
agentic-search scan --diff main..HEAD --strict-revision --output-dir /tmp/review-context
agentic-search scan --diff worktree --output-dir /tmp/review-context

Run in the repository or add --cwd /path/to/repo after the subcommand. Use search --help, collect --help or scan --help for all options. Numeric CLI options reject values outside their documented limits. scan --anchor path:line accepts repeated anchors instead of --diff.

Text is the default. --json writes one {text, details} object to stdout, including coverage and pack paths. JSON is not truncated; text is capped at 2,000 lines or 50 KiB, with overflow saved to a reported temporary file. Diagnostics go to stderr. Ruby parsing can emit Node's WASI warning there.

Exit codes: 0 for a result, including a complete search with no matches; 1 for execution failure; 2 for invalid arguments; 130 for interruption. A successful exit can still contain partial coverage or unresolved calls. Inspect the result before drawing conclusions.

Scan packs default to a fresh system temporary directory. A relative --output-dir resolves against the selected repository. The CLI builds its Ruby index in temporary storage and removes that index when the command finishes, unless collect or scan gets --cache-dir <path>. That directory keeps one compressed index per root and commit tree, so a later run at the same commit reads it and parses only changed files; on a large repository that is most of a scan's time. A relative path resolves against the selected repository, --strict-revision needs it outside the repository, and it grows until you remove it. The CLI does not use Pi's metrics log or persistent cache; Pi keeps its existing storage locations. Use a dedicated output directory: a scan writes pack.md, pack.json and metrics.json there. These files contain source and remain until you remove them.

Pi tools

Pi can call these tools during coding work. You can also ask for one by name:

Use sparsity_scan to collect context for my uncommitted changes. Explain what changed and which callers might be affected.

Pi can collect the diff with diff: "worktree", read the relevant sections, and use sparsity_collect for a closer look at a definition. When starting from a name rather than a diff, agentic_search finds candidates first.

All three Pi tools accept an optional cwd to select another repository, defaulting to the session's working directory. For example, call agentic_search with { query: "calculateTotal", cwd: "/path/to/repo" }. Use path separately to narrow the search within that repository.

Code Mode

All three tools support Pi's Code Mode with the same arguments as direct calls. They are callable while active in both codemode.mode: "on" and "only"; "only" hides their direct declarations without disabling script calls.

The extension does not enable codemode itself. If needed, add it in Pi's user or project settings:

{
  "defaultTools": ["+codemode"]
}

An explicit --tools allowlist must include codemode and the search tools you want, alongside any other tools you need. Tool exclusions can disable them.

Inside a codemode script (replace the example query and target with your own):

text(await tools.agentic_search({ query: "calculateTotal", intent: "definition" }));
text(await tools.sparsity_collect({ target: "src/cart.ts:12" }));
text(await tools.sparsity_scan({ diff: "worktree" }));

Each awaited call returns a text string, not structured JSON. Read coverage notes and any context-pack paths in that text.

Find tools through ALL_TOOLS or await searchTools("sparsity"); inspect a tool's arguments with await describeTool("sparsity_collect"). A tool omitted from Code Mode's inline declarations can still be discovered and called.

Pi's built-in tool guidance comes from its registrations. The package also ships the portable skill; it prefers native tools when they are available.

Scope and limitations

Depth, file, node, and time limits bound each search or traversal. When a tool stops early, it reports unfinished scopes and unresolved relationships so the agent knows where to follow up. The collector reports setup time and total wall time separately. Its traversal budget doesn't interrupt initial parser, index, or compiler setup.

Call resolution is static. A matching name, especially in Ruby, doesn't prove which method gets called at runtime. Labels distinguish exact declarations from candidates, ambiguous matches, and unresolved calls. Each unresolved edge has a reason: operator (such as + or []), unknown-receiver (the receiver's type was not traced or only guessed from its name), dynamic (the callee is chosen at runtime) or no-definition. Coverage counts them in unresolvedByReason. The tools find tests that reference the code, but don't run them or establish coverage. They also omit common library operations, so zero unresolved edges doesn't mean they found every runtime call.

Context collection defaults to the nearest component root within the working directory. Use cwd to select another checkout. For a diff, omitting root or passing . keeps separate component roots; an explicit path narrows the scan. Files absent from a sparse checkout aren't searchable.

By default, committed-range scans can mix revisions: changed files come from the range's head when it differs from checkout HEAD; callers, tests, and unchanged files come from the checkout. Searches read the changed files at that head too, so a caller inside a changed file has the head's line number. Local edits can affect checkout content. The manifest records which revisions it used.

Use CLI --strict-revision, Pi strict_revision: true, or scanSparsity({ ..., strictRevision: true }) to reject mixed-revision input before parsing source or writing a pack. This option requires an explicit commit or range (base..head or base...head); it rejects worktree scans and explicit anchors. The resolved head commit, including an annotated tag's commit, must equal checkout HEAD.

Strict mode checks the entire repository, even with a narrower cwd or root. It rejects staged/unstaged changes, deletions and non-ignored untracked files of any type, not just Ruby/JS/TS. It also rejects sparse checkouts, skip-worktree/assume-unchanged index entries, and repositories containing submodules. For a submodule, scan a separate full checkout of its requested commit. Diagnostics identify the mismatch and ask for a clean checkout; the tool never checks out, stashes, fetches or creates a worktree.

Keep strict-mode output directories, index caches and metrics logs outside the repository, including ignored directories. Existing symlinks are resolved when checking destinations. Existing non-ignored packs inside the checkout count as untracked changes; there is no output-directory exemption.

This is a Git checkout preflight, not a snapshot or sandbox. Do not change source, refs or output paths during a scan. Ignored untracked files (including dependencies and generated code), sources outside the repository and dependency reproducibility are not verified. Parsers may still read those files. Strict mode does not change static-resolution labels, traversal limits or coverage disclosures.

Large TypeScript projects can use a lot of memory. Building a compiler program for one recorded 5,800-file import closure took about two seconds and 1 GB. Those numbers describe that workload, not a resource limit.

Evaluation

The public evaluation compares search results on 15 frozen Pi, Rails, and Zod cases, including six holdouts. Its baseline report records:

MeasureRaw rgFull search
Correct first file, positive cases6/1211/12
Correct first span, positive cases5/1210/12
Valid negative misses3/33/3

These cases were selected manually. They measure search quality, not how many tool round-trips the extension saves in general. Two Zod ranking/span limitations remain; the evaluation documents them alongside the feature ablations and model runs.

The synthetic benchmarks check ranking and execution behavior. Exact-file searches without related expansion use one ripgrep process and no path listing, including in fixtures with 7,999 unrelated files.

Use /agentic-search-stats in Pi to inspect recent context-tool runs, or /agentic-search-stats 10 for the last ten.

Data access

The extension makes no direct network requests. It reads local source and configuration, runs ripgrep and Git, and writes context packs, metrics, Ruby index caches, and oversized output. Packs contain source snippets.

The runtime access document describes search's filesystem and subprocess access. Report vulnerabilities privately using SECURITY.md.

Other installation options

Install from GitHub:

pi install git:github.com/dantetekanem/pi-agentic-search

Or use a local checkout:

git clone https://github.com/dantetekanem/pi-agentic-search.git
cd pi-agentic-search
npm ci
pi install .

Development

This repository uses npm and package-lock.json for development, CI, and publishing. Use Node.js 22.19 or newer in the Node 22 line, as CI does, with rg on your PATH. Keep dependency changes in package.json and package-lock.json together; don't maintain a second lockfile.

npm ci
npm run check
npm test
npm run smoke
npm run benchmark -- --samples 15 --check --output /tmp/search-benchmark.json

The build script compiles the standalone CLI. prepack runs it before packaging. The test:cli script builds and checks the CLI against Pi results, argument errors, and execution without Pi packages. The regular test script also builds before running tests.

The smoke command covers search, call cycles, committed-range context, the language adapters, cached Ruby indexing, and boundary ranking. Write new benchmark runs to a separate output file.

Public-source and opt-in model measurements have separate reproduction instructions. Normal tests don't make live model requests.