@polyweave/state-search (1.0.4)
Installation
@polyweave:registry=https://hub.kl1.tenere.ai/api/packages/Polyweave/npm/npm install @polyweave/state-search@1.0.4"@polyweave/state-search": "1.0.4"About this package
state-search
State search tools and recursive traversal for Polyweave.
Published as @polyweave/state-search.
Synopsis
import {
createSleuthRetriever,
createTreeSearch,
createTreeSearchHarness,
andFilters,
orFilters,
textFilter,
parseFilter,
createAsyncToolRouter
} from '@polyweave/state-search';
const retriever = createSleuthRetriever({
state: myMultiStateStore,
textStore: myTextStore
});
const results = await retriever.search({
query: 'machine learning',
filters: andFilters([textFilter('neural'), textFilter('network')]),
limit: 10
});
Install
npm install @polyweave/state-search
Description
The state-search package provides tools for searching, retrieving, and recursively traversing Polyweave state stores. It bridges multi-state document/text/graph stores with query builders, filter parsers, and search harnesses.
Key components:
- Sleuth Retriever — A unified search interface over multi-state stores, supporting text search, filter-based querying, and entity retrieval with configurable candidate stores and scoring profiles.
- Tree Search — Recursive traversal of tree-store-backed document hierarchies with configurable node visitors, path collectors, and depth limits.
- Tree Search Harness — A bt-harness-based tool wrapping tree search with agent-driven search strategies.
- Filter System — A composable filter algebra with building blocks for graph, tree, text, predicate, temporal, and spatial filters. Includes a parser for DSL-like filter expressions.
- Query Builder — Programmatic query DSL builder with validation and error handling.
- Async Tool Router — Asynchronous tool routing for deferred tool execution and stream management.
API
State Search (Sleuth Retriever)
createSleuthRetriever(options)
Creates a unified retriever for multi-state stores.
Parameters:
options.state— Multi-state store withsearch,query,get,searchEntities.options.textStore— Optional text store for full-text indexing.options.defaultCandidateStores— Default stores to search across (default['text']).options.defaultLimit— Default result limit (default 10).
Returns: { search(query, options), query(dsl), get(id), searchEntities(entity, query, options) }
Filter System
andFilters(filters)
Combines multiple filters with AND logic. Returns: A filter object.
orFilters(filters)
Combines multiple filters with OR logic. Returns: A filter object.
notFilter(filter)
Negates a filter. Returns: A filter object.
graphFilter(pattern)
Matches documents in a fact graph with pattern-based traversal.
Parameters: pattern — Pattern object { subject, predicate, object, direction? }.
treeFilter(pattern)
Matches documents in a tree store by path or parent-child pattern.
Parameters: pattern — { path?, parentId?, childDepth?, includeAncestors? }.
textFilter(query)
Full-text match filter.
Parameters: query — Search string.
predicateFilter(field, operator, value)
Field-level predicate filter.
Parameters: field — Field name, operator — 'eq'|'neq'|'gt'|'gte'|'lt'|'lte'|'like'|'in', value — Comparison value.
temporalFilter(range)
Time-range filter.
Parameters: range — { after?, before?, field? }.
spatialFilter(box)
Spatial bounding box filter.
Parameters: box — { minLat, maxLat, minLng, maxLng, field? }.
leafScope(docId)
Scope filter for leaf node descendants.
Parameters: docId — Root document ID.
citesDoc(docId)
Filter for documents citing a given document.
writtenBetween(start, end)
Convenience temporal filter for date ranges.
locatedIn(region)
Convenience spatial filter.
parseFilter(filterString)
Parses a DSL filter string into a filter object.
Returns: A filter object.
Throws: FilterParseError with FilterErrorLayer detail on parse failure.
FilterParseError
Error class for filter parsing failures.
FilterErrorLayer
Enum: LEXER, PARSER, VALIDATOR, EXECUTOR.
Tree Search
createTreeSearch(options)
Creates a recursive tree search engine.
Parameters:
options.treeStore— Tree store for traversal.options.maxDepth— Maximum recursion depth (default 100).options.visitor(node, path, context)— Node visitor function; returnfalseto prune branch.
Returns: { search(rootId, options, callback), searchSync(rootId, options), breadthFirst(rootId, options, callback), getPath(nodeId) }
createTreeSearchHarness(options)
Creates a bt-harness tool wrapping tree search with agent-driven exploration.
Parameters:
options.treeSearch— Tree search instance.options.apiKey,options.model,options.createAdapter— LLM configuration.
Returns: { source, sink } — Frame duplex tool.
Query Builder
createQueryBuilder()
Creates a programmatic query builder with validation.
Returns: Builder object with chainable methods:
.select(fields)— Projection fields..from(entities)— Source entities..where(filter)— Filter criteria..orderBy(field, direction)— Sort specification..limit(n)/.offset(n)— Pagination..build()— Produces the final query object..validate()— Validates the query against schema..toDSL()— Serializes to DSL string.
Async Tool Router
createAsyncToolRouter(options)
Creates an async tool router for deferred tool execution.
Parameters:
options.tools— Map of tool name to handler function.options.timeoutMs— Default timeout for async tools.options.maxConcurrency— Maximum concurrent tool executions.
Returns: { route(toolCall, callback), cancel(requestId), close }
Examples
// Advanced filtering with graph and temporal scoping
const filter = andFilters([
orFilters([textFilter('sorting'), textFilter('ordering')]),
predicateFilter('language', 'eq', 'JavaScript'),
temporalFilter({ after: '2024-01-01', field: 'createdAt' }),
notFilter(leafScope('archive'))
]);
const results = await retriever.search({ query: 'algorithm', filter, limit: 5 });
// Recursive tree search with visitor
const search = createTreeSearch({ treeStore: myTreeStore, maxDepth: 50 });
search.search(rootDocId, {
visitor: (node, path, ctx) => {
if (node.metadata?.type === 'section') return true; // descend
ctx.collected.push(node);
return false; // stop at leaf
}
}, (err, results) => {
console.log('Collected:', results.collected.length);
});
// Query builder with filter DSL
import { createQueryBuilder, parseFilter } from '@polyweave/state-search';
const query = createQueryBuilder()
.select(['text', 'score', 'metadata'])
.from(['SleuthCandidate', 'SleuthEvidence'])
.where(parseFilter('text CONTAINS "neural" AND score > 0.7'))
.orderBy('score', 'desc')
.limit(20)
.build();
Tests
npm test
Tests cover sleuth retriever creation and search, filter composition (AND/OR/NOT), filter DSL parsing and error handling, tree search traversal strategies, query builder validation and DSL serialization, async tool routing with concurrency control, and bt-harness tree search integration.
Requirements
Node.js 18 or later. ESM only.
Caveats
- Filter parsing uses a simple DSL grammar; complex nested expressions may require programmatic filter construction instead of string parsing.
- Tree search depth is bounded by
maxDepth(default 100). Very deep trees with high branching factors may exceed this. - Async tool router limits concurrency via
maxConcurrency; requests beyond this are queued. Set appropriately for your tool execution capacity.
License
MIT
Dependencies
Dependencies
| ID | Version |
|---|---|
| @polyweave/bt-harness | * |
| @polyweave/tools | * |
| peggy | ^4.0.2 |
Development Dependencies
| ID | Version |
|---|---|
| @rigor/core | * |
Peer Dependencies
| ID | Version |
|---|---|
| @polyweave/core | * |
| @polyweave/state | * |