Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(doctor): hot-check goldens pin the fence trend day without depending on today
time-attackbd524c7f0bf9
diff --git a/test/doctor-hot-checks-golden.test.ts b/test/doctor-hot-checks-golden.test.tsindex 94ec4fbdad..35ca8b1822 100644--- a/test/doctor-hot-checks-golden.test.ts+++ b/test/doctor-hot-checks-golden.test.ts@@ -16,7 +16,7 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';import { defineNormalizer, expectGolden, expectNormalizerStable } from './helpers/golden.ts';import { doctorJsonNormalizer, makeDoctorHome, networkAttempts, runGbrain, type DoctorHome, type GbrainRun } from './helpers/doctor-json-golden.ts';-import { buildHotCheckFixture, editHotCheckFixture, pgliteSql } from './helpers/doctor-hot-checks-fixture.ts';+import { buildHotCheckFixture, editHotCheckFixture, HOT_CHECK_CLOCK, pgliteSql } from './helpers/doctor-hot-checks-fixture.ts';const DOCTOR = doctorJsonNormalizer();const homes: DoctorHome[] = [];@@ -28,7 +28,7 @@ type Captures = { first: GbrainRun; second: GbrainRun };const BOTH = defineNormalizer<Captures>(DOCTOR.name, (c) => ({ first: DOCTOR.apply(c.first), second: DOCTOR.apply(c.second) }));async function capture(): Promise<Captures> {- const h = makeDoctorHome('doctor-hot-checks');+ const h = makeDoctorHome('doctor-hot-checks', { clock: HOT_CHECK_CLOCK });homes.push(h);const init = await runGbrain(h, ['init', '--pglite', '--no-embedding']);if (init.exitCode !== 0) throw new Error(`gbrain init failed (${init.exitCode}): ${init.stderr}`);diff --git a/test/doctor-hot-checks-sync-day.test.ts b/test/doctor-hot-checks-sync-day.test.tsnew file mode 100644index 0000000000..11fca77f39--- /dev/null+++ b/test/doctor-hot-checks-sync-day.test.ts@@ -0,0 +1,49 @@+/**+ * The Postgres hot-check golden's fence trend day (test/e2e/doctor-hot-checks-golden.test.ts)+ * against a recorded run shifted to another day, without a database: a golden+ * that pins the capture day (2026-10-10) fails on any other day; `stampSyncDay`+ * accepts the run only when every trend day is the day the sync stamped and+ * that day is one of the days read around the sync, and it touches no other field.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { stampSyncDay, SYNC_DAY } from './helpers/doctor-hot-checks-fixture.ts';++type Check = { name: string; message?: string; details?: { trend?: Array<{ by_day?: Array<{ day: string }> }> } };+type Report = { checks: Check[] };+const golden = (JSON.parse(readFileSync(join(import.meta.dir, 'fixtures/goldens/doctor/hot-checks-postgres-json.json'), 'utf8')) as { golden: { first: { report: Report } } }).golden.first.report;++/** The recorded report with its fence trend day set to `day` (a run on that day). */+const runOn = (day: string): Report => JSON.parse(JSON.stringify(golden).replaceAll(`"day":"${SYNC_DAY}"`, `"day":"${day}"`)) as Report;+const trendDays = (report: Report) => report.checks.filter(c => c.name === 'fence_integrity').flatMap(c => c.details?.trend ?? []).flatMap(t => t.by_day ?? []).map(d => d.day);++describe('Postgres hot-check golden: the fence trend day', () => {+ test('the recorded run carries trend days to check', () => {+ expect(trendDays(golden)).toEqual([SYNC_DAY]);+ });++ test('a golden pinned to the capture day fails on another day; the sync-day check passes', () => {+ const pinned = runOn('2026-10-10');+ const later = runOn('2026-11-20');+ expect(later).not.toEqual(pinned);+ expect(stampSyncDay(later, '2026-11-20', ['2026-11-20', '2026-11-20'])).toEqual(golden);+ });++ test('a sync across midnight UTC accepts only the day it stamped, and only if it is one of the two', () => {+ expect(stampSyncDay(runOn('2026-11-21'), '2026-11-21', ['2026-11-20', '2026-11-21'])).toEqual(golden);+ expect(stampSyncDay(runOn('2026-11-20'), '2026-11-20', ['2026-11-20', '2026-11-21'])).toEqual(golden);+ expect(() => stampSyncDay(runOn('2026-11-22'), '2026-11-22', ['2026-11-20', '2026-11-21'])).toThrow('neither the day before');+ });++ test('a trend day other than the stamped one fails', () => {+ expect(() => stampSyncDay(runOn('2026-11-19'), '2026-11-20', ['2026-11-20', '2026-11-20'])).toThrow('not the day the fixture sync stamped');+ });++ test('only the trend day is replaced: other date-like drift still differs', () => {+ const drifted = runOn('2026-11-20');+ const other = drifted.checks.find(c => c.name !== 'fence_integrity' && typeof c.message === 'string')!;+ other.message = `${other.message} 2026-11-20`;+ expect(stampSyncDay(drifted, '2026-11-20', ['2026-11-20', '2026-11-20'])).not.toEqual(golden);+ });+});diff --git a/test/e2e/doctor-hot-checks-golden.test.ts b/test/e2e/doctor-hot-checks-golden.test.tsindex d5e04107b2..9986bd84e3 100644--- a/test/e2e/doctor-hot-checks-golden.test.ts+++ b/test/e2e/doctor-hot-checks-golden.test.ts@@ -15,7 +15,8 @@ import postgres from '#postgres';import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';import { defineNormalizer, expectGolden, expectNormalizerStable } from '../helpers/golden.ts';import { doctorJsonNormalizer, makeDoctorHome, networkAttempts, runGbrain, type DoctorHome, type GbrainRun } from '../helpers/doctor-json-golden.ts';-import { buildHotCheckFixture, editHotCheckFixture, type Sql } from '../helpers/doctor-hot-checks-fixture.ts';+import { FENCE_TREND_OP } from '../../src/core/fence-repair/census-store.ts';+import { buildHotCheckFixture, editHotCheckFixture, stampSyncDay, type Sql } from '../helpers/doctor-hot-checks-fixture.ts';const DATABASE_URL = process.env.DATABASE_URL;const describeE2E = DATABASE_URL ? describe : describe.skip;@@ -69,11 +70,17 @@ async function capture(adminUrl: string): Promise<PgCaptures> {await db.end();}};- await buildHotCheckFixture(h, sql);+ const { syncDays } = await buildHotCheckFixture(h, sql);const first = await runGbrain(h, ['doctor', '--json', '--skills-dir', h.skillsDir]);await editHotCheckFixture(h, sql);const second = await runGbrain(h, ['doctor', '--json', '--skills-dir', h.skillsDir]);expect(networkAttempts(h)).toEqual([]);+ // Real clock here (the server's now() stamps last_sync_at): the fence trend day is checked against the day the sync stamped, then stored as <sync-day>.+ const db = postgres(url, { max: 1, prepare: false });+ const stamped = await db.unsafe(`SELECT DISTINCT completed_keys->0->>'day' AS day FROM op_checkpoints WHERE op = $1`, [FENCE_TREND_OP]).finally(() => db.end());+ expect(stamped.length).toBe(1);+ const day = stamped[0]!.day as string;+ for (const run of [first, second]) run.json = stampSyncDay(run.json, day, syncDays);return { first, second, url, name };}diff --git a/test/fixtures/goldens/README.md b/test/fixtures/goldens/README.mdindex 5be9d51ef5..645e9efa8a 100644--- a/test/fixtures/goldens/README.md+++ b/test/fixtures/goldens/README.md@@ -114,3 +114,11 @@ reproduce byte for byte. Each file is written by `test/helpers/golden.ts` asPGLite brain (`brain.tar.gz` + `MANIFEST.json`, rebuilt only on master with`bun scripts/build-pglite-upgrade-fixture.ts`), its post-boot catalog, and theobjects a repeat boot recreates.+- `doctor/hot-checks-{pglite,postgres}-json.json` (`test/doctor-hot-checks-golden.test.ts`,+ `test/e2e/doctor-hot-checks-golden.test.ts`): full `doctor --json` on the hot-check+ fixture. The fence trend's calendar day is pinned, never dropped: PGLite runs every+ CLI process on one clock that starts on the capture day (`makeDoctorHome({ clock })`,+ `test/helpers/fixed-clock-preload.ts`); Postgres, whose server stamps its own times,+ stores `fence_integrity.details.trend[].by_day[].day` as `<sync-day>` only after+ `stampSyncDay` checks it equals the day the fixture's sync stamped (one of the days+ read around the sync). Regenerating writes the marker again.diff --git a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json b/test/fixtures/goldens/doctor/hot-checks-postgres-json.jsonindex c699888c06..4366ce95fe 100644--- a/test/fixtures/goldens/doctor/hot-checks-postgres-json.json+++ b/test/fixtures/goldens/doctor/hot-checks-postgres-json.json@@ -2401,7 +2401,7 @@"by_day": [{"count": 1,- "day": "2026-10-10"+ "day": "<sync-day>"}],"normalized_7d": 1,@@ -5413,7 +5413,7 @@"by_day": [{"count": 1,- "day": "2026-10-10"+ "day": "<sync-day>"}],"normalized_7d": 1,diff --git a/test/helpers/doctor-hot-checks-fixture.ts b/test/helpers/doctor-hot-checks-fixture.tsindex 60e4186513..3aab6be94d 100644--- a/test/helpers/doctor-hot-checks-fixture.ts+++ b/test/helpers/doctor-hot-checks-fixture.ts@@ -99,6 +99,8 @@ const PLAIN: Record<string, string> = {};const FIXED_DATE = '2024-01-01T00:00:00Z';+/** The fixture's clock (fixed-clock-preload.ts): its sync writes the fence trend on this day and doctor reads the trend window from it. The day the goldens were captured. */+export const HOT_CHECK_CLOCK = '2026-10-10T12:00:00Z';function writeAll(dir: string, files: Record<string, string>): void {for (const [rel, body] of Object.entries(files)) {@@ -122,7 +124,7 @@ async function gbrain(h: DoctorHome, args: string[]): Promise<GbrainRun> {* Builds the fixture on an initialized brain (`init` already ran) and returns* nothing; doctor runs next.*/-export async function buildHotCheckFixture(h: DoctorHome, sql: Sql): Promise<void> {+export async function buildHotCheckFixture(h: DoctorHome, sql: Sql): Promise<{ syncDays: [string, string] }> {const src = join(h.home, 'notes-src');writeAll(src, IMPORTED);git(src, 'init', '-q', '-b', 'main');@@ -141,7 +143,10 @@ export async function buildHotCheckFixture(h: DoctorHome, sql: Sql): Promise<voiwriteAll(src, ON_DISK);git(src, 'add', '-A');git(src, 'commit', '-q', '-m', 'broken files');+ const utcDay = () => new Date().toISOString().slice(0, 10);+ const before = utcDay();await runGbrain(h, ['sync', '--source', 'notes', '--no-pull', '--no-embed']);+ const syncDays: [string, string] = [before, utcDay()];// After the sync (a full catch-up re-imports changed pages): database-only timeline rows, one materializable and one that cannot round-trip (comment markup).const insert = `INSERT INTO timeline_entries(page_id,date,source,summary,detail)SELECT id, $2::date, $3, $4, '' FROM pages WHERE slug = $1 AND source_id = 'notes'`;@@ -155,6 +160,33 @@ export async function buildHotCheckFixture(h: DoctorHome, sql: Sql): Promise<voi['ANALYZE', []],]);writeAll(src, { ...UNTRACKED, 'fences/untracked.md': `${fm('Untracked Fence')}\n## Facts\n\n${DETERMINISTIC_FENCE}` });+ return { syncDays };+}++/** The golden's symbol for the UTC day the fixture's sync stamped on its fence trend row. */+export const SYNC_DAY = '<sync-day>';++/**+ * The Postgres hot-check golden runs on the real clock (the server stamps+ * `last_sync_at` with its own `now()`, which no test clock can shift), so the+ * fence trend's `by_day[].day` is the day the fixture synced. This replaces+ * exactly that field, and only after checking it: `stamped` is the day read+ * back from the trend row, it must be one of the days read just before and+ * after the sync (two only when the sync crossed midnight UTC), and every+ * `fence_integrity.details.trend[].by_day[].day` must equal it. Any other+ * field, date-like or not, is left for the golden to compare.+ */+export function stampSyncDay(report: unknown, stamped: string, syncDays: readonly [string, string]): unknown {+ if (!syncDays.includes(stamped)) throw new Error(`fence trend day ${stamped} is neither the day before (${syncDays[0]}) nor after (${syncDays[1]}) the fixture sync`);+ const copy = structuredClone(report) as { checks?: Array<{ name: string; details?: { trend?: Array<{ by_day?: Array<{ day: string }> }> } }> };+ for (const check of copy.checks ?? []) {+ if (check.name !== 'fence_integrity') continue;+ for (const trend of check.details?.trend ?? []) for (const entry of trend.by_day ?? []) {+ if (entry.day !== stamped) throw new Error(`fence_integrity trend day ${entry.day} is not the day the fixture sync stamped (${stamped})`);+ entry.day = SYNC_DAY;+ }+ }+ return copy;}/**diff --git a/test/helpers/doctor-json-golden.ts b/test/helpers/doctor-json-golden.tsindex af71b375df..9e2fa216f0 100644--- a/test/helpers/doctor-json-golden.ts+++ b/test/helpers/doctor-json-golden.ts@@ -31,6 +31,7 @@ import { MIGRATIONS } from '../../src/core/schema-migrations/registry.generated.const REPO_ROOT = join(import.meta.dir, '..', '..');const CLI = join(REPO_ROOT, 'src', 'cli.ts');const PRELOAD = join(import.meta.dir, 'no-network-preload.ts');+const CLOCK_PRELOAD = join(import.meta.dir, 'fixed-clock-preload.ts');const PACKAGE_VERSION = (JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf-8')) as { version: string }).version;const REGISTRY_LATEST = Math.max(...MIGRATIONS.map((m) => m.version));const SCHEMA_LATEST = /\b(Version |latest: |latest is |latest known version \()(\d+)\b/g;@@ -40,10 +41,13 @@ export interface DoctorHome {work: string;skillsDir: string;netLog: string;+ /** Milliseconds every CLI process of this home adds to the real clock (fixed-clock-preload.ts); unset runs on the real clock. */+ clockOffsetMs?: number;cleanup: () => void;}-export function makeDoctorHome(prefix: string): DoctorHome {+/** `opts.clock`: an ISO instant; the home's CLI processes share one clock that reads it now and moves forward from it. */+export function makeDoctorHome(prefix: string, opts: { clock?: string } = {}): DoctorHome {const home = mkdtempSync(join(tmpdir(), `gbrain-${prefix}-`));const work = join(home, 'work');const skillsDir = join(home, 'skills');@@ -65,6 +69,7 @@ export function makeDoctorHome(prefix: string): DoctorHome {work,skillsDir,netLog: join(home, 'net.log'),+ ...(opts.clock ? { clockOffsetMs: Date.parse(opts.clock) - Date.now() } : {}),cleanup: () => rmSync(home, { recursive: true, force: true }),};}@@ -98,11 +103,13 @@ export async function runGbrain(h: DoctorHome, args: string[], env: Record<strinNO_COLOR: '1',PATH: [join(h.home, 'bin'), '/usr/bin', '/bin'].join(delimiter),});+ delete childEnv.GBRAIN_TEST_CLOCK_OFFSET_MS;+ if (h.clockOffsetMs !== undefined) childEnv.GBRAIN_TEST_CLOCK_OFFSET_MS = String(h.clockOffsetMs);for (const [k, v] of Object.entries(env)) {if (v === undefined) delete childEnv[k];else childEnv[k] = v;}- const proc = Bun.spawn([process.execPath, '--no-env-file', '--preload', PRELOAD, CLI, ...args], {+ const proc = Bun.spawn([process.execPath, '--no-env-file', '--preload', PRELOAD, '--preload', CLOCK_PRELOAD, CLI, ...args], {cwd: h.work,env: childEnv,stdin: 'ignore',diff --git a/test/helpers/fixed-clock-preload.ts b/test/helpers/fixed-clock-preload.tsnew file mode 100644index 0000000000..43879abb69--- /dev/null+++ b/test/helpers/fixed-clock-preload.ts@@ -0,0 +1,28 @@+/**+ * Child-process preload for doctor goldens that print a calendar day: when+ * `$GBRAIN_TEST_CLOCK_OFFSET_MS` is set, the process clock reads the real+ * clock shifted by that many milliseconds. The harness computes one offset per+ * doctor home (test/helpers/doctor-json-golden.ts `makeDoctorHome({ clock })`),+ * so every CLI process of a fixture shares one clock that starts at the fixed+ * instant and keeps moving forward across processes: the fixture's writes and+ * the doctor runs that read them land on the same day whatever day the suite+ * runs. PGLite runs in-process and reads the same clock. A no-op without the+ * variable. Loaded with `bun --preload`.+ */+const raw = process.env.GBRAIN_TEST_CLOCK_OFFSET_MS;++if (raw) {+ const offset = Number(raw);+ if (!Number.isFinite(offset)) throw new Error(`GBRAIN_TEST_CLOCK_OFFSET_MS is not a number: ${raw}`);+ const RealDate = Date;+ class OffsetClockDate extends RealDate {+ constructor(...args: unknown[]) {+ if (args.length === 0) super(RealDate.now() + offset);+ else super(...(args as [string]));+ }+ static override now(): number {+ return RealDate.now() + offset;+ }+ }+ globalThis.Date = OffsetClockDate as DateConstructor;+}