Skip to content

Library API

Terminal window
# Core package (queries only)
npm install @intentweave/index
# Full build pipeline (requires analyzer)
npm install @intentweave/index @intentweave/analyzer @intentweave/core

The CariIndex class is the recommended entry point. It manages the database lifecycle and exposes typed query methods.

import { CariIndex } from "@intentweave/index";
const index = await CariIndex.build({
paths: ["docs/", "packages/"],
workspaceRoot: process.cwd(),
depth: "full",
});
const results = index.retrieve({ query: "authentication" });
console.log(results.files);
index.close();

Pass a CariConfig object to CariIndex.build() or buildFromPaths():

PropertyTypeDefaultDescription
pathsstring[]Document file paths or directories to analyze
workspaceRootstringWorkspace root directory
depth"structured" | "full""structured"Annotation depth (full = +IDF scoring)
excludestring[][]Additional glob patterns to exclude
includestring[]Only include files matching these globs
sessionstringdirectory basenameSession name
outputPathstring.iw/index.dbOutput SQLite path
log(msg: string) => voidnoopVerbose logging callback
onProgress(s: CariStageProgress) => voidCalled after each pipeline stage completes

The Entity Bridge lets consumers inject external entities (domain concepts, pipeline entities, third-party models) so that annotation matching works beyond AST-extracted code symbols.

import { CariIndex, type ExternalEntity } from "@intentweave/index";
const index = CariIndex.load(".iw/index.db");
index.registerEntities([
{
id: "entity:auth-service",
name: "AuthService",
type: "component",
aliases: ["auth service", "authentication module"],
},
{
id: "entity:adr-005",
name: "ADR-005",
type: "decision",
aliases: ["token rotation decision"],
metadata: { status: "accepted" },
},
]);
// Find all doc mentions of an entity
const mentions = index.mentionsOf({ entityId: "entity:auth-service" });
// → [{ docPath, line, text, confidence, source }]
// List all annotations for a doc file
const annotations = index.annotationsForFile({ filePath: "docs/AUTH.md" });
// → [{ mention, entityId, entityName, entitySource, line, confidence }]
index.close();
PropertyTypeRequiredDescription
idstringyesUnique entity identifier
namestringyesDisplay name (matched against doc text)
typestringyesEntity type (e.g. component, decision)
aliasesstring[]noAlternative names for matching
metadataRecord<string, unknown>noArbitrary metadata

All query methods are synchronous and return typed results.

retrieve(params) — Ranked File Retrieval

Section titled “retrieve(params) — Ranked File Retrieval”
const result = index.retrieve({
query: "authentication",
scope: "docs", // 'docs' | 'code' | 'all'
limit: 10,
});
// result.files: Array<{ path, score, reason, spans? }>

connections(params) — Cross-Layer Connections

Section titled “connections(params) — Cross-Layer Connections”
const result = index.connections({
entity: "AuthService",
limit: 10,
include: ["doc_cooc", "co_change", "code_import"],
});
// result.connections: Array<{ entity, score, sources }>
// result.gaps: Array<{ entity, expectedIn, reason }>
const result = index.check({
changed: ["src/auth/service.ts"],
severity: "warning",
});
// result.findings: Array<{ file, line, severity, message, relatedDocs }>
const result = index.report();
// result.coverage: { documented, total, percentage, topUndocumented }
// result.staleness: { staleDocCount, topStale }
// result.hiddenCouplings, result.undocumentedDeps
const exact = index.clones(); // Identical body hashes
const type2 = index.structuralClones(); // Same AST, different identifiers
// .cloneGroups: Array<{ bodyHash|structureHash, bodyLines, symbols }>
const cycles = index.circularImports(); // .cycles: Array<{ files, length }>
const unused = index.unusedExports(); // .unused: Array<{ name, filePath, kind }>

hotspotPriority() — Documentation Urgency

