Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(timeline): defer meeting fan-out until the meeting has happened (#6966)
time-attackaa2d090f912a
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.mdindex e72016892d..10f63a368c 100644--- a/docs/architecture/key-files/graph-and-facts.md+++ b/docs/architecture/key-files/graph-and-facts.md@@ -73,7 +73,7 @@ rejection of serve-only flags before a brain opens.- `src/core/facts/extraction-availability.ts` — the ONE extraction-availability gate: `resolveExtractionAvailability(engine, model?)` resolves the extraction model through the engine (`getFactsExtractionModel`, DB-plane `facts.extraction_model` included) and asks the configured gateway `isAvailable('chat', model)`; `extractionAvailableForEngine(engine, capabilities?)` is the corpus-harvest form, where an explicit caller-supplied capability report stays authoritative. Used by the serve checkpoint harvest (both lanes), the maintenance sweep's corpus pass, OpenClaw compact() rung 3 and the facts backstop's execution-time gate, so a servable DB-plane model is never classified keyless by the engine-blind `detectCapabilities()` probe; an unconfigured gateway answers unavailable (the segment stays banked for the sweep). Pinned by `test/facts-extraction-availability.test.ts`, `test/checkpoint-harvest.serial.test.ts`, `test/sweep-writeback-corpus.test.ts` and `test/e2e/context-engine-rung3-extraction.test.ts`.-- `src/core/extract-timeline-from-meetings.ts` — normalizes canonical incoming and pack-owned outgoing `attended` edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); existing private-meeting filtering, source opt-in and source-qualified deduplication still apply. Dual-engine tests in `test/extract-timeline-attendance.test.ts` use an empty gazetteer so a body-mention fallback cannot conceal a broken attendance consumer. #6273: on a managed brain the rows are grouped per entity page and published by `publishMeetingTimelines` as database-only `managed_maintenance_meeting_timeline` requests (at most 200 rows each; the request id binds the page revision and the rows; rows already stored are not resubmitted, so a rerun admits nothing; a pending request stops that source for the run). `prepareMeetingTimeline` (dispatched from `prepared-maintenance.ts`) refuses malformed rows `invalid_params`, and at apply time re-reads each meeting (tier, title, slug, visibility) and runs the #5575 gate at the stored tier under `withWriteTrust`. The job handler throws on refused or pending writes. Test: `test/extract-timeline-from-meetings-managed.test.ts`.+- `src/core/extract-timeline-from-meetings.ts` — normalizes canonical incoming and pack-owned outgoing `attended` edges into meeting/person roles before timeline fan-out. SQL requires a live person and live meeting (including legacy meeting notes); private-meeting filtering, source opt-in and source-qualified dedup apply. An invite waits until its first valid end, start or date passes (#6966). Tests `test/extract-timeline-attendance.test.ts` (empty gazetteer), `test/extract-timeline-future-6966.test.ts`. #6273: on a managed brain the rows are grouped per entity page and published by `publishMeetingTimelines` as database-only `managed_maintenance_meeting_timeline` requests (at most 200 rows each; the request id binds the page revision and the rows; rows already stored are not resubmitted, so a rerun admits nothing; a pending request stops that source for the run). `prepareMeetingTimeline` (dispatched from `prepared-maintenance.ts`) refuses malformed rows `invalid_params`, and at apply time re-reads each meeting (tier, title, slug, visibility) and runs the #5575 gate at the stored tier under `withWriteTrust`. The job handler throws on refused or pending writes. Test: `test/extract-timeline-from-meetings-managed.test.ts`.- `src/core/context/delta-cursor.ts` — pure helpers for delta's per-arm cursor: the opaque base64url `cursor` (`{v:1, p:[since, slug], f:[created_at, id]}`, validated like `since`), microsecond ISO normalization and the one-microsecond clamp, `nextPagesPos`/`nextFactsPos` (delivered prefix, `now() - 2 s` horizon `DELTA_COMMIT_LAG_MS`, the facts cursor computed from raw rows so a duplicate cluster split by a budget cut loses nothing), `resolveDeltaStart` and `legacyDeltaCursor`. `test/delta-cursor-integrity.test.ts`.- `src/core/facts/question-recall.ts` — recall's `question`: `parseQuestionParam` refuses `supersessions`, `include_expired` and more than 2,000 characters with the corrected call as `fix.mcp`; `rankFactsByQuestion` resolves `entity` per source to pairs and runs `unlinkedNamesakes` on the whole filtered pool before ranking, embeds the question once through `embedQueryBounded` (the gateway's query-embedding cache, so a `query` of the same text shares it; the embedding opt-out, a missing provider or a failed embed rank by term share and set `facts_degraded.reason`), ranks with `search/fact-relevance.ts` under the `recall.question_admission` rule (`reserve` default, or `facts_arm`; pool, uncomparable count and rule read concurrently), hydrates the ranked ids through `rowToFact`, counts uncomparable facts (`facts_degraded.unembedded`, the `facts_unembedded` notice with the `embed --stale --facts` preview), sets `calibration` (recall's informational `facts_calibration: {status: 'unmeasured', model_key}`, #6590) when the cosine arm ran on a model with no row in `FACT_ADMISSION_FLOOR_EVIDENCE` (`search/fact-relevance.ts`, shared with doctor `fact_admission_floors`), with the `facts_calibration_unmeasured` info notice deduped per brain per session by its `dedupe_key` (test `test/recall-facts-calibration-6590.test.ts`), and turns a DB error into `unavailable` (`fix.next: wait`). `recallHintNotice` builds `recall_hint`. Tests: `test/recall-question.test.ts` (both engines), `test/recall-question-cli.test.ts`.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex b2447b2c08..479eec404b 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -912,6 +912,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.307.0', text: 'Automatic mention linking now skips a page of any type whose whole title is one generic word (such as "Info", "Team" or "Update"); before, only person pages were skipped, so a company or concept page with such a title collected a mention link from every page that used the word (#6958). The page itself is unchanged, multi-word titles still link, and `gbrain extract mentions --explain <slug>` reports the reason as `generic_token`.' },{ since: '0.60.307.0', text: 'When `chat_fallback_chain` answers a `gbrain think` (or `think` tool) call, the result now names the model that answered instead of the configured one that failed: `modelUsed`, `cost_usd`, the synthesize verb\'s `cost.model` and a `--save` page\'s `model:` frontmatter use it. New fields `requested_model` (the configured model) and `fallback_reason` (why it did not answer; omitted for HTTP MCP callers) appear only after a fallback, and the human output says `(fallback from ...)`. Calls the first model answers are unchanged.' },{ since: '0.60.307.0', text: '`gbrain extract links --source db` (and `extract all --source db`, `extract --stale`) no longer aborts the whole run at the first page whose source, or whose link target\'s source, has no sources row. That page keeps its links and watermark and the run continues; the summary counts it as `skipped_unknown_source`, names the first 20 in `unknown_source_pages` (JSON) and names the missing sources. Re-running extract does not clear these pages: re-register the source or remove its pages (#6808).' },+ // Wave 20 lane 1, pending D9 (#6966).+ { since: '0.60.307.0', text: '`gbrain extract timeline --from-meetings` (and its background job) no longer writes "Discussed in ..." timeline rows for a meeting that has not happened yet. A meeting waits until its frontmatter `end` has passed (else `start`, else the meeting date); the meeting page is unchanged and a later run adds the rows once it has ended (#6966).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/extract-timeline-from-meetings.ts b/src/core/extract-timeline-from-meetings.tsindex 547f45788f..599183e69a 100644--- a/src/core/extract-timeline-from-meetings.ts+++ b/src/core/extract-timeline-from-meetings.ts@@ -235,6 +235,14 @@ export async function extractTimelineFromMeetings(dateFallbacks++;}+ // #6966: a retained calendar invite is not evidence that a discussion happened.+ // Defer its rows until the first valid declared end, else start, else meeting+ // date; the source page stays as it is for meeting prep, and a later run admits it.+ const happenedAt = [frontmatter.end, frontmatter.start, date]+ .map(value => value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : NaN)+ .find(value => Number.isFinite(value));+ if (happenedAt !== undefined && happenedAt > Date.now()) continue;+meetingsScanned++;opts.onProgress?.(meetingsScanned, meetings.length, entriesCreated);diff --git a/test/e2e/extract-timeline-future-6966-postgres.test.ts b/test/e2e/extract-timeline-future-6966-postgres.test.tsnew file mode 100644index 0000000000..7c7d3b708e--- /dev/null+++ b/test/e2e/extract-timeline-future-6966-postgres.test.ts@@ -0,0 +1,2 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';+await registerPostgresTests(() => import('../extract-timeline-future-6966.test.ts'));diff --git a/test/extract-timeline-future-6966.test.ts b/test/extract-timeline-future-6966.test.tsnew file mode 100644index 0000000000..8fc0109ede--- /dev/null+++ b/test/extract-timeline-future-6966.test.ts@@ -0,0 +1,70 @@+/**+ * #6966: `extract timeline --from-meetings` must not write "Discussed in ..." rows+ * for a retained calendar invite that has not happened yet. The first valid+ * declared end, else start, else the meeting date decides; the meeting page is+ * left as it is and a later run admits the rows once the meeting has ended.+ * Real engines, no module mocks; dates are far apart so the wall clock never sits+ * on a boundary.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { extractTimelineFromMeetings } from '../src/core/extract-timeline-from-meetings.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { resetPgliteState, resetPgliteStateNarrow } from './helpers/reset-pglite.ts';+import { testBackends } from './helpers/test-backends.ts';++const person = 'people/alice-example';+const meeting = 'meetings/acme-example-sync';+const PAST = '2000-01-01T00:00:00Z';+const FUTURE = '2999-01-01T00:00:00Z';++for (const kind of testBackends()) describe(`meeting timeline waits for future invites (${kind})`, () => {+ let engine: BrainEngine;+ let close: (() => Promise<void>) | undefined;+ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }+ }, 240_000);+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });+ beforeEach(async () => {+ if (engine instanceof PGLiteEngine) await resetPgliteState(engine);+ else await resetPgliteStateNarrow(engine, ['sources', 'config']);+ });++ async function seedMeeting(frontmatter: Record<string, unknown>, effectiveDate: Date) {+ await engine.putPage(person, { type: 'person', title: 'Alice Example', compiled_truth: 'Profile.', timeline: '', frontmatter: {} });+ await engine.putPage(meeting, { type: 'meeting', title: 'Acme example sync', compiled_truth: 'Agenda.', timeline: '',+ frontmatter, effective_date: effectiveDate });+ await engine.addLinksBatch([{ from_slug: person, to_slug: meeting, link_type: 'attended', link_source: 'manual' }]);+ }+ const rows = async () => (await engine.executeRaw<{ summary: string }>(+ `SELECT t.summary FROM timeline_entries t JOIN pages p ON p.id = t.page_id WHERE p.slug = $1`, [person])).map(r => r.summary);+ const extract = () => extractTimelineFromMeetings(engine, { gazetteer: new Map() });++ test.each([+ ['future end', { start: PAST, end: FUTURE }, PAST, 0],+ ['future start, no end', { start: FUTURE }, PAST, 0],+ ['unparseable end falls back to a future start', { start: FUTURE, end: 'soon' }, PAST, 0],+ ['future meeting date, no start or end', {}, FUTURE, 0],+ ['ended meeting', { start: PAST, end: PAST }, PAST, 1],+ ['a past end wins over a later start', { start: FUTURE, end: PAST }, PAST, 1],+ ['ended with a timezone offset', { start: '2000-01-01T09:00:00+08:00', end: '2000-01-01T10:00:00+08:00' }, PAST, 1],+ ['unparseable start and end keep the past meeting date', { start: 'tbd', end: false }, PAST, 1],+ ] as const)('%s', async (_label, frontmatter, date, expected) => {+ await seedMeeting({ ...frontmatter }, new Date(date));+ const result = await extract();+ expect(result).toMatchObject({ entries_created: expected, meetings_scanned: expected, batch_errors: 0 });+ expect(await rows()).toEqual(expected ? ['Discussed in Acme example sync'] : []);+ });++ test('a deferred invite keeps its page and is admitted by a later run once it has ended', async () => {+ await seedMeeting({ start: PAST, end: FUTURE }, new Date(PAST));+ expect((await extract()).entries_created).toBe(0);+ const page = await engine.getPage(meeting);+ expect(page?.frontmatter).toMatchObject({ start: PAST, end: FUTURE });+ await engine.executeRaw(`UPDATE pages SET frontmatter = frontmatter || '{"end": "${PAST}"}'::jsonb WHERE slug = $1`, [meeting]);+ expect((await extract()).entries_created).toBe(1);+ expect(await rows()).toEqual(['Discussed in Acme example sync']);+ });+});