Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
ai: date-grounding module — observation/event/recording time vocabulary and the relative-date rule
garrytanc4be20d9dee6
diff --git a/src/core/ai/date-grounding.ts b/src/core/ai/date-grounding.tsnew file mode 100644index 0000000000..59a371782c--- /dev/null+++ b/src/core/ai/date-grounding.ts@@ -0,0 +1,162 @@+/**+ * date-grounding.ts — the time vocabulary and the relative-date rule shared by+ * every LLM extraction prompt.+ *+ * THREE TIMES. Every stored claim can carry three different times; code and+ * prompts must never conflate them:+ *+ * observation time when the source text was written or said (a chat turn's+ * timestamp, a dated note's filename or `date:`). Relative+ * phrases ("last week", "by Friday") resolve against it.+ * event/validity when the claim was true in the world (`facts.valid_from`;+ * time later, edge validity). May differ from observation time:+ * a 2026-03 note says "we closed the round in 2024".+ * recording time when GBrain stored it (`created_at`). Never used to+ * 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+ * (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.+ *+ * `resolveObservationDate` deliberately does NOT use a page's `event_date`+ * (an event's own time, not when the note was written) nor the `fallback`+ * effective-date source (row creation / update time), and never returns now.+ *+ * Pure: no engine, no IO. Shared API (other extraction work imports it).+ */++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';++/** Where an observation date came from. `caller` = supplied by the code path (turn timestamp, message date). */+export type ObservationDateSource = 'caller' | 'filename' | 'date' | 'published' | 'created';++export interface ObservationDate {+ /** Calendar date, YYYY-MM-DD. */+ date: string;+ source: ObservationDateSource;+}++const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;++/** YYYY-MM-DD of a Date in UTC. */+function isoDay(d: Date): string {+ return d.toISOString().slice(0, 10);+}++/**+ * Observation date of a page: its filename/slug date, frontmatter `date`,+ * `published`, or a created key — whichever `computeEffectiveDate`'s+ * precedence picks once `event_date` is removed. Null when none exists; never+ * the row timestamps and never now().+ */+export function resolveObservationDate(page: {+ slug: string;+ frontmatter?: Record<string, unknown> | null;+ /** Import basename without extension, when known. Defaults to the slug's last segment. */+ filename?: string | null;+ /** `brain.timezone` for offset-less datetimes. */+ timeZone?: string;+}): ObservationDate | null {+ const { event_date: _eventDate, ...frontmatter } = page.frontmatter ?? {};+ const invalid = new Date(Number.NaN);+ const result = computeEffectiveDate({+ slug: page.slug,+ frontmatter,+ filename: page.filename ?? page.slug.split('/').pop() ?? null,+ timeZone: page.timeZone,+ createdAt: invalid,+ updatedAt: invalid,+ });+ if (!result.date || !result.source) return null;+ if (result.source !== 'filename' && result.source !== 'date' && result.source !== 'published' && result.source !== 'created') {+ return null;+ }+ return { date: isoDay(result.date), source: result.source };+}++/** An observation date supplied directly by a code path (turn timestamp, message date). Null when unparseable. */+export function observationDateFrom(value: Date | string | null | undefined): ObservationDate | null {+ if (value === null || value === undefined) return null;+ const d = value instanceof Date ? value : parseDateLoose(value);+ if (!d || Number.isNaN(d.getTime())) return null;+ return { date: isoDay(d), source: 'caller' };+}++/**+ * The rule text for a SYSTEM prompt. Static (no date inside), so a system+ * prompt that embeds it stays byte-identical across calls and prompt-cache+ * friendly; the date itself goes in the user message via `observationDateLine`.+ */+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.',+ 'Never alter text you are asked to quote verbatim.',+ ].join('\n');+}++/** The user-message line carrying the observation date (or its absence). */+export function observationDateLine(observation: ObservationDate | null): string {+ return observation+ ? `Observation date: ${observation.date} (when this text was written or said; resolve relative dates against it).`+ : 'Observation date: unknown (keep relative dates as written).';+}++/** Earliest event date an extractor may assert. */+const MIN_EVENT_YEAR = 1900;++/**+ * Validate an extractor-stated event date (`YYYY-MM-DD`). Rejects malformed+ * values, dates before 1900, and dates more than one year after `now`+ * (the same forward window effective dates use). Returns a UTC-midnight Date.+ */+export function parseExtractedEventDate(raw: unknown, now: Date = new Date()): Date | null {+ if (typeof raw !== 'string') return null;+ const s = raw.trim();+ if (!DAY_RE.test(s)) return null;+ const d = new Date(`${s}T00:00:00.000Z`);+ if (Number.isNaN(d.getTime()) || isoDay(d) !== s) return null;+ if (d.getUTCFullYear() < MIN_EVENT_YEAR) return null;+ const max = new Date(now.getTime());+ max.setUTCFullYear(max.getUTCFullYear() + 1);+ if (d.getTime() > max.getTime()) return null;+ return d;+}++/** Which input set a fact's valid_from. */+export type ValidFromSource = 'extracted' | 'caller' | 'observation' | 'now';++/**+ * `facts.valid_from` precedence: an event date the extractor stated (already+ * validated) > a caller-supplied time > the observation date > now.+ */+export function resolveValidFrom(input: {+ extracted?: Date | null;+ caller?: Date | null;+ observation?: ObservationDate | null;+ now?: Date;+}): { date: Date; source: ValidFromSource } {+ if (input.extracted) return { date: input.extracted, source: 'extracted' };+ if (input.caller) return { date: input.caller, source: 'caller' };+ if (input.observation) return { date: new Date(`${input.observation.date}T00:00:00.000Z`), source: 'observation' };+ return { date: input.now ?? new Date(), source: 'now' };+}++/**+ * Judge-free check used by tests and the eval: true when `text` holds a+ * relative time phrase NOT followed by a parenthesized absolute date or bound.+ */+const RELATIVE_PHRASE_RE = /\b(yesterday|today|tomorrow|tonight|last (?:week|month|year|night|weekend|monday|tuesday|wednesday|thursday|friday|saturday|sunday)|next (?:week|month|year|weekend|monday|tuesday|wednesday|thursday|friday|saturday|sunday)|this (?:week|month|year|weekend|morning|afternoon|evening)|recently|\d+ (?:days?|weeks?|months?|years?) ago|in \d+ (?:days?|weeks?|months?|years?))\b(?!\s*\()/i;++export function hasUnresolvedRelativeDate(text: string): boolean {+ return RELATIVE_PHRASE_RE.test(text);+}diff --git a/test/ai/date-grounding.test.ts b/test/ai/date-grounding.test.tsnew file mode 100644index 0000000000..138e253c37--- /dev/null+++ b/test/ai/date-grounding.test.ts@@ -0,0 +1,86 @@+import { describe, test, expect } from 'bun:test';+import {+ hasUnresolvedRelativeDate,+ observationDateFrom,+ observationDateLine,+ observationDateRule,+ parseExtractedEventDate,+ resolveObservationDate,+ resolveValidFrom,+} from '../../src/core/ai/date-grounding.ts';++describe('resolveObservationDate', () => {+ test('dated slugs and filenames are observation dates', () => {+ expect(resolveObservationDate({ slug: 'meetings/2026-04-03-acme-example-sync' })).toEqual({ date: '2026-04-03', source: 'filename' });+ expect(resolveObservationDate({ slug: 'daily/2026-05-20' })).toEqual({ date: '2026-05-20', source: 'filename' });+ });++ test('frontmatter date and published count; event_date never does', () => {+ expect(resolveObservationDate({ slug: 'notes/x', frontmatter: { date: '2025-11-02' } })).toEqual({ date: '2025-11-02', source: 'date' });+ expect(resolveObservationDate({ slug: 'writing/y', frontmatter: { published: '2024-01-15' } })).toEqual({ date: '2024-01-15', source: 'published' });+ expect(resolveObservationDate({ slug: 'events/launch', frontmatter: { event_date: '2026-09-01' } })).toBeNull();+ expect(resolveObservationDate({ slug: 'events/launch', frontmatter: { event_date: '2026-09-01', date: '2026-03-01' } }))+ .toEqual({ date: '2026-03-01', source: 'date' });+ });++ test('undated pages return null, never now or row timestamps', () => {+ expect(resolveObservationDate({ slug: 'people/alice-example' })).toBeNull();+ expect(resolveObservationDate({ slug: 'people/alice-example', frontmatter: { title: 'Alice' } })).toBeNull();+ });+});++describe('observationDateFrom', () => {+ test('dates and ISO strings become caller observations; garbage is null', () => {+ expect(observationDateFrom('2026-03-10T23:15:00Z')).toEqual({ date: '2026-03-10', source: 'caller' });+ expect(observationDateFrom(new Date('2026-03-10T00:00:00Z'))).toEqual({ date: '2026-03-10', source: 'caller' });+ expect(observationDateFrom('not a date')).toBeNull();+ expect(observationDateFrom(null)).toBeNull();+ });+});++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()).not.toMatch(/\d{4}-\d{2}-\d{2}T/);+ });+ test('the user line carries the date or says unknown', () => {+ expect(observationDateLine({ date: '2026-03-10', source: 'filename' })).toContain('2026-03-10');+ expect(observationDateLine(null)).toContain('unknown');+ });+});++describe('parseExtractedEventDate', () => {+ const now = new Date('2026-10-04T00:00:00Z');+ test('accepts calendar dates in range', () => {+ expect(parseExtractedEventDate('2024-02-29', now)?.toISOString()).toBe('2024-02-29T00:00:00.000Z');+ expect(parseExtractedEventDate(' 2027-10-01 ', now)?.toISOString()).toBe('2027-10-01T00:00:00.000Z');+ });+ test('rejects malformed, impossible, ancient and far-future dates', () => {+ for (const v of ['2023-02-29', '2026-13-01', 'last week', '2026/03/01', '1899-12-31', '2027-10-05', 20260301, null, undefined]) {+ expect(parseExtractedEventDate(v, now)).toBeNull();+ }+ });+});++describe('resolveValidFrom precedence', () => {+ const now = new Date('2026-10-04T12:00:00Z');+ const obs = { date: '2026-03-10', source: 'filename' as const };+ test('extracted > caller > observation > now', () => {+ const extracted = new Date('2024-05-01T00:00:00Z');+ const caller = new Date('2026-01-01T00:00:00Z');+ expect(resolveValidFrom({ extracted, caller, observation: obs, now })).toEqual({ date: extracted, source: 'extracted' });+ expect(resolveValidFrom({ caller, observation: obs, now })).toEqual({ date: caller, source: 'caller' });+ expect(resolveValidFrom({ observation: obs, now })).toEqual({ date: new Date('2026-03-10T00:00:00Z'), source: 'observation' });+ expect(resolveValidFrom({ now })).toEqual({ date: now, source: 'now' });+ });+});++describe('hasUnresolvedRelativeDate', () => {+ test('a relative phrase followed by a parenthesized date counts as resolved', () => {+ expect(hasUnresolvedRelativeDate('User went to Lisbon last week')).toBe(true);+ expect(hasUnresolvedRelativeDate('User went to Lisbon last week (week of 2026-03-02)')).toBe(false);+ expect(hasUnresolvedRelativeDate('Alice joined 3 weeks ago')).toBe(true);+ expect(hasUnresolvedRelativeDate('Alice joined in March 2026')).toBe(false);+ });+});