Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(#6712 PR 4b): idle-hit gate (ceo-native-2) and the BEHAVIOR_CHANGES block pin (dx-native-3)
garrytand665e06736a2
diff --git a/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.tsnew file mode 100644index 0000000000..c527620ee1--- /dev/null+++ b/test/behavior-change-notice-6712-block.test.ts@@ -0,0 +1,59 @@+/**+ * #6712 PR 4b (design v3.2 §13; dx-native-3): the PR's BEHAVIOR_CHANGES rows are one tagged block. The registry export+ * carries no tags, so the block is located by a narrow parse of the array literal (each row opens with `{ since: '`, at+ * most a few to a line; the block runs from its marker comment to the next comment or the end of the array) and its rows are then+ * read from the export by index. Pinned: the row count, one `since` for the whole block (the merge-slot stamp replaces the+ * placeholder on every row at once), the block after master's rows (last in the array, no earlier row newer), and every+ * row's text inside the notice's rendered 2,000-character cap.+ */+import { describe, expect, test } from 'bun:test';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';++const MARKER = '// #6712 PR 4b (the level-triggered sync pass';+const ROWS = 23;+const NOTICE_CAP = 2_000;++/** The array literal's row lines in order, and where the block's rows start and how many there are. */+function locateBlock(source: string): { rowLines: number; first: number; count: number } {+ const lines = source.split('\n');+ const open = lines.findIndex(line => line.startsWith('export const BEHAVIOR_CHANGES'));+ const close = lines.findIndex((line, i) => i > open && line === '];');+ let rowLines = 0, first = -1, count = 0, inBlock = false;+ for (const line of lines.slice(open + 1, close)) {+ const trimmed = line.trimStart();+ if (trimmed.startsWith(MARKER)) { inBlock = true; first = rowLines; continue; }+ if (trimmed.startsWith('//')) inBlock = false;+ const rows = line.match(/\{ since: '\d/g)?.length ?? 0;+ rowLines += rows;+ if (inBlock) count += rows;+ }+ return { rowLines, first, count };+}++const source = readFileSync(join(import.meta.dir, '..', 'src', 'core', 'behavior-change-notice.ts'), 'utf8');++describe('#6712 PR 4b BEHAVIOR_CHANGES block', () => {+ const { rowLines, first, count } = locateBlock(source);+ const block = BEHAVIOR_CHANGES.slice(first, first + count);++ test('the narrow parse sees every exported row and finds the block', () => {+ expect(rowLines).toBe(BEHAVIOR_CHANGES.length);+ expect(first).toBeGreaterThan(0);+ });++ test(`the block has ${ROWS} rows, all with the block's first since`, () => {+ expect(count).toBe(ROWS);+ expect(block.filter(row => row.since !== block[0]!.since).map(row => row.since)).toEqual([]);+ });++ test("the block sits after master's rows: last in the array, and no earlier row is newer", () => {+ expect(first + count).toBe(BEHAVIOR_CHANGES.length);+ expect(BEHAVIOR_CHANGES.slice(0, first).filter(row => compareReleases(row.since, block[0]!.since) > 0).map(row => row.since)).toEqual([]);+ });++ test(`every row of the block is plain text inside the rendered ${NOTICE_CAP}-character cap`, () => {+ expect(block.filter(row => typeof row.text !== 'string' || row.text.length > NOTICE_CAP).length).toBe(0);+ });+});diff --git a/test/e2e/sync-idle-hit-6712-postgres.test.ts b/test/e2e/sync-idle-hit-6712-postgres.test.tsnew file mode 100644index 0000000000..2052c3d6f0--- /dev/null+++ b/test/e2e/sync-idle-hit-6712-postgres.test.ts@@ -0,0 +1,3 @@+import { registerPostgresTests } from '../helpers/test-backends.ts';++await registerPostgresTests(() => import('../sync-idle-hit-6712.test.ts'));diff --git a/test/sync-idle-hit-6712.test.ts b/test/sync-idle-hit-6712.test.tsnew file mode 100644index 0000000000..aea7afd06c--- /dev/null+++ b/test/sync-idle-hit-6712.test.ts@@ -0,0 +1,104 @@+/**+ * #6712 PR 4b (design v3.2 §2.2, §11; ceo-native-2): the idle-hit gate as a deterministic test. A converged source runs+ * IDLE_TICKS no-change ticks with no obligation; at least 90% of them must be `kind: 'idle'` (read from the pass row's telemetry).+ * The full-round limits are pinned so the window holds no forced full round: `passes_since_full` starts at 0 and+ * `last_full_at` at the window's start, and the test asserts the window ends inside both limits. Then each disqualifier, from+ * an idle tick, flips the next tick off idle: a new commit, a re-screen-due hold (`hold_only`), a parser change, keep_db+ * writes the previous pass deferred, a withheld mass delete with the valve open, and the configured full-round limits+ * (passes and wall clock). PGLite here; Postgres through test/e2e/sync-idle-hit-6712-postgres.test.ts.+ */+import { describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { mkdirSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { performManagedSync } from '../src/core/persistence/sync-run.ts';+import { writeGitHold } from '../src/core/persistence/sync-holds.ts';+import { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';+import { SYNC_FULL_ROUND_MAX_MS, SYNC_FULL_ROUND_MAX_PASSES } from '../src/core/persistence/sync-classify.ts';+import { RECOVERY_VERSION } from '../src/core/markdown.ts';+import { managedBrain } from './helpers/managed-brain.ts';+import { testBackends } from './helpers/test-backends.ts';+import { withEnv } from './helpers/with-env.ts';++const IDLE_TICKS = 25;+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();+const commit = (root: string, message: string) => { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };+const note = (title: string, body: string) => `---\ntype: concept\ntitle: ${title}\n---\n\n${body}\n`;+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };+const setup = ({ root }: { root: string }) => {+ mkdirSync(join(root, 'notes'), { recursive: true }); git(root, 'init', '-q');+ for (const slug of ['a', 'b', 'c']) writeFileSync(join(root, `notes/${slug}.md`), note(`notes/${slug}`, `The committed body of notes/${slug}.`));+ commit(root, 'notes');+};++type Row = { telemetry: { kind: string; outcome: string }; obligations: { converged?: { passes_since_full: number; last_full_at: string } } };+const passRow = async (engine: BrainEngine) => (await engine.executeRaw<{ value: Row }>(+ "SELECT completed_keys->0 AS value FROM op_checkpoints WHERE op=$1 AND completed_keys->0->>'source_id'='default'", [MANAGED_SYNC_PASS_OP]))[0]!.value;+/** One tick, and the kind its pass row recorded. */+const tick = async (engine: BrainEngine) => { await performManagedSync(engine, OPTS); return (await passRow(engine)).telemetry.kind; };+/** Sets one jsonb path of the pass row (`path` is a Postgres text[] literal under completed_keys->0). */+const setRow = (engine: BrainEngine, path: string, value: unknown) => engine.executeRaw(+ "UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,$2::text[],$3::text::jsonb) WHERE op=$1 AND completed_keys->0->>'source_id'='default'",+ [MANAGED_SYNC_PASS_OP, `{0,${path}}`, JSON.stringify(value)]);++for (const backend of testBackends()) {+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;+ const brain = (run: Parameters<typeof managedBrain>[0]) => managedBrain(run, { ...(databaseUrl ? { databaseUrl } : {}), setup });++ describe(`#6712 PR 4b idle-hit gate (${backend})`, () => {+ test(`at least 90% of ${IDLE_TICKS} no-change ticks with no obligation run idle, inside the configured full-round limits`, () => brain(async ({ engine }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ const start = new Date().toISOString();+ await setRow(engine, 'obligations,converged,passes_since_full', 0);+ await setRow(engine, 'obligations,converged,last_full_at', start);+ const kinds: string[] = [];+ for (let i = 0; i < IDLE_TICKS; i++) kinds.push(await tick(engine));+ // The window never reached a forced full round: both configured limits are still ahead of it.+ const converged = (await passRow(engine)).obligations.converged!;+ expect(converged.passes_since_full).toBeLessThan(SYNC_FULL_ROUND_MAX_PASSES);+ expect(Date.now() - Date.parse(converged.last_full_at)).toBeLessThan(SYNC_FULL_ROUND_MAX_MS);+ const idle = kinds.filter(kind => kind === 'idle').length;+ expect({ ticks: kinds.length, idle_at_least_90_percent: idle >= Math.ceil(0.9 * IDLE_TICKS) }).toEqual({ ticks: IDLE_TICKS, idle_at_least_90_percent: true });+ }), 300_000);++ test('each disqualifier turns the next tick off idle, and the tick after it is idle again', () => brain(async ({ engine, root }) => {+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');+ expect(await tick(engine)).toBe('idle');+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ const kinds: Record<string, [string, string]> = {};+ const flip = async (name: string, disqualify: () => Promise<unknown>, env: Record<string, string | undefined> = {}) => {+ await disqualify();+ const first = await withEnv(env, () => tick(engine));+ kinds[name] = [first, await tick(engine)];+ };++ await flip('new commit', async () => { writeFileSync(join(root, 'notes/a.md'), note('notes/a', 'A new commit.')); commit(root, 'edit a'); });+ await flip('re-screen-due hold', async () => {+ const page = (await engine.readPageSnapshot('notes/b', { sourceId: 'default' }))!;+ await engine.transaction(tx => writeGitHold(tx, { source_id: 'default', incarnation, path: 'notes/b.md', source_path: 'notes/b.md', slug: 'notes/b', page_id: Number(page.page.id),+ code: 'frontmatter_slug_conflict', message: 'Synthetic frontmatter_slug_conflict hold.', upstream_version: null, observed_at: new Date().toISOString(), run_id: null, mode: 'managed',+ meta: { recovery_version: RECOVERY_VERSION, blob_oid: git(root, 'rev-parse', 'HEAD:notes/b.md'), page_revision: page.revision } } as never));+ });+ await flip('parser change', () => setRow(engine, 'obligations,converged,parser_fp', 'an-older-parser'));+ await flip('owed keep_db writes', () => setRow(engine, 'telemetry,classes', { keep_db_pending: { count: 1, action: 'owner' } }));+ // A withheld mass delete keeps the tick idle until the owner host opens the valve.+ await setRow(engine, 'obligations,deletes_withheld', 'f'.repeat(64));+ await flip('withheld delete, valve closed', async () => {}, { GBRAIN_ALLOW_MASS_RECONCILE: undefined });+ await flip('withheld delete, valve open', async () => {}, { GBRAIN_ALLOW_MASS_RECONCILE: '1' });+ await flip('passes since full at the limit', () => setRow(engine, 'obligations,converged,passes_since_full', SYNC_FULL_ROUND_MAX_PASSES));+ await flip('last full round past the wall-clock limit', () => setRow(engine, 'obligations,converged,last_full_at', new Date(Date.now() - SYNC_FULL_ROUND_MAX_MS - 60_000).toISOString()));++ expect(kinds).toEqual({+ 'new commit': ['full', 'idle'],+ 're-screen-due hold': ['hold_only', 'idle'],+ 'parser change': ['full', 'idle'],+ 'owed keep_db writes': ['full', 'idle'],+ 'withheld delete, valve closed': ['idle', 'idle'],+ 'withheld delete, valve open': ['full', 'idle'],+ 'passes since full at the limit': ['full', 'idle'],+ 'last full round past the wall-clock limit': ['full', 'idle'],+ });+ }), 300_000);+ });+}