/** * Date-grounding retry (Graphiti pattern) — a second, narrow LLM call fired * ONLY on atoms whose text still carries an unresolved relative-date * expression after the main extraction prompt's own resolve-in-place * instruction (see prompts/extract.ts's "Date grounding" rule, PR #189/#191) * — that instruction is not reliably followed by every model in production * (~13% of temporal atoms measured still relative on the eval store). This * is a second chance at the SPECIFIC missing field, not a redesign — mirrors * graphiti's edge_operations.py:576-620 (a dedicated single-purpose call for * exactly the field that came back null/unresolved). * * A REGEX rewrite of this exact problem was tried and closed unmerged: PR * #257 fabricated dates across three adversarial rounds because deciding * whether a phrase like "last week" is a free-standing, session-relative * adverbial or a modifier bound inside a DIFFERENT noun's own timeline (“the * project's last week”, “her last week”) is a syntactic question a regex * lookaround cannot answer — see * docs/research/20260713-temporal-grounding-regex-postmortem.md. This module * still uses a regex (RELATIVE_DATE_DETECT_RE below) — but ONLY to decide * whether to ASK, never to answer. The actual resolution (or the decision to * leave the sentence alone) is made by the LLM, which reads the whole * sentence for its structure the way a regex lookaround cannot. Over-firing * the detector only costs one extra bounded call that may itself correctly * decline to rewrite; under-firing silently leaves a real relative phrase * ungrounded — the asymmetry is intentional. * * Placement: called from the PIPELINE (pipeline.ts, between stage 6 reduce * and stage 7 memory-normalize) — not from 05-extract.ts / the extraction * prompt (prompts/extract.ts). That file has two sibling PRs contending for * it as of 2026-07-13; this fix belongs to the pipeline, not the prompt. * * Contract, load-bearing: * - NEVER touches `atom.evidence` (the verbatim-quote/citation field) — only * `atom.text`. Every code path below destructures/returns `text` alone. * - Failure of any kind (parse, network, timeout, thrown, malformed JSON) is * a no-op: the atom's text is left EXACTLY as it was. Distill must never * block or poison a job on this retry. * - Reuses the same LLMProvider the caller already has (extraction tier) — * no new provider config surface, same posture as contradiction-judge.ts. * - No dollar-budget check (FEAT-482 lesson, see contradiction-judge.ts's own * doc comment): codex-subscription always reports `usage.usd: 0`, so a * dollar cap here could never trip. `maxCalls` bounds CALL COUNT instead — * the real scarce resource for a metered subscription endpoint. * * GRANULARITY BUG (found in review, 2026-07-13, before this PR's first * merge attempt): an early version of the system prompt let the model * resolve "last week" all the way down to a specific day ("8 July 2023"). * The source text never said WHICH day within that week — a specific day is * an invented fact, not a grounded one, even though it isn't the #257 * class of fabrication (wrong noun/referent). Proof it was real: run twice * against the same anchor, the model returned two DIFFERENT days for the * identical input ("3 July 2023" vs "8 July 2023") — non-determinism on a * fixed anchor is itself the signal that the value wasn't derivable and the * model was guessing. Fixed by the GRANULARITY RULE in SYSTEM_PROMPT below: * a week/month/year-granularity source expression must resolve to a * week/month/year-granularity output (e.g. "the week before 15 July 2023"), * never collapsed to a specific day. Only genuinely day-determining source * expressions (yesterday/today/tomorrow, a named weekday, "N days ago") * resolve to a specific day. Regression coverage: * tests/distill/ground-dates.test.ts's granularity block, and * scripts/eval/date-grounding-retry-adversarial.mts's determinism check * (same input run 3+ times against the real provider, output must be * byte-identical every time). */ import type { LLMProvider } from '../contracts/llm.js'; import type { ReducedAtom } from './stages/06-reduce.js'; /** * Stable marker embedded in the system prompt so a mock LLMProvider (tests, * ASTRA_MEMORY_MOCK_PROVIDERS=1) can route this call to a dedicated branch * before any extraction/json-mode detection heuristic misclassifies it — * mirrors CONTRADICTION_JUDGE_MARKER's role in contradiction-judge.ts. */ export declare const DATE_GROUNDING_RETRY_MARKER = "astramem-date-grounding-retry-v1"; /** Exported so a caller (or a test) can check candidacy without spending a call. */ export declare function hasUnresolvedRelativeDate(text: string): boolean; export interface GroundDatesResult { atoms: ReducedAtom[]; /** Atoms whose text matched the detector AND had a real session anchor — * i.e. the retry call was actually fired for them. */ fired: number; /** Subset of `fired` whose text the LLM actually changed. `fired - * resolved` is NOT a failure by itself — it includes the LLM correctly * declining to rewrite a phrase that wasn't genuinely session-relative, * as well as parse/network fallbacks (see `errors`). */ resolved: number; /** Subset of `fired` that fell back to unchanged text because the call * threw or the response failed to parse — a strict subset of `fired - * resolved`, kept separate so a caller/test can distinguish "the model * declined on purpose" from "the retry mechanism itself broke". */ errors: number; /** Total atoms considered — the denominator for a fire-rate measurement. */ totalAtoms: number; /** True iff `maxWallClockMs` tripped before every candidate atom got a * call — distinguishes "ran out of time" from "ran out of candidates" the * same way consolidate.ts's `contradictionWallClockCapReached` does. */ wallClockCapReached: boolean; } export interface GroundDatesOptions { /** Safety valve bounding total LLM calls this invocation can make, * independent of how many atoms match the detector. This runs against one * session's already-reduced atoms (typically single-digit to low tens), * so blowup risk is far lower than the pairwise contradiction judge — this * is cheap insurance against a pathological transcript, not a routine * limiter. Mirrors consolidate.ts's maxPerRun call-count cap (FEAT-482). */ maxCalls?: number; /** * FEAT-482 fold (worker-starvation wave): wall-clock cap (ms) on the * ENTIRE grounding sweep within one `groundAtomDates()` invocation — * mirrors consolidate.ts's dual-cap shape (contradiction-judge.ts / * dup-judge.ts's `maxPerRun` + `maxWallClockMs`). `maxCalls` alone bounds * CALL COUNT, not TIME: a slow or rate-limited provider can still stall a * distill job well past what `maxCalls` alone protects against if each * call is slow enough — the exact FEAT-482 incident shape (~245 calls at * ~13/min against a throttled endpoint, 10+ minutes, not a count * problem). Once exceeded, remaining candidate atoms fall through * UNCHANGED — same fail-open contract as the `maxCalls` cap, never a * partial/guessed resolution. Default 300_000 (5 min), matching * contradictionDetection/dupJudge/atomTriage/gatekeeper's shared default. */ maxWallClockMs?: number; log?: (message: string) => void; } /** * Runs the date-grounding retry over a reduced atom list. `sessionDateIso` * absent (no real capture-date anchor available for this session — legacy * v0.0 envelopes, direct /remember calls) is a total no-op: every atom * passes through unchanged, byte-identical to the pre-retry pipeline, since * there is nothing to ground against. */ export declare function groundAtomDates(atoms: ReducedAtom[], sessionDateIso: string | undefined, llm: LLMProvider, opts?: GroundDatesOptions): Promise;