/** * The extraction pipeline — composes config, adapters, storage, and * anthropic-client into an end-to-end indexer. * * Stages (per DESIGN.md's extraction pipeline section): * 0. Atlas-aware startup: import committed atlas.json if present, * establishing the committed SHA baseline. * 1. Walk prose files (ADRs + docs.include globs), compute SHAs. * 2. Diff current SHAs against the committed baseline. * 3. Walk source code files, build the symbol inventory via adapters. * 4. Upsert symbols (with file SHAs) into storage. * 5. Handle deletions: drop claims + source_shas for files gone from disk. * 6. Extract changed/added prose files in batches, resolve candidates, * and write claims. * 7. If atlas.committed, regenerate atlas.json iff any modification * happened. Bump atlas_meta.generated_at on real changes only. * * Result is summary stats, NOT the extracted claims themselves — the * caller inspects storage for those. */ import type { DatabaseInstance } from "../storage/db.js"; import type { ContextAtlasConfig, LanguageAdapter, LanguageCode, SymbolId } from "../types.js"; import { type ExtractionClient } from "./anthropic-client.js"; import { type UsageInfo } from "./pricing.js"; import { type SymbolInventory } from "./resolver.js"; export interface ExtractionPipelineDeps { /** * Source code root. Passed to the language adapter's `initialize`. * `walkSourceFiles` indexes from here. Source files must stay under * this root — ADR-01's security/ID-stability invariant. */ repoRoot: string; /** * Directory containing `.contextatlas.yml`. Resolution base for * `adrs.path` and `docs.include` glob patterns. Defaults to * `repoRoot`, preserving current behavior when config lives * alongside source (the common case). * * Diverges from `repoRoot` in setups where config + ADRs live * separately from source — e.g., a benchmarks project whose ADRs * describe a cloned external source tree. See ADR-08. */ configRoot?: string; config: ContextAtlasConfig; db: DatabaseInstance; anthropicClient: ExtractionClient; adapters: ReadonlyMap; /** Batch size for concurrent extraction calls. Default: 3. */ batchSize?: number; /** Provided by caller when a real run should bump generated_at. */ contextatlasVersion?: string; /** * Git HEAD SHA of the contextatlas binary that produced the atlas * (atlas schema v1.3+, v0.3 Theme 1.3). Resolved by the CLI runner * at startup; passed through to atlas_meta + the exported atlas. * Pass `null` to explicitly omit (e.g., binary not in a git * checkout). Pass `undefined` to fall back to the stored meta * value (lossless round-trip path for imported atlases). */ contextatlasCommitSha?: string | null; /** * Override the git `log` window. Defaults to the ADR-11 constant. * Primarily a test knob — production runs take the default. */ gitCommitLimit?: number; /** * Override the git binary path. Defaults to `"git"` on PATH. Test * harnesses that want to avoid spawning the real binary pass a * script path or a non-existent path (triggering the "no git" * branch). */ gitBinary?: string; /** * When true, bypass SHA-diff gating and re-extract every prose * file regardless of whether its content matches the committed * baseline. Used by `contextatlas index --full` (ADR-12) for * rebuild cases — prompt changes, model changes, suspected * extraction quality issues. Default: false. */ skipShaDiff?: boolean; /** * Optional USD ceiling. When set and cumulative extraction cost * exceeds this value during a run, a single warning is logged to * stderr and no further warnings fire for the rest of the run. * Not a hard cap — the run continues regardless. v0.2 Stream A #2. */ budgetWarnUsd?: number; /** * Claim-attribution narrowing rule (v0.3 Theme 1.2 Fix 2). * Targets the muddy-bundle mechanism documented in Phase 6 §5.1 * (atlas-claim-attribution-ranking.md): frontmatter symbols * inherited as a per-claim baseline dominate per-symbol ranking * when many claims share the same baseline. * * Three states: * - `undefined` (default): baseline behavior — frontmatter * symbols merge into every claim's candidates as authoritative * leading entries. v0.2 behavior; preserves byte-equivalence * with pre-Step-5 atlases. * - `"drop"`: drop frontmatter inheritance entirely. Claims * attach only to model-extracted candidates. Cleanest * experimental knob; isolates Phase 6 §5.1's mechanism check. * Regression risk: claims where the model didn't surface * specific candidates may attach to ZERO symbols, becoming * invisible to get_symbol_context lookups. * - `"drop-with-fallback"`: drop, but recover when a claim * would otherwise resolve to zero symbols by falling back to * frontmatter inheritance for that claim only. Addresses the * "drop" regression risk; cheap insurance. * * Step 5 ships flag opt-in only; Step 7 reads spot-check evidence * + decides the v0.3 ship default. Stream D (Step 15) re-measures * the chosen configuration. */ narrowAttribution?: "drop" | "drop-with-fallback"; } /** * Per-file breakdown of unresolved symbol candidates and frontmatter * hints, accumulated during Stage 6 of the pipeline. Surfaces via the * `--verbose` flag on `contextatlas index` (v0.2 Stream A #3). Empty * cases are *not* pushed onto `ExtractionPipelineResult.unresolvedDetails`; * the array contains only files that had ≥1 unresolved token. */ export interface UnresolvedClaimDetail { /** Full claim text. Truncation for display is the caller's concern. */ claim: string; severity: "hard" | "soft" | "context"; /** Candidate names that did not resolve to any symbol. */ unresolved: string[]; } export interface FileUnresolvedDetail { sourcePath: string; /** Frontmatter `symbols:` hints that did not resolve. */ frontmatterUnresolved: string[]; /** Per-claim unresolved candidates, in claim order. */ claimUnresolved: UnresolvedClaimDetail[]; } export interface ExtractionPipelineResult { filesExtracted: number; filesUnchanged: number; filesDeleted: number; claimsWritten: number; symbolsIndexed: number; unresolvedCandidates: number; /** * Frontmatter `symbols:` hints that didn't resolve to any symbol in * the codebase. Aspirational misses — logged at debug, surfaced here * as a summary stat for visibility. A non-zero value is not an error; * it may indicate an ADR references code that was renamed or hasn't * been written yet. */ unresolvedFrontmatterHints: number; extractionErrors: Array<{ sourcePath: string; error: string; }>; atlasExported: boolean; wallClockMs: number; apiCalls: number; /** * Cumulative `input_tokens` across successful Anthropic API calls * (v0.2 Stream A #2). Failed-retry tokens are invisible to us and * not included. Null-result calls (max_tokens, malformed JSON) * still count — those API calls consumed tokens even if we * couldn't use the response body. */ inputTokens: number; /** Cumulative `output_tokens`. Same inclusion rules as `inputTokens`. */ outputTokens: number; /** * USD cost computed from `inputTokens` and `outputTokens` under * Opus 4.7 pricing (see `pricing.ts`). Full precision; formatting * is the caller's concern. */ costUsd: number; /** * Number of git commits captured during the run (ADR-11). Zero when * the repo is not a git working tree. */ gitCommitsIndexed: number; /** * HEAD SHA at extraction time, or null when the repo is not a git * tree. Echoes what lands in `atlas.extracted_at_sha`. */ extractedAtSha: string | null; /** * Per-file detail of unresolved tokens — frontmatter `symbols:` hints * plus per-claim unresolved candidates. Only files with ≥1 unresolved * appear. Surfaces via `--verbose` on `contextatlas index` (v0.2 * Stream A #3). Default summary output does not use this; callers * that want per-token detail format it themselves. */ unresolvedDetails: FileUnresolvedDetail[]; } export declare function runExtractionPipeline(deps: ExtractionPipelineDeps): Promise; /** * Derive the `source` field value for a prose file. Preference order: * 1. YAML frontmatter `id:` field (our ADRs use this — `id: ADR-03`). * 2. Filename regex `ADR-\d+` (case-insensitive, to catch `adr-01.md`). * 3. Basename without extension. */ /** * v0.7.2 substrate-currency migration: emit modern `adr:` * convention matching Skill `/index-atlas` SKILL.md spec + * `validate-extraction` canonical source-field format invariant. * * Pre-v0.7.2 emitted frontmatter `id` field (ADR-NN) which was the * substrate-currency outlier — Skill substrate at v0.7 Step 2.3.b.0 * adopted prefix convention but CLI `deriveSourceName` preserved * pre-v0.5 era identifier-only format unchanged through cycle * boundaries. Empirically surfaced at v0.7.1 first-run mechanical- * floor verification (validate-extraction `adr_claims_present` * invariant failure on CLI atlases despite legitimate ADR claims). * * Post-v0.7.2 substrate-convention alignment: CLI + Skill + validator * all emit/expect `adr:` for ADR-source claims. */ export declare function deriveSourceName(absPath: string): string; /** * Exposed so callers (or the final cross-check) can verify the pipeline's * output round-trips correctly through the storage layer. */ export declare function roundTripAtlas(db: DatabaseInstance): string; /** * Re-export for caller convenience when constructing a mock client. */ export type { ExtractionClient } from "./anthropic-client.js"; export interface DocstringExtractionResult { /** Number of claims written to the database. */ claimsWritten: number; /** Number of symbols listSymbols returned for this file. */ symbolsProcessed: number; /** * Number of exported symbols (per language convention) considered * for docstring extraction. Subset of symbolsProcessed. */ symbolsExported: number; /** * Number of symbols that had a non-null/non-empty docstring and * triggered an extraction API call. Subset of symbolsExported. */ symbolsWithDocstring: number; /** Cumulative count of unresolved symbol_candidates across all claims. */ unresolvedCandidates: number; /** Number of API calls made (one per symbolsWithDocstring). */ apiCalls: number; /** Token usage across all API calls. */ totalUsage: UsageInfo; /** Per-symbol errors (API failures, etc.). Pipeline continues on error. */ errors: Array<{ symbolId: SymbolId; error: string; }>; } /** * Extract architectural claims from docstrings in a single source file. * * For each exported symbol with a non-empty docstring: query the * adapter's `getDocstring`, send to the extraction API (which uses * `EXTRACTION_PROMPT` per Step 9 H1 design), and persist resulting * claims with `source: "docstring:"` + two-channel * attribution: * - **Provenance channel (always)**: documented symbol's `SymbolId` * attached to every claim emitted from its docstring. * - **Cross-reference channel**: claim's `symbol_candidates` resolved * via the existing `resolveCandidates` path (same code path as * ADR claims). * * Idempotent at file granularity: existing claims for `relPath` are * cleared before extraction (matches `writeClaimsForFile` discipline). * * Per Step 10 ship criterion 6 + Step 9 open question (d): per-symbol * single-call API shape; not batched. Step 11 may revisit per-language. */ export declare function extractDocstringsForFile(db: DatabaseInstance, adapter: LanguageAdapter, relPath: string, fileSha: string, inventory: SymbolInventory, anthropicClient: ExtractionClient): Promise; /** * Per-language exported-symbol check. * * Go: first character uppercase (godoc convention). For * interface-method-flattened names like "Shape.Area", check the * trailing component (matches listSymbols' shape per ADR-14 * §Decision 4). * * TypeScript / Python: deferred to Step 11 (returns true permissively * for now; both adapters' `getDocstring` returns null until Step 11 * implementation, so no docstring claims are produced for those * languages regardless of this check). */ export declare function isExportedSymbol(name: string, language: LanguageCode): boolean; //# sourceMappingURL=pipeline.d.ts.map