Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cycle): consolidate reads cycle.consolidate.cluster_threshold and never merges incompatible typed claims (#5363)

time-attacke795c0fb3470
diff --git a/src/commands/config.ts b/src/commands/config.ts
index ea52887179..1a9523e2b3 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -1088,6 +1088,14 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
}
}
+ // #5363: the consolidate phase falls back to 0.85 on a malformed value;
+ // refuse it here, where the operator can fix it.
+ if (key === 'cycle.consolidate.cluster_threshold') {
+ const { parseClusterThreshold } = await import('../core/cycle/phases/consolidate.ts');
+ try { parseClusterThreshold(value); }
+ catch (error) { console.error(`[config] ${(error as Error).message}`); process.exit(1); }
+ }
+
// Validate sources.default at set time. This key is read by
// source-resolver.ts tier 5 on EVERY unqualified call, and tier 5 calls
// assertSourceExists — so a syntactically valid but non-existent id set
diff --git a/src/core/config.ts b/src/core/config.ts
index 098aff1f81..1f547eae27 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1520,6 +1520,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// #4348: IANA timezone that owns the dream-cycle calendar day (summary
// bucketing). Unset → host timezone → UTC. Validated at set time.
'cycle.timezone',
+ // #5363: consolidate phase cosine cluster threshold, (0, 1], default 0.85.
+ // Read in src/core/cycle/phases/consolidate.ts; validated at set time.
+ 'cycle.consolidate.cluster_threshold',
// A11: IANA timezone for offset-less frontmatter datetimes in effective_date.
// Unset → UTC (date-only values are always UTC calendar dates). Validated at set time.
'brain.timezone',
diff --git a/src/core/cycle/phases/consolidate.ts b/src/core/cycle/phases/consolidate.ts
index 7546f9a357..d5c84778d0 100644
--- a/src/core/cycle/phases/consolidate.ts
+++ b/src/core/cycle/phases/consolidate.ts
@@ -41,7 +41,7 @@ export interface ConsolidatePhaseOpts {
* force-evict instead of running to completion after cancellation.
*/
signal?: AbortSignal;
- /** Cosine cluster threshold. Default 0.85. */
+ /** Cosine cluster threshold. Overrides `cycle.consolidate.cluster_threshold`; default 0.85. */
clusterThreshold?: number;
/** Minimum facts per (source, entity) bucket before consolidation. Default 3. */
minFactsPerBucket?: number;
@@ -50,13 +50,41 @@ export interface ConsolidatePhaseOpts {
sourceId?: string;
}
+export const CLUSTER_THRESHOLD_KEY = 'cycle.consolidate.cluster_threshold';
+export const DEFAULT_CLUSTER_THRESHOLD = 0.85;
+
+/**
+ * #5363: parse `cycle.consolidate.cluster_threshold`. A cosine similarity in
+ * (0, 1]; lower values merge more facts into one take. Throws on anything
+ * else so `gbrain config set` can refuse it.
+ */
+export function parseClusterThreshold(value: string): number {
+ const n = Number(value.trim());
+ if (value.trim() === '' || !Number.isFinite(n) || n <= 0 || n > 1) {
+ throw new Error(`${CLUSTER_THRESHOLD_KEY} must be a number greater than 0 and at most 1 (default ${DEFAULT_CLUSTER_THRESHOLD}); got '${value}'.`);
+ }
+ return n;
+}
+
export async function runPhaseConsolidate(
engine: BrainEngine,
opts: ConsolidatePhaseOpts = {},
): Promise<PhaseResult> {
const dryRun = opts.dryRun === true;
const managed = await managedPersistenceEnabled(engine);
- const threshold = opts.clusterThreshold ?? 0.85;
+ // #5363: the knob was unreachable (cycle.ts never passed it); the phase now
+ // reads its own config key. A malformed stored value keeps the default and
+ // is reported in details instead of failing the cycle.
+ let thresholdInvalid: string | undefined;
+ let threshold = opts.clusterThreshold;
+ if (threshold === undefined) {
+ const configured = await engine.getConfig(CLUSTER_THRESHOLD_KEY);
+ threshold = DEFAULT_CLUSTER_THRESHOLD;
+ if (configured != null && configured.trim() !== '') {
+ try { threshold = parseClusterThreshold(configured); }
+ catch { thresholdInvalid = configured; }
+ }
+ }
const minPerBucket = opts.minFactsPerBucket ?? 3;
const minOldestAgeMs = opts.minOldestAgeMs ?? 24 * 60 * 60 * 1000;
@@ -132,7 +160,8 @@ export async function runPhaseConsolidate(
}
bucketsProcessed += 1;
- const clusters = clusterFacts(unconsolidated, threshold);
+ const claims = await loadClaimShapes(engine, unconsolidated.map(f => f.id));
+ const clusters = clusterFacts(unconsolidated, threshold, claims);
// Resolve entity_slug → page_id. If page missing in this source, skip.
const pageRows = await engine.executeRaw<{ id: number }>(
@@ -309,6 +338,8 @@ export async function runPhaseConsolidate(
(clustersSkippedRetired ? `; skipped ${clustersSkippedRetired} clusters with retired takes` : ''),
details: {
dryRun,
+ cluster_threshold: threshold,
+ ...(thresholdInvalid !== undefined ? { cluster_threshold_invalid: thresholdInvalid } : {}),
facts_consolidated: factsConsolidated,
takes_written: takesWritten,
buckets_processed: bucketsProcessed,
@@ -319,17 +350,47 @@ export async function runPhaseConsolidate(
};
}
+/** The typed-claim columns of a fact (FactRow does not carry them). */
+export interface ClaimShape {
+ metric: string | null;
+ unit: string | null;
+ period: string | null;
+}
+
+async function loadClaimShapes(engine: BrainEngine, ids: number[]): Promise<Map<number, ClaimShape>> {
+ const rows = ids.length === 0 ? [] : await engine.executeRaw<{
+ id: number; claim_metric: string | null; claim_unit: string | null; claim_period: string | null;
+ }>(`SELECT id, claim_metric, claim_unit, claim_period FROM facts WHERE id = ANY($1::bigint[])`, [ids]);
+ return new Map(rows.map(r => [Number(r.id), { metric: r.claim_metric, unit: r.claim_unit, period: r.claim_period }]));
+}
+
+/**
+ * #5363: two facts may share a take only when their typed claims agree.
+ * Untyped facts (no metric) cluster with untyped facts; a typed fact
+ * clusters only with facts of the same metric, unit and period (a monthly
+ * and an annual MRR, or USD and EUR, never merge however close their text
+ * embeddings are). A fact whose claim columns are unknown is treated as
+ * untyped.
+ */
+export function claimsCompatible(a: ClaimShape | undefined, b: ClaimShape | undefined): boolean {
+ const metricA = a?.metric ?? null;
+ const metricB = b?.metric ?? null;
+ if (metricA === null || metricB === null) return metricA === metricB;
+ return metricA === metricB && (a?.unit ?? null) === (b?.unit ?? null) && (a?.period ?? null) === (b?.period ?? null);
+}
+
/**
* Greedy cosine clustering. Iterate facts sorted by valid_from DESC; each
* fact joins the first cluster whose centroid (the first member, for
- * simplicity) is within `threshold` cosine. Otherwise starts a new cluster.
+ * simplicity) is within `threshold` cosine and whose typed claim is
+ * compatible (#5363). Otherwise starts a new cluster.
*
* Facts with no embedding cluster on their own (single-element cluster);
* the consolidate phase only writes takes from clusters of size ≥ 2, so
* no-embedding singletons sit out the cycle. v0.32+ fact-extraction
* pipeline ensures embeddings are computed at insertFact time.
*/
-function clusterFacts(facts: FactRow[], threshold: number): FactRow[][] {
+export function clusterFacts(facts: FactRow[], threshold: number, claims: Map<number, ClaimShape> = new Map()): FactRow[][] {
const sorted = [...facts].sort((a, b) => b.valid_from.getTime() - a.valid_from.getTime());
const clusters: FactRow[][] = [];
for (const f of sorted) {
@@ -342,7 +403,8 @@ function clusterFacts(facts: FactRow[], threshold: number): FactRow[][] {
const head = c[0];
if (!head.embedding || f.embedding_model !== head.embedding_model
|| head.embedded_text_hash !== createHash('md5').update(head.fact).digest('hex')
- || f.embedding.length !== head.embedding.length) continue;
+ || f.embedding.length !== head.embedding.length
+ || !claimsCompatible(claims.get(f.id), claims.get(head.id))) continue;
if (cosineSimilarity(f.embedding, head.embedding) >= threshold) {
c.push(f);
placed = true;
diff --git a/test/cycle-consolidate-threshold-5363.test.ts b/test/cycle-consolidate-threshold-5363.test.ts
new file mode 100644
index 0000000000..659bf1337c
--- /dev/null
+++ b/test/cycle-consolidate-threshold-5363.test.ts
@@ -0,0 +1,141 @@
+/**
+ * #5363 (fix wave 9) — consolidate's cluster threshold is reachable through
+ * `cycle.consolidate.cluster_threshold`, and typed claims only cluster with
+ * the same metric, unit and period.
+ *
+ * Pre-fix `clusterThreshold` was never passed by cycle.ts and no config key
+ * existed, so the 0.85 default was fixed; and facts with near-identical text
+ * but a different period or unit (monthly vs annual MRR, USD vs EUR) merged
+ * into one take.
+ */
+
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway } from '../src/core/ai/gateway.ts';
+import { parseClusterThreshold, runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ configureGateway({
+ embedding_model: 'openai:text-embedding-3-large',
+ embedding_dimensions: 1536,
+ env: { ...process.env },
+ });
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+beforeEach(async () => {
+ await engine.executeRaw(`DELETE FROM facts`);
+ await engine.executeRaw(`DELETE FROM takes`);
+ await engine.executeRaw(`DELETE FROM config WHERE key = 'cycle.consolidate.cluster_threshold'`);
+});
+
+const oldDate = (hoursAgo: number) => new Date(Date.now() - hoursAgo * 60 * 60 * 1000).toISOString();
+
+/** Unit vector at cosine `c` from e0. */
+function vecAt(c: number): string {
+ const a = new Float32Array(1536);
+ a[0] = c;
+ a[1] = Math.sqrt(Math.max(0, 1 - c * c));
+ return '[' + Array.from(a).join(',') + ']';
+}
+
+async function seedPage(slug: string): Promise<void> {
+ await engine.executeRaw(
+ `INSERT INTO pages (slug, type, title) VALUES ($1, 'company', 'Test') ON CONFLICT DO NOTHING`,
+ [slug],
+ );
+}
+
+async function seedFact(slug: string, text: string, vec: string, hoursAgo: number, claim?: { metric: string; unit?: string; period?: string }): Promise<number> {
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, embedding, embedded_at, embedding_model, embedded_text_hash,
+ claim_metric, claim_unit, claim_period, claim_value)
+ VALUES ('default', $1, $2, 'fact', 'test', $3::timestamptz, $4::vector, $3::timestamptz, 'openai:text-embedding-3-large', md5($2),
+ $5, $6, $7, $8)
+ RETURNING id`,
+ [slug, text, oldDate(hoursAgo), vec, claim?.metric ?? null, claim?.unit ?? null, claim?.period ?? null, claim ? 1000 : null],
+ );
+ return Number(rows[0].id);
+}
+
+async function consolidatedIds(): Promise<number[]> {
+ const rows = await engine.executeRaw<{ id: number }>(`SELECT id FROM facts WHERE consolidated_at IS NOT NULL ORDER BY id`);
+ return rows.map(r => Number(r.id));
+}
+
+describe('#5363 cluster threshold is configurable', () => {
+ test('cycle.consolidate.cluster_threshold lowers the bar the phase actually uses', async () => {
+ await seedPage('acme-example');
+ await seedFact('acme-example', 'acme ships weekly', vecAt(1), 40);
+ await seedFact('acme-example', 'acme releases every week', vecAt(0.8), 39);
+ await seedFact('acme-example', 'acme was founded in 2020', vecAt(0), 38);
+
+ const atDefault = await runPhaseConsolidate(engine, {});
+ expect(atDefault.details.facts_consolidated).toBe(0);
+ expect(atDefault.details.cluster_threshold).toBe(0.85);
+
+ await engine.setConfig('cycle.consolidate.cluster_threshold', '0.75');
+ const lowered = await runPhaseConsolidate(engine, {});
+ expect(lowered.details.cluster_threshold).toBe(0.75);
+ expect(lowered.details.facts_consolidated).toBe(2);
+ expect(lowered.details.takes_written).toBe(1);
+ });
+
+ test('a malformed stored value keeps the default and is reported', async () => {
+ await engine.setConfig('cycle.consolidate.cluster_threshold', 'lots');
+ const r = await runPhaseConsolidate(engine, {});
+ expect(r.details.cluster_threshold).toBe(0.85);
+ expect(r.details.cluster_threshold_invalid).toBe('lots');
+ });
+
+ test('parseClusterThreshold accepts (0, 1] and refuses the rest', () => {
+ expect(parseClusterThreshold('0.9')).toBe(0.9);
+ expect(parseClusterThreshold('1')).toBe(1);
+ for (const bad of ['0', '-0.2', '1.5', 'abc', '', 'NaN']) {
+ expect(() => parseClusterThreshold(bad)).toThrow(/cluster_threshold/);
+ }
+ });
+});
+
+describe('#5363 typed claims only cluster when metric, unit and period agree', () => {
+ test('monthly vs annual, and USD vs EUR, never share a take even with identical embeddings', async () => {
+ await seedPage('acme-example');
+ await seedFact('acme-example', 'acme mrr is 1000', vecAt(1), 40, { metric: 'mrr', unit: 'USD', period: 'monthly' });
+ await seedFact('acme-example', 'acme arr is 1000', vecAt(1), 39, { metric: 'mrr', unit: 'USD', period: 'annual' });
+ await seedFact('acme-example', 'acme mrr is 1000 eur', vecAt(1), 38, { metric: 'mrr', unit: 'EUR', period: 'monthly' });
+ const r = await runPhaseConsolidate(engine, {});
+ expect(r.details.facts_consolidated).toBe(0);
+ expect(r.details.takes_written).toBe(0);
+ expect(await consolidatedIds()).toEqual([]);
+ });
+
+ test('a typed claim never clusters with untyped prose', async () => {
+ await seedPage('acme-example');
+ const typed = await seedFact('acme-example', 'acme revenue grew', vecAt(1), 40, { metric: 'mrr', unit: 'USD', period: 'monthly' });
+ const proseA = await seedFact('acme-example', 'acme revenue is growing', vecAt(1), 39);
+ const proseB = await seedFact('acme-example', 'acme revenue keeps growing', vecAt(1), 38);
+ const r = await runPhaseConsolidate(engine, {});
+ expect(r.details.facts_consolidated).toBe(2);
+ const done = await consolidatedIds();
+ expect(done).toEqual([proseA, proseB].sort((a, b) => a - b));
+ expect(done).not.toContain(typed);
+ });
+
+ test('successive compatible values still cluster', async () => {
+ await seedPage('acme-example');
+ await seedFact('acme-example', 'acme mrr is 1000', vecAt(1), 40, { metric: 'mrr', unit: 'USD', period: 'monthly' });
+ await seedFact('acme-example', 'acme mrr is 1200', vecAt(1), 39, { metric: 'mrr', unit: 'USD', period: 'monthly' });
+ await seedFact('acme-example', 'acme mrr is 1500', vecAt(1), 38, { metric: 'mrr', unit: 'USD', period: 'monthly' });
+ const r = await runPhaseConsolidate(engine, {});
+ expect(r.details.facts_consolidated).toBe(3);
+ expect(r.details.takes_written).toBe(1);
+ });
+});