mirror of
https://github.com/garrytan/gbrain.git
synced 2026-07-27 22:15:33 +00:00
* feat(facts): typed-claim substrate + cycle correctness fixes (v0.35.6 wave 1/3) Schema (migration v67): - Add four optional typed-claim columns to facts: claim_metric TEXT, claim_value DOUBLE PRECISION, claim_unit TEXT, claim_period TEXT - Partial index facts_typed_claim_idx ON (entity_slug, claim_metric, valid_from) WHERE claim_metric IS NOT NULL - All nullable, metadata-only on both engines Fence layer: - ParsedFact (facts-fence.ts) gains optional claimMetric/Value/Unit/Period - Parser tolerates both 10-cell (legacy) and 14-cell (widened) rows - Renderer emits 14 cells iff any row has typed data; otherwise stays 10-cell so existing fences don't widen on unrelated edits - Numeric value cell tolerates comma thousand separators (50,000 -> 50000) Extract pipeline (D-CDX-2, D-ENG-1): - src/core/facts/extract.ts (the actual Haiku call site, NOT extract-facts.ts cycle phase) extends its system prompt to emit typed fields for metric-shaped claims - extractFactsFromFenceText gains optional pageEffectiveDate. Precedence: fence-row validFrom > pageEffectiveDate > undefined (engine defaults to now) - normalizeMetricLabel: 15-entry seed map for common founder metrics (mrr, arr, runway, headcount, team_size, cac, ltv, gross_margin, burn_rate, cash, users, mau, dau, churn_rate, revenue); unknown labels lowercase + space->_ Engine extensions: - NewFact + insertFact + insertFacts in both engines accept the four typed columns (all nullable) - Cycle phase extract-facts.ts threads page.effective_date through AND batch-embeds via gateway.embed() before insertFacts (D-CDX-3 fix for cycle-inserted facts arriving with embedding=NULL) Consolidate fix (D-CDX-4 — Codex F4): - Replace MAX(row_num)+1 INSERT with semantic upsert on (page_id, claim, since_date). Re-running the full cycle on stable input produces zero new takes — fixes the pre-existing duplicate-takes bug after extract_facts wipes consolidated_at - Chronological valid_until writeback per cluster: sort by (valid_from ASC, id ASC), walk pairs, set older.valid_until = newer.valid_from Tests: - test/migrate.test.ts +6 cases for v67 shape + materialization + nullable backward compat - test/facts-fence-typed.test.ts (new, 17 cases): parser+renderer round-trip, normalization seed map coverage, valid_from precedence three-branch - test/consolidate-valid-until.test.ts (new, 4 cases): chronological writeback (R4a), same-day id tiebreaker, cycle re-run zero duplicates (R4b/R7), valid_until idempotency - test/schema-bootstrap-coverage.test.ts: add four typed-claim columns to COLUMN_EXEMPTIONS (migration co-defines the partial index, no forward reference to bootstrap) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(trajectory): find_trajectory MCP op + eval/founder CLIs (v0.35.6 wave 2/3) Engine method (D-CDX-1, D-CDX-6): - BrainEngine.findTrajectory(opts) on both Postgres and PGLite - TrajectoryOpts: scalar sourceId fast path + sourceIds federated array (mirrors v0.34.1.0 search* dual pattern) - opts.remote: when true, SQL adds AND visibility='world' so OAuth read clients see only world-visibility facts (mirrors recall's posture — closes the F7 privacy regression Codex caught in plan review) - Single SQL query, ORDER BY valid_from ASC, id ASC for deterministic output (R3 pin). Returns TrajectoryPoint[] including raw embedding so the caller can compute drift without a second round-trip Pure function library (src/core/trajectory.ts, new): - detectRegressions(points, threshold): walks consecutive (metric, value) pairs per metric; emits when newer drops >= threshold below older. 10% default, override via GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD - computeDriftScore(points): 1 - mean(cosine(emb[i], emb[i-1])) over embedded points; clamped [0,1]; null when <3 embedded points (D-ENG-3 graceful degradation) - computeTrajectoryStats(points): composed shape returning both - TRAJECTORY_SCHEMA_VERSION = 1 — additive-only across releases (R5) MCP op (src/core/operations.ts): - find_trajectory: scope read, NOT localOnly. Routes through sourceScopeOpts(ctx) for federated isolation AND threads ctx.remote for visibility filtering. Strips raw Float32Array embeddings from the wire shape; converts valid_from to YYYY-MM-DD string - Registered in operations array after find_experts - FIND_TRAJECTORY_DESCRIPTION in operations-descriptions.ts CLIs: - gbrain eval trajectory <entity> [--metric M] [--since D] [--until D] [--limit N] [--json] — chronological human view with [REGRESSION] inline annotation; thin-client routing via callRemoteTool(find_trajectory). Dispatched in src/commands/eval.ts sub-subcommand block - gbrain founder scorecard <entity> [--since D] [--until D] [--json] — pure aggregation over Phase 2's substrate. Four signals: claim_accuracy (over resolved takes), consistency, growth_trajectory, red_flags. computeFounderScorecard exported for tests. Registered as top-level command in cli.ts; added to CLI_ONLY set Tests (45 cases across 5 files): - test/engine-find-trajectory.test.ts: 18 cases — chronological order, source scoping (scalar + federated), visibility filter on remote=true, metric + since/until filters, regression detection at threshold boundaries, drift score with various embedding states - test/operations-find-trajectory.test.ts: 9 cases — op registration, param validation, JSON envelope shape, R5 schema_version: 1, embedding stripped from wire, R6 visibility filter, source scoping - test/eval-trajectory.test.ts: 7 cases — arg parsing, --help, --json envelope, regression annotation, --metric filter, empty entity - test/founder-scorecard.test.ts: 9 cases — empty inputs no-NaN (G2), claim_accuracy math, consistency math, growth_trajectory math, red_flags fire for regression / narrative_drift / missed_prediction - test/eval-contradictions/no-valid-until-write.test.ts: 4 cases — R1 (probe never writes valid_until under eval-contradictions/) + R8 (only allow-listed files write valid_until anywhere in src/) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: v0.35.6.0 — CHANGELOG + VERSION + docs + migration note Bumps to v0.35.6.0 (next-minor after master's v0.35.5.1 — typed-claim substrate + trajectory + founder scorecard is a new user-facing feature surface, not a fix). - VERSION + package.json synced - CHANGELOG.md release-summary block in the wave-style voice, lead with what the user can now DO. Sections: typed metric claims in the fence, chronological metric trajectories, founder scorecard, MCP find_trajectory op, cycle re-run idempotency fix, embedding-on-insert fix, valid_from precedence fix. To-take-advantage-of block with verification + opt-in fence syntax example - CLAUDE.md Key Files entry consolidating the wave across eval-trajectory.ts + founder-scorecard.ts + trajectory.ts. Names every D-ENG / D-CDX decision and the Codex outside-voice F-numbers - skills/migrations/v0.35.6.md agent-readable migration note. Includes fence-syntax example for typed-claim rows so downstream agents start emitting them. Iron-rule contracts called out (R1 + R8 + R7 + visibility) - llms-full.txt regenerated to reflect the new CLAUDE.md entry Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: post-ship sync for v0.35.7.0 — trajectory + founder scorecard - README.md: add `gbrain eval trajectory` to EVAL section, add new TEMPORAL block covering `gbrain founder scorecard` + the GBRAIN_TRAJECTORY_REGRESSION_THRESHOLD env override; add v0.35.7 "What's new" paragraph below the v0.28.8 LongMemEval blurb - AGENTS.md: new bullet under Common tasks teaching agents to reach for `gbrain eval trajectory` / `gbrain founder scorecard` / the `find_trajectory` MCP op when asked to evaluate a founder/company over time - docs/contradictions.md: append "Temporal axis follow-on (v0.35.3.1 + v0.35.7)" subsection under See also, cross-linking the trajectory substrate and naming the auto-supersession.ts:4 invariant preserved by both the verdict enum (probe side) and consolidate's valid_until writeback (cycle side) - CLAUDE.md: fix stale (v0.35.4) tag on the trajectory entry to (v0.35.7) — version got rebumped twice during the merge wave - skills/migrations/v0.35.7.md renamed to v0.35.7.0.md for consistency with the v0.35.0.0.md / v0.14.0.md / etc naming convention - llms-full.txt regenerated to reflect the CLAUDE.md edit Coverage map (Diataxis): /eval trajectory CLI ✅ ref (README, AGENTS) ✅ how-to (CHANGELOG) ❌ tutorial /founder scorecard CLI ✅ ref (README, AGENTS) ✅ how-to (CHANGELOG) ❌ tutorial find_trajectory MCP op ✅ ref (CLAUDE.md, AGENTS, contradictions.md) typed-claim fence cols ✅ ref (skills/migrations/v0.35.7.0.md, CHANGELOG) Migration v67 ✅ ref (CLAUDE.md, CHANGELOG) No tutorial / explanation gaps worth filling in this PR — the migration note's fence-syntax example already covers the "first typed claim" walkthrough. ARCHITECTURE diagrams not drifted (the trajectory work extends existing facts/takes infrastructure; no new component boxes). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
227 lines
9.4 KiB
TypeScript
227 lines
9.4 KiB
TypeScript
/**
|
|
* v0.35.4 (D-CDX-4) — consolidate semantic upsert + chronological
|
|
* valid_until writeback.
|
|
*
|
|
* Pins:
|
|
* - R4a: a cluster of 3 chronologically-ordered facts produces
|
|
* 2 facts with valid_until set (older) and 1 with NULL (newest).
|
|
* - R4b/R7: running consolidate twice on the same input produces zero
|
|
* NEW takes (semantic upsert by (page_id, claim, since_date)).
|
|
* This is the Codex F4 fix — without it, the second cycle's
|
|
* extract_facts would clear consolidated_at and the second
|
|
* consolidate would append duplicate takes via MAX(row_num)+1.
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
|
import { runPhaseConsolidate } from '../src/core/cycle/phases/consolidate.ts';
|
|
|
|
let engine: PGLiteEngine;
|
|
|
|
beforeAll(async () => {
|
|
engine = new PGLiteEngine();
|
|
await engine.connect({});
|
|
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 pages WHERE slug LIKE 'cdx4-%'`);
|
|
});
|
|
|
|
function unitVec(): string {
|
|
const a = new Float32Array(1536);
|
|
a[0] = 1.0;
|
|
return '[' + Array.from(a).join(',') + ']';
|
|
}
|
|
|
|
async function seedPage(slug: string): Promise<number> {
|
|
await engine.executeRaw(
|
|
`INSERT INTO pages (slug, type, title) VALUES ($1, 'company', 'Test') ON CONFLICT DO NOTHING`,
|
|
[slug],
|
|
);
|
|
const r = await engine.executeRaw<{ id: number }>(
|
|
`SELECT id FROM pages WHERE slug = $1 AND source_id = 'default'`,
|
|
[slug],
|
|
);
|
|
return r[0].id;
|
|
}
|
|
|
|
async function insertFact(args: {
|
|
entity_slug: string;
|
|
text: string;
|
|
valid_from: Date;
|
|
confidence?: number;
|
|
}): Promise<number> {
|
|
const r = await engine.executeRaw<{ id: number }>(
|
|
`INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from, confidence, embedding, embedded_at)
|
|
VALUES ('default', $1, $2, 'fact', 'test', $3::timestamptz, $4, $5::vector, $3::timestamptz)
|
|
RETURNING id`,
|
|
[args.entity_slug, args.text, args.valid_from.toISOString(), args.confidence ?? 0.9, unitVec()],
|
|
);
|
|
return r[0].id;
|
|
}
|
|
|
|
describe('R4a — chronological valid_until writeback', () => {
|
|
test('cluster of 3 chronologically-ordered facts: 2 older get valid_until set, newest stays NULL', async () => {
|
|
await seedPage('cdx4-acme-mrr');
|
|
const olderDay = new Date('2026-01-15T00:00:00Z');
|
|
const midDay = new Date('2026-04-12T00:00:00Z');
|
|
const newest = new Date('2026-07-08T00:00:00Z');
|
|
|
|
// All three close enough in vector space to cluster together (identical
|
|
// embeddings via unitVec()). Past the 24h "oldest age" gate.
|
|
const idOlder = await insertFact({
|
|
entity_slug: 'cdx4-acme-mrr',
|
|
text: 'MRR claim',
|
|
valid_from: olderDay,
|
|
});
|
|
const idMid = await insertFact({
|
|
entity_slug: 'cdx4-acme-mrr',
|
|
text: 'MRR claim',
|
|
valid_from: midDay,
|
|
});
|
|
const idNewest = await insertFact({
|
|
entity_slug: 'cdx4-acme-mrr',
|
|
text: 'MRR claim',
|
|
valid_from: newest,
|
|
});
|
|
|
|
const r = await runPhaseConsolidate(engine, {});
|
|
expect(r.details.facts_consolidated).toBe(3);
|
|
expect(r.details.takes_written).toBe(1);
|
|
|
|
const rows = await engine.executeRaw<{ id: number; valid_until: Date | null }>(
|
|
`SELECT id, valid_until FROM facts WHERE entity_slug = 'cdx4-acme-mrr' ORDER BY valid_from ASC`,
|
|
);
|
|
expect(rows.length).toBe(3);
|
|
// Older fact's valid_until = mid.valid_from.
|
|
expect(rows[0].id).toBe(idOlder);
|
|
expect(rows[0].valid_until).not.toBeNull();
|
|
expect(new Date(rows[0].valid_until!).toISOString().slice(0, 10)).toBe('2026-04-12');
|
|
// Mid fact's valid_until = newest.valid_from.
|
|
expect(rows[1].id).toBe(idMid);
|
|
expect(rows[1].valid_until).not.toBeNull();
|
|
expect(new Date(rows[1].valid_until!).toISOString().slice(0, 10)).toBe('2026-07-08');
|
|
// Newest fact's valid_until stays NULL.
|
|
expect(rows[2].id).toBe(idNewest);
|
|
expect(rows[2].valid_until).toBeNull();
|
|
});
|
|
|
|
test('same-day cluster (3 facts, identical valid_from): id tiebreaker establishes chronological order', async () => {
|
|
await seedPage('cdx4-acme-sameday');
|
|
const sameDay = new Date(Date.now() - 30 * 60 * 60 * 1000);
|
|
const idA = await insertFact({ entity_slug: 'cdx4-acme-sameday', text: 'same day', valid_from: sameDay });
|
|
const idB = await insertFact({ entity_slug: 'cdx4-acme-sameday', text: 'same day', valid_from: sameDay });
|
|
const idC = await insertFact({ entity_slug: 'cdx4-acme-sameday', text: 'same day', valid_from: sameDay });
|
|
|
|
await runPhaseConsolidate(engine, {});
|
|
|
|
// All three valid_from values are equal; the (id ASC) tiebreaker
|
|
// makes the lowest-id row the "oldest" chronologically. Pin that
|
|
// contract since the trajectory CLI depends on this ordering.
|
|
const rows = await engine.executeRaw<{ id: number; valid_until: Date | null }>(
|
|
`SELECT id, valid_until FROM facts WHERE entity_slug = 'cdx4-acme-sameday' ORDER BY id ASC`,
|
|
);
|
|
expect(rows.length).toBe(3);
|
|
expect(rows[0].id).toBe(idA);
|
|
expect(rows[1].id).toBe(idB);
|
|
expect(rows[2].id).toBe(idC);
|
|
// First two are "older" by tiebreaker → both get valid_until set
|
|
// (= sameDay, since the next-newer fact has the same valid_from).
|
|
expect(rows[0].valid_until).not.toBeNull();
|
|
expect(rows[1].valid_until).not.toBeNull();
|
|
// Newest by tiebreaker stays NULL.
|
|
expect(rows[2].valid_until).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('R4b / R7 — cycle idempotency: re-run consolidate produces zero new takes (Codex F4 fix)', () => {
|
|
test('semantic upsert: second consolidate on identical state produces zero NEW takes', async () => {
|
|
await seedPage('cdx4-idempo-1');
|
|
const oldDate = new Date(Date.now() - 30 * 60 * 60 * 1000);
|
|
for (let i = 0; i < 4; i++) {
|
|
await insertFact({
|
|
entity_slug: 'cdx4-idempo-1',
|
|
text: 'stable claim',
|
|
valid_from: new Date(oldDate.getTime() + i * 60 * 60 * 1000),
|
|
});
|
|
}
|
|
|
|
// First run: 1 take, 4 facts consolidated.
|
|
const r1 = await runPhaseConsolidate(engine, {});
|
|
expect(r1.details.takes_written).toBe(1);
|
|
const countAfter1 = await engine.executeRaw<{ n: string }>(
|
|
`SELECT COUNT(*)::text AS n FROM takes WHERE page_id = (SELECT id FROM pages WHERE slug = 'cdx4-idempo-1')`,
|
|
);
|
|
expect(parseInt(countAfter1[0].n, 10)).toBe(1);
|
|
|
|
// Simulate the Codex F4 scenario: clear consolidated_at on every fact
|
|
// (extract_facts cycle phase wipes facts via delete-then-insert, which
|
|
// is functionally identical to NULL-ing consolidated_at). DO NOT touch
|
|
// valid_until — the prior consolidate wrote it; the semantic upsert
|
|
// should still find the take.
|
|
await engine.executeRaw(
|
|
`UPDATE facts SET consolidated_at = NULL, consolidated_into = NULL
|
|
WHERE entity_slug = 'cdx4-idempo-1'`,
|
|
);
|
|
|
|
// Second run: must NOT append another take.
|
|
const r2 = await runPhaseConsolidate(engine, {});
|
|
expect(r2.details.facts_consolidated).toBe(4);
|
|
// takes_written reports the NEW takes inserted this run; on the upsert
|
|
// hit path it's 0 (no new INSERT) but facts still get marked consolidated.
|
|
expect(r2.details.takes_written).toBe(0);
|
|
|
|
const countAfter2 = await engine.executeRaw<{ n: string }>(
|
|
`SELECT COUNT(*)::text AS n FROM takes WHERE page_id = (SELECT id FROM pages WHERE slug = 'cdx4-idempo-1')`,
|
|
);
|
|
expect(parseInt(countAfter2[0].n, 10)).toBe(1); // STILL 1 — no duplicate
|
|
|
|
// Facts were re-consolidated into the existing take.
|
|
const facts = await engine.executeRaw<{ consolidated_into: number }>(
|
|
`SELECT consolidated_into FROM facts WHERE entity_slug = 'cdx4-idempo-1' AND consolidated_into IS NOT NULL`,
|
|
);
|
|
expect(facts.length).toBe(4);
|
|
});
|
|
|
|
test('valid_until idempotency: second run leaves valid_until unchanged (no diff)', async () => {
|
|
await seedPage('cdx4-idempo-2');
|
|
const t1 = new Date('2026-01-15T00:00:00Z');
|
|
const t2 = new Date('2026-04-12T00:00:00Z');
|
|
const t3 = new Date('2026-07-08T00:00:00Z');
|
|
await insertFact({ entity_slug: 'cdx4-idempo-2', text: 'iterable', valid_from: t1 });
|
|
await insertFact({ entity_slug: 'cdx4-idempo-2', text: 'iterable', valid_from: t2 });
|
|
await insertFact({ entity_slug: 'cdx4-idempo-2', text: 'iterable', valid_from: t3 });
|
|
|
|
await runPhaseConsolidate(engine, {});
|
|
const before = await engine.executeRaw<{ id: number; valid_until: Date | null }>(
|
|
`SELECT id, valid_until FROM facts WHERE entity_slug = 'cdx4-idempo-2' ORDER BY valid_from ASC`,
|
|
);
|
|
|
|
// Reset consolidated_at to simulate extract_facts re-run.
|
|
await engine.executeRaw(
|
|
`UPDATE facts SET consolidated_at = NULL, consolidated_into = NULL
|
|
WHERE entity_slug = 'cdx4-idempo-2'`,
|
|
);
|
|
|
|
await runPhaseConsolidate(engine, {});
|
|
const after = await engine.executeRaw<{ id: number; valid_until: Date | null }>(
|
|
`SELECT id, valid_until FROM facts WHERE entity_slug = 'cdx4-idempo-2' ORDER BY valid_from ASC`,
|
|
);
|
|
// Same valid_until values; the IS DISTINCT FROM guard avoided rewrites.
|
|
expect(after.length).toBe(3);
|
|
for (let i = 0; i < before.length; i++) {
|
|
expect(after[i].id).toBe(before[i].id);
|
|
const a = after[i].valid_until ? new Date(after[i].valid_until!).toISOString() : null;
|
|
const b = before[i].valid_until ? new Date(before[i].valid_until!).toISOString() : null;
|
|
expect(a).toBe(b);
|
|
}
|
|
});
|
|
});
|