Section titled “hotspotPriority() — Documentation Urgency”
const result = index.hotspotPriority();
// .priorities: Array<{ filePath, churn, coveragePercent, priorityScore }>
const result = index.todos();
// .todos: Array<{ filePath, line, kind, text }>
// .byKind: Record<string, number>
MethodReturnsPurpose
moduleCoverage()ModuleCoverageResultCoverage % per directory
orphanedSections()OrphanedSectionsResultDoc sections with no grounded mentions
docCompleteness()DocCompletenessResultPer-doc completeness score
crossGroupDrift()CrossGroupDriftResultEntity conflicts across doc groups
testCoverage()TestCoverageResultTest→source mapping + untested exports
hubs()HubsResultGod-node / hub analysis
communities()CommunitiesResultLabel-propagation community detection
surprises()SurprisesResultSurprising connection ranking
rationale()RationaleResultWHY/NOTE/IMPORTANT/DESIGN inventory
terminologyInconsistency()TerminologyInconsistencyResultTerminology inconsistency detection
dependencyDepth()DependencyDepthResultTransitive import depth + risk
boundaryViolations()BoundaryViolationsResultCross-package import detection
layersInfer()LayersInferResultAuto-infer layers from import graph
layersCheck()LayersCheckResultValidate imports against layer config

mentionsOf(params) — Entity → Doc Mentions

Section titled “mentionsOf(params) — Entity → Doc Mentions”

Find all documentation mentions of a specific entity (code symbol or external).

const result = index.mentionsOf({
entityId: "entity:auth-service",
minConfidence: 0.7,
limit: 20,
});
// result: Array<{ docPath, line, text, confidence, source }>

annotationsForFile(params) — File → Annotations

Section titled “annotationsForFile(params) — File → Annotations”

List all annotations for a documentation file, resolving entity names from both symbols and external entities.

const result = index.annotationsForFile({
filePath: "docs/AUTH.md",
minConfidence: 0.5,
});
// result: Array<{ mention, entityId, entityName, entitySource, line, confidence }>
// entitySource: "symbol" | "external" | undefined

For fine-grained control, use the dual-signature query functions directly:

import { retrieve, retrieveFromDb, openIndex } from "@intentweave/index";
// Path-based (opens and closes DB internally)
const result = retrieve(".iw/index.db", { query: "auth" });
// DB-based (you manage the connection)
const db = openIndex(".iw/index.db");
const r1 = retrieveFromDb(db, { query: "auth" });
const r2 = retrieveFromDb(db, { query: "database" });
db.close();

import { detectChanges, applyChanges } from "@intentweave/index";
const changes = detectChanges(".iw/index.db", process.cwd());
const result = await applyChanges(".iw/index.db", changes, {
workspaceRoot: process.cwd(),
depth: "structured",
});

import {
DEFAULT_EXCLUDES,
loadIwIgnore,
buildExcludeList,
discoverFiles,
} from "@intentweave/index";
const ignorePatterns = await loadIwIgnore(process.cwd());
const excludes = buildExcludeList(["custom/**"], ignorePatterns, true);
const files = await discoverFiles(["docs/"], process.cwd(), { exclude: excludes });

All result types are exported for TypeScript consumers:

import type {
CariConfig, CariStageProgress,
RetrieveParams, RetrieveResult,
ConnectionsParams, ConnectionsResult,
CheckParams, CheckResult,
ReportResult, ClonesResult, StructuralClonesResult,
CircularImportsResult, UnusedExportsResult,
HotspotPriorityResult, TodosResult,
ModuleCoverageResult, OrphanedSectionsResult,
DocCompletenessResult, CrossGroupDriftResult,
ExternalEntity, MentionsOfParams, MentionsOfResult,
AnnotationsForFileParams, AnnotationsForFileResult,
InferredLayer, LayersInferResult, LayerViolation, LayersCheckResult,
NamedLayer, NamedDirectory, LayerNamingResult,
ArchReportData, ArchReportNode, ArchReportEdge, ArchReportOptions,
} from "@intentweave/index";