Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(extraction): date grounding rewrites relative dates as absolute dates instead of keeping the phrase beside them (rule v2)

garrytan7eba8a802894
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index dcd99e0528..e2914b68ea 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/chat-usage.ts` + `src/core/ops/usage.ts` — durable per-call chat usage accounting. `gateway.chat()` calls `recordChatUsage` at its SUCCESS boundary (production provider path AND test-transport path) with the answering model + token usage; the record lands in the `chat_usage_log` table (migration v140) via an injected sink (`setChatUsageSink` — no engine import here, so the gateway imports this leaf statically without deepening a cycle). Phase attribution is best-effort via AsyncLocalStorage (`withChatPhase`): the minion worker AND the cycle's inline drain (`inline-drain.ts`) both wrap handler execution in `job:<name>`, a cycle phase that meters its own spend wraps itself in `phase:<name>` (dream synthesize does), and direct callers record phase NULL. The innermost wrap wins, which is the point — a child drained INSIDE a wrapped phase must carry its own `job:` tag or the phase tag absorbs every child's spend and the ledger double-counts (one ledger per surface: `minion_jobs` stays the child-spend authority, the phase row is the orchestrator's own calls). Pricing resolves through `CANONICAL_PRICING` (`estimateChatCostUsd`, cache_read/cache_write at provider cache rates when the table carries them); unknown models record `cost_usd = NULL`, never a fake 0. Accounting is strictly fail-open + fire-and-forget: a sink error must never break a chat call. The `get_usage` op (admin scope, NOT read — `chat_usage_log` has no source dimension, so a source-restricted/federated token must not see brain-wide spend telemetry) returns per-model/per-phase aggregates only, plus an explicit `coverage` block stating what the ledger does NOT capture (subagent raw-SDK path, embeddings, pre-sink/pre-v140 calls, failed calls); `budget-tracker.ts` remains the pessimistic in-flight spend gate — this table is the after-the-fact ledger.
-- `src/core/ai/date-grounding.ts` — the time vocabulary every extraction prompt shares: observation time (when text was written or said), event/validity time (`facts.valid_from`), recording time (`created_at`). `resolveObservationDate` (filename / `date` / `published` / created keys via `computeEffectiveDate`; never `event_date`, row timestamps or now), `observationDateFrom` (turn/message timestamps), `observationDateRule` (static system-prompt rule: resolve relative dates against the observation date, keep the phrase and add the date, unknown → keep as written), `observationDateLine` (user-message date or `unknown`), `parseExtractedEventDate` (YYYY-MM-DD, 1900..now+1y), `resolveValidFrom` (extracted > caller > observation > now), `hasUnresolvedRelativeDate` (judge-free eval check). The fact extractor, chronicle judge, dream synthesis, extract_atoms and propose_takes add the rule when `extraction.date_grounding` is on (default off); page-body facts default to the page's observation date regardless. Pinned by `test/ai/date-grounding.test.ts`, `test/facts/extract-date-grounding.test.ts`, `test/facts/backstop-page-date.test.ts`.
+- `src/core/ai/date-grounding.ts` — the time vocabulary every extraction prompt shares: observation time (when text was written or said), event/validity time (`facts.valid_from`), recording time (`created_at`). `resolveObservationDate` (filename / `date` / `published` / created keys via `computeEffectiveDate`; never `event_date`, row timestamps or now), `observationDateFrom` (turn/message timestamps), `observationDateRule` (static system-prompt rule: rewrite relative dates as absolute dates or bounds resolved against the observation date, never leaving the phrase beside its date; unknown → keep as written), `observationDateLine` (user-message date or `unknown`), `parseExtractedEventDate` (YYYY-MM-DD, 1900..now+1y), `resolveValidFrom` (extracted > caller > observation > now), `hasUnresolvedRelativeDate` (judge-free eval check). The fact extractor, chronicle judge, dream synthesis, extract_atoms and propose_takes add the rule when `extraction.date_grounding` is on (default off); page-body facts default to the page's observation date regardless. Pinned by `test/ai/date-grounding.test.ts`, `test/facts/extract-date-grounding.test.ts`, `test/facts/backstop-page-date.test.ts`.
- `src/core/ai/defaults.ts` — leaf module for canonical embedding and reranker defaults, without a gateway import. Voyage `voyage:voyage-4` at 1024 dimensions is the new-install embedding default; `voyage:rerank-2.5` is the runtime/mode-bundle reranker default. `renderCanonicalMigrationCommands` supplies an explicit-target cost preview and an OpenAI keep-width alternative where supported. These constants do not establish the identity of vectors in an existing database and must never authorize automatic provider conversion. Init preserves explicit choices, writes no reranker row when the Voyage key is available, disables reranking for keyed installs without that key, and preserves keyless setup.
- `src/core/ai/dims.ts` — per-provider `providerOptions` resolver for embed-time dimension passthrough; the single source of truth for "which provider needs which knob to produce `vector(N)`". Exports `dimsProviderOptions(implementation, modelId, dims)` (called by `embed()` in `gateway.ts`), `VOYAGE_OUTPUT_DIMENSION_MODELS` (private const — the 7 hosted Voyage models that accept `output_dimension`: `voyage-4-large`, `voyage-4`, `voyage-4-lite`, `voyage-3-large`, `voyage-3.5`, `voyage-3.5-lite`, `voyage-code-3` — nano deliberately excluded), `VOYAGE_VALID_OUTPUT_DIMS = [256, 512, 1024, 2048] as const`, `supportsVoyageOutputDimension(modelId)`, `isValidVoyageOutputDim(dims)`. Voyage path uses the SDK-supported `dimensions` field (`{ openaiCompatible: { dimensions: N } }`), NOT Voyage's `output_dimension` wire-key — the `voyageCompatFetch` shim in `gateway.ts:541` translates `dimensions → output_dimension` before the HTTP body is built (the AI SDK's openai-compatible adapter doesn't recognize the wire-key, so sending it from here would be silently dropped and Voyage would return its default 1024-dim). Runtime guard: when a Voyage flexible-dim model is configured with `dims` outside `VOYAGE_VALID_OUTPUT_DIMS`, throws `AIConfigError` with a paste-ready `gbrain config set embedding_dimensions <256|512|1024|2048>` hint at the embed boundary (most common trigger: `embedding_model: voyage:voyage-4-large` without `embedding_dimensions`, retaining an incompatible 1536-dimensional setting from another provider). Every lookup in this module folds through the private `modelMatchKey` (trim + lowercase) so cased hub-form ids (`Qwen/Qwen3-Embedding-4B`) match the all-lowercase tables — the folded key is a MATCH key only, never sent to a provider (wire model ids are case-sensitive; error messages keep the original id so they stay paste-ready); the Qwen3-Embedding native-width table lives at module scope alongside the other dim tables. Consequence, deliberate: a cased Voyage/Perplexity config matches and fails loudly at init when its `dims` is invalid, rather than skipping validation and silently producing wrong-width vectors.
diff --git a/src/core/ai/date-grounding.ts b/src/core/ai/date-grounding.ts
index 59a371782c..c32677d685 100644
--- a/src/core/ai/date-grounding.ts
+++ b/src/core/ai/date-grounding.ts
@@ -15,7 +15,9 @@
* interpret text.
*
* WHY. "User went to Lisbon last week" is useless months later; the extractor
- * must write "last week (week of 2026-03-02)". Resolving against today's date
+ * must write "the week of 2026-03-02". Keeping the relative phrase beside the
+ * date ("two days ago (2026-03-02)") reads wrong once the fact is shown under
+ * its event date: a reader applies "two days ago" a second time. Resolving against today's date
* (the run date) silently re-dates historical imports, so the rule names the
* observation date and forbids "today". When the observation date is unknown
* the phrase is kept as written — never a guessed date.
@@ -30,7 +32,7 @@
import { computeEffectiveDate, parseDateLoose } from '../effective-date.ts';
/** Prompt-text identity for the grounding rule (provenance; bump on rule edits). */
-export const DATE_GROUNDING_RULE_VERSION = 'date-grounding-v1';
+export const DATE_GROUNDING_RULE_VERSION = 'date-grounding-v2';
/** Where an observation date came from. `caller` = supplied by the code path (turn timestamp, message date). */
export type ObservationDateSource = 'caller' | 'filename' | 'date' | 'published' | 'created';
@@ -95,11 +97,13 @@ export function observationDateFrom(value: Date | string | null | undefined): Ob
export function observationDateRule(): string {
return [
'Dates: the input states its observation date (when the text was written or said).',
- 'Resolve every relative time reference (yesterday, last week, next month, recently, in 18 months, by Friday)',
- "against the observation date, never against today's date. Keep the original phrase and add the absolute",
- "date or bound in parentheses: 'last week (week of 2026-03-02)', 'by Friday (by 2026-03-13)',",
- "'recently (before 2026-03-10)'. Never turn an absolute date into a vague one. If the observation date is",
- 'unknown, keep relative phrases exactly as written and do not invent dates.',
+ 'Rewrite every relative time reference (yesterday, last week, next month, recently, in 18 months, by Friday,',
+ 'for about a month) as an absolute date or bound resolved against the observation date,',
+ "never against today's date, so the saved text means the same thing on any later day:",
+ "'flew to Lisbon last week' -> 'flew to Lisbon the week of 2026-03-02', 'due by Friday' -> 'due by 2026-03-13',",
+ "'has played for about a month' -> 'has played since about 2026-02-10', 'recently moved' -> 'moved before 2026-03-10'.",
+ 'Do not leave the relative phrase beside its date. Never turn an absolute date into a vague one. If the observation',
+ 'date is unknown, keep relative phrases exactly as written and do not invent dates.',
'Never alter text you are asked to quote verbatim.',
].join('\n');
}
diff --git a/test/ai/date-grounding.test.ts b/test/ai/date-grounding.test.ts
index 138e253c37..51f355c3e1 100644
--- a/test/ai/date-grounding.test.ts
+++ b/test/ai/date-grounding.test.ts
@@ -42,6 +42,7 @@ describe('prompt text', () => {
test('the system rule is static and forbids resolving against today', () => {
expect(observationDateRule()).toBe(observationDateRule());
expect(observationDateRule()).toContain("never against today's date");
+ expect(observationDateRule()).toContain('Do not leave the relative phrase beside its date');
expect(observationDateRule()).not.toMatch(/\d{4}-\d{2}-\d{2}T/);
});
test('the user line carries the date or says unknown', () => {
diff --git a/test/facts/extract-date-grounding.test.ts b/test/facts/extract-date-grounding.test.ts
index 2d7fe572c0..0eb8abc4a3 100644
--- a/test/facts/extract-date-grounding.test.ts
+++ b/test/facts/extract-date-grounding.test.ts
@@ -76,7 +76,7 @@ describe('extractor prompt variants', () => {
describe('extractor-stated event dates', () => {
test('a valid date becomes valid_from; malformed and far-future dates are dropped; grounding off ignores the field', async () => {
const reply = { facts: [
- { fact: 'User flew to Lisbon last week (week of 2026-03-02)', kind: 'event', notability: 'high', valid_from: '2026-03-04' },
+ { fact: 'User flew to Lisbon the week of 2026-03-02', kind: 'event', notability: 'high', valid_from: '2026-03-04' },
{ fact: 'User plans a trip', kind: 'event', notability: 'high', valid_from: 'next spring' },
{ fact: 'User will retire', kind: 'event', notability: 'high', valid_from: '2099-01-01' },
] };