/** * Stage 5 — Extract (LLM JSON-mode per chunk) * * Emits typed atoms {type, text, importance, confidence, evidence}. * Zod-validates the JSON response. A parse/validation failure throws * TransientError — LLM JSON output is stochastic, so the worker retries * (with backoff, up to its normal attempt cap) before poisoning the job, * rather than dropping a whole session's memories on one bad sample. * Throws BudgetExceeded if over cap. */ import type { LLMProvider } from '../../contracts/index.js'; import { type Atom, type ExtractProfile } from '../prompts/extract.js'; import { BudgetTracker, BudgetExceeded } from '../../budget/tracker.js'; import type { DistillCostCapTracker } from '../cost-cap.js'; export type { ExtractProfile }; export declare const EXTRACT_TEMPERATURE: number; /** Pass-A extraction output ceiling (tokens). Pass-B sweeper calls may * override it downward via the centrally-resolved clerk tuning * (EXTRACTION_PASS_B_DEFAULTS.maxTokens) — see callExtract's * maxTokensOverride doc. Exported for eval run-provenance manifests * (scripts/eval/shared/run-constants.ts) so recorded runs derive the value * from this constant instead of hand-copying the literal (ADR-016). */ export declare const PASS_A_MAX_TOKENS = 6000; export { BudgetExceeded }; export type { Atom }; export interface ExtractResult { chunkIndex: number; atoms: Atom[]; usageUsd: number; retried: boolean; /** * FEAT-481 SLICE-430: per-reason drop counts from this chunk's * filterAtomRelations pass (design doc §2.2/§2.3) -- 'predicate_invalid', * 'missing_fields', 'subject_equals_object', 'no_hallucination_guard'. * Empty object when the chunk's atoms had no relations[] to filter, or * every triple survived. Never includes reasons with a zero count. See * src/storage/relation-guard-log.ts for why this is persisted. */ relationDropCounts: Record; /** * Issue #207: per-reason drop counts from this chunk's filterAtomEntities * pass -- 'too_short', 'bare_issue_ref', 'bare_number', 'missing_name', * 'not_an_object'. Same shape/semantics as relationDropCounts above (empty * object when nothing was dropped, never a zero-count entry). See * src/storage/entity-guard-log.ts for why this is persisted. */ entityDropCounts: Record; /** * FEAT-485: count of whole ATOMS dropped by requireEvidenceForRichTypes * (below) because they were type `lesson`/`decision` with no non-empty * `evidence` string -- keyed 'lesson' | 'decision'. Empty object when * nothing was dropped. See src/storage/evidence-guard-log.ts for why this * is persisted (same "distinguish never-emitted from dropped" rationale as * relationDropCounts/entityDropCounts, one level up: a whole atom, not a * relation triple or an entity). */ evidenceDropCounts: Record; /** * FEAT-552 AC-A1: present ONLY when this chunk's atoms were recovered via * deterministic JSON-truncation salvage after a normal JSON.parse/Zod * failure (see tryParseAtoms's salvage fallback, ./parse-salvage.ts). * Absent (not merely zero-valued) on every chunk that parsed cleanly on * the first attempt — the healthy path stays byte-identical to pre- * FEAT-552 behavior. `recovered` counts atoms whose raw JSON object was * successfully reconstructed and validated; `lost` counts fragments the * salvage scanner could not use (a truncated trailing object, or one * with a detected duplicate key — AC-A2). */ salvage?: { recovered: number; lost: number; }; } /** * Extract atoms from a single compacted chunk. * * Parse / Zod validation failure → throws TransientError. The worker * classifies this as transient and retries (with backoff) up to its normal * attempt cap before poisoning the job — LLM JSON output is stochastic (the * same chunk can parse cleanly on the very next call), so a single flaky * sample must not permanently drop a session's memories. * * Follow-up (not yet wired): EXTRACTION_STRICT_PROMPT already exists as a * stricter variant, but no attempt number is threaded from the worker's * retry count down into this function, so retries currently reuse the base * prompt rather than escalating to it. */ export declare function extractChunk(chunkIndex: number, text: string, provider: LLMProvider, budget: BudgetTracker, capUsd: number, /** FEAT-479 AC-2: already-precedence-resolved (envelope > config default) * by the caller (see PipelineContext.extractProfile / runPipeline) — * defaults to 'engineering', the byte-identical pre-FEAT-479 behavior, * for callers that don't pass one. `ASTRA_EXTRACT_PROMPT` is applied on * top of this, per call, inside resolveExtractionPrompt. */ extractProfile?: ExtractProfile, /** Temporal-grounding fix (2026-07-13): the session's observation date as * an ISO calendar date (`YYYY-MM-DD`), threaded from the already-computed * `PipelineContext.capturedAtMs` (see pipeline.ts's stage-5 call site). * When present, `callExtract` prepends an "Observation date: ..." line to * the user message so the model can resolve relative time expressions * ("yesterday", "last year") to absolute dates directly in atom text — * `valid_from` alone earns nothing here, since the LoCoMo/real answerer * only ever sees `text` (see prompts/extract.ts's date-grounding rule). * `undefined` (the default) is byte-identical to pre-fix behavior — every * caller that has no real anchor (legacy v0.0 envelopes, direct * `/remember` calls) sees no change. */ sessionDateIso?: string, /** Dual-pass extraction (opt-in): when present, this REPLACES the profile/ * env-resolved prompt entirely — `extractProfile` is still accepted (so * checkpoint variant keying and call signatures stay uniform) but plays no * role in prompt selection once this is set. Used by extractSpecifics() * below to run the "specifics sweeper" prompt without going through * resolveExtractionPrompt's profile/env precedence chain, which is pass-A * only by design. `undefined` (the default) is byte-identical to pre- * dual-pass behavior for every existing caller. */ promptOverride?: string, /** Opt-in call-count/wall-clock cap (`config.distill.costCap`, see * `src/distill/cost-cap.ts`) — `undefined`/disabled is a pure no-op. * Shares the SAME tracker instance compactChunk() checks, so the budget * is one combined compact()+extract() total per job. Checked BEFORE the * LLM call; when it trips, this chunk contributes zero atoms (same * shape as the empty-text case above) and no `provider.chat()` call is * made. */ costCap?: DistillCostCapTracker, /** See callExtract's maxTokensOverride doc — threaded verbatim; pass-B * sweeper calls set it (extractSpecifics), pass A never does. */ maxTokensOverride?: number): Promise; /** * Classify a candidate entity name as junk, or return null if it's fine. * Exported so the doctor "Entity name quality" canary (src/doctor/checks.ts) * can apply the identical rule to existing `entities` rows and measure the * junk rate already sitting in the corpus, not just guard new writes. * * Deliberately narrow: a name that merely CONTAINS a number ("FEAT-402", * "sqlite-vec", "Node 20") or is a short but real word ("Go", "C#") must * never trip this — only a name that IS, in its entirety, a bare issue/PR * reference, a bare number, or below the length floor. */ export declare function classifyJunkEntityName(name: string, kind?: string): string | null; /** * Extract atoms from all compacted chunks, up to `concurrency` at a time * (FEAT-487). * * Stops dispatching further chunks at the first BudgetExceeded (or any other * error, e.g. a TransientError parse failure) — results stay in chunk-index * order regardless of completion order. See src/distill/concurrency.ts for * the full invariant contract `mapWithConcurrency` provides. * * `concurrency` defaults to 1 — BYTE-IDENTICAL to the pre-FEAT-487 * sequential `for…of await` loop this replaces. Production callers resolve * the real value from config via `resolveChunkConcurrency` * (src/distill/pipeline.ts). * * `jobKey` (chunk-retry-amplification fix) opts into per-chunk * checkpointing — same contract as compact()'s `jobKey` param (see * 04-compact.ts's doc comment for the full rationale): a chunk whose result * is already cached under `jobKey` is skipped rather than re-dispatched, and * every fresh success is cached before extract() returns. Omitted (the * default), behavior is byte-identical to pre-fix — no cache lookup, no * cache write, every call re-dispatches every chunk. * * `sessionDateIso` (temporal-grounding fix) — see extractChunk's doc * comment — is threaded unchanged to every chunk's extractChunk call. */ export declare function extract(chunks: Array<{ index: number; text: string; }>, provider: LLMProvider, budget: BudgetTracker, capUsd: number, extractProfile?: ExtractProfile, concurrency?: number, jobKey?: string, sessionDateIso?: string, /** Opt-in call-count/wall-clock cap — see `extractChunk`'s param doc and * `src/distill/cost-cap.ts`. Pass the SAME tracker instance given to * compact() so the two stages share one per-job budget. */ costCap?: DistillCostCapTracker): Promise; /** * Dual-pass extraction, Pass B ("specifics sweeper") — opt-in via * `distill.extractionPasses: 2` (src/config/config.ts). Runs * EXTRACTION_SYSTEM_PROMPT_SPECIFICS_SWEEPER (prompts/extract.ts) over the * SAME compacted chunks pass A already processed, on the SAME provider * instance — no new provider config, no new budget surface. * * Mirrors extract()'s chunk-checkpoint contract exactly (same jobKey, same * chunk indices) but under its OWN checkpoint variant (`'specifics-sweeper'`) * so a collision with pass A's cached results under the same jobKey/index is * impossible — see chunk-checkpoint.ts's own doc comment on why `variant` * disambiguation is load-bearing, not decoration. * * Caller contract (pipeline.ts): only invoke this AFTER pass A's `extract()` * call has returned successfully for the run — never on a failed/aborted * pass A. This is enforced by the CALLER's control flow (pass A's own * try/catch already re-throws before this would be reached), not by this * function itself. * * `costCap` — same shared-tracker contract as `extract()`'s own `costCap` * param: pass the SAME instance given to compact()/extract() so pass B * shares the job's combined call-count/wall-clock budget. Previously omitted * entirely here, which left the sweeper pass unbounded even when * `config.distill.costCap` was enabled (pipeline.ts had no way to pass a * tracker in) — fixed alongside issue #396. */ export declare function extractSpecifics(chunks: Array<{ index: number; text: string; }>, provider: LLMProvider, budget: BudgetTracker, capUsd: number, concurrency?: number, jobKey?: string, sessionDateIso?: string, costCap?: DistillCostCapTracker, /** Clerk-tuning output cap for sweeper calls (2026-07-18) — the caller * (runPipeline) resolves it centrally via resolveExtractionPassBTuning; * `0`/undefined = no override (pass-A ceiling). */ maxTokens?: number): Promise;