Files
gbrain/test/founder-scorecard.test.ts
T
1dadd9ed71 v0.35.7.0 feat: temporal trajectory + founder scorecard (Phases 2-4) (#1131)
* 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>
2026-05-17 18:52:38 -07:00

243 lines
8.5 KiB
TypeScript

/**
* v0.35.4 — `gbrain founder scorecard` CLI (T7) tests.
*
* Pins:
* - Pure compute fn: each of the four rollup fields produces correct math.
* - JSON envelope has schema_version: 1 + every required field (R5).
* - G2: empty entity (no facts, no takes) returns a valid empty rollup
* with no NaN / nulls in numeric slots.
* - Red flags fire for regressions + high drift + missed predictions.
*/
import { describe, test, expect } from 'bun:test';
import { computeFounderScorecard } from '../src/commands/founder-scorecard.ts';
import type { TrajectoryPoint, Take } from '../src/core/engine.ts';
function pt(args: {
id: number;
metric: string;
value: number;
date: string;
emb?: Float32Array | null;
}): TrajectoryPoint {
return {
fact_id: args.id,
valid_from: new Date(args.date),
metric: args.metric,
value: args.value,
unit: 'USD',
period: 'monthly',
text: `${args.metric} = ${args.value}`,
source_session: null,
source_markdown_slug: null,
embedding: args.emb ?? null,
};
}
function take(args: {
id: number;
claim: string;
resolved_outcome: boolean | null;
}): Take {
return {
id: args.id,
page_id: 1,
page_slug: 'companies/acme-example',
row_num: args.id,
claim: args.claim,
kind: 'fact',
holder: 'self',
weight: 0.9,
since_date: '2026-01-15',
until_date: null,
source: 'test',
active: true,
resolved_at: args.resolved_outcome === null ? null : '2026-06-01',
resolved_outcome: args.resolved_outcome,
resolved_value: null,
resolved_unit: null,
resolved_source: null,
resolved_outcome_label: null,
resolved_by: null,
superseded_by: null,
embedded_at: null,
created_at: '2026-01-15',
updated_at: '2026-01-15',
} as unknown as Take;
}
describe('computeFounderScorecard — JSON envelope (R5)', () => {
test('empty inputs → valid empty rollup, schema_version: 1, no NaN (G2)', () => {
const sc = computeFounderScorecard({
entitySlug: 'companies/empty',
windowSince: '2025-05-17',
windowUntil: '2026-05-17',
points: [],
takes: [],
});
expect(sc.schema_version).toBe(1);
expect(sc.entity_slug).toBe('companies/empty');
expect(sc.window.since).toBe('2025-05-17');
expect(sc.window.until).toBe('2026-05-17');
expect(sc.claim_accuracy.predicted).toBe(0);
expect(sc.claim_accuracy.accurate).toBe(0);
expect(sc.claim_accuracy.pct).toBeNull();
expect(sc.consistency.score).toBeNull();
expect(sc.consistency.metric_changes).toBe(0);
expect(sc.consistency.typed_facts).toBe(0);
expect(sc.growth_trajectory).toEqual([]);
expect(sc.red_flags).toEqual([]);
// No NaN slipped into numeric slots.
expect(Number.isNaN(sc.claim_accuracy.predicted)).toBe(false);
expect(Number.isNaN(sc.consistency.metric_changes)).toBe(false);
});
});
describe('computeFounderScorecard — claim_accuracy', () => {
test('3 takes, 1 accurate, 1 missed, 1 unresolved → 1/2 = 50% over RESOLVED only', () => {
const sc = computeFounderScorecard({
entitySlug: 'companies/acme-example',
windowSince: null, windowUntil: null,
points: [],
takes: [
take({ id: 1, claim: 'will hit $1M ARR', resolved_outcome: true }),
take({ id: 2, claim: 'will close X', resolved_outcome: false }),
take({ id: 3, claim: 'might do Y', resolved_outcome: null }),
],
});
expect(sc.claim_accuracy.predicted).toBe(2);
expect(sc.claim_accuracy.accurate).toBe(1);
expect(sc.claim_accuracy.pct).toBeCloseTo(0.5, 3);
});
});
describe('computeFounderScorecard — consistency + growth_trajectory', () => {
test('3-point stable trajectory → 0 changes, score 1.0, growth direction matches latest delta', () => {
const sc = computeFounderScorecard({
entitySlug: 'companies/stable',
windowSince: null, windowUntil: null,
points: [
pt({ id: 1, metric: 'mrr', value: 100, date: '2026-01-15' }),
pt({ id: 2, metric: 'mrr', value: 101, date: '2026-04-12' }),
pt({ id: 3, metric: 'mrr', value: 102, date: '2026-07-08' }),
],
takes: [],
});
// 1% deltas are below the 5% change threshold.
expect(sc.consistency.metric_changes).toBe(0);
expect(sc.consistency.typed_facts).toBe(3);
expect(sc.consistency.score).toBeCloseTo(1.0, 3);
expect(sc.growth_trajectory.length).toBe(1);
expect(sc.growth_trajectory[0].metric).toBe('mrr');
// 101 → 102 = 0.99% delta < 1% threshold → 'flat'.
expect(sc.growth_trajectory[0].direction).toBe('flat');
});
test('trajectory with one big drop → 1 change, score 0.667, direction down', () => {
const sc = computeFounderScorecard({
entitySlug: 'companies/declining',
windowSince: null, windowUntil: null,
points: [
pt({ id: 1, metric: 'mrr', value: 200000, date: '2026-04-12' }),
pt({ id: 2, metric: 'mrr', value: 150000, date: '2026-07-08' }),
pt({ id: 3, metric: 'mrr', value: 150500, date: '2026-09-01' }),
],
takes: [],
});
expect(sc.consistency.metric_changes).toBe(1);
expect(sc.consistency.typed_facts).toBe(3);
expect(sc.consistency.score).toBeCloseTo(1 - 1 / 3, 3);
expect(sc.growth_trajectory[0].direction).toBe('flat'); // last delta is tiny
});
test('multiple metrics: each gets its own growth entry, alphabetically ordered', () => {
const sc = computeFounderScorecard({
entitySlug: 'companies/multi',
windowSince: null, windowUntil: null,
points: [
pt({ id: 1, metric: 'mrr', value: 100, date: '2026-01-15' }),
pt({ id: 2, metric: 'arr', value: 1200, date: '2026-01-15' }),
pt({ id: 3, metric: 'mrr', value: 130, date: '2026-04-12' }),
pt({ id: 4, metric: 'arr', value: 1500, date: '2026-04-12' }),
],
takes: [],
});
expect(sc.growth_trajectory.map(g => g.metric)).toEqual(['arr', 'mrr']);
expect(sc.growth_trajectory[0].direction).toBe('up'); // arr +25%
expect(sc.growth_trajectory[1].direction).toBe('up'); // mrr +30%
});
});
describe('computeFounderScorecard — red_flags', () => {
test('regression fires a red flag', () => {
const sc = computeFounderScorecard({
entitySlug: 'companies/regression',
windowSince: null, windowUntil: null,
points: [
pt({ id: 1, metric: 'mrr', value: 200000, date: '2026-04-12' }),
pt({ id: 2, metric: 'mrr', value: 150000, date: '2026-07-08' }),
],
takes: [],
});
const reg = sc.red_flags.find(f => f.kind === 'regression');
expect(reg).toBeDefined();
expect(reg!.metric).toBe('mrr');
expect(reg!.text).toContain('25.0%');
});
test('missed predictions surface as red flags', () => {
const sc = computeFounderScorecard({
entitySlug: 'companies/missed',
windowSince: null, windowUntil: null,
points: [],
takes: [
take({ id: 1, claim: 'predicted X by June, did not hit it', resolved_outcome: false }),
],
});
const missed = sc.red_flags.find(f => f.kind === 'missed_prediction');
expect(missed).toBeDefined();
expect(missed!.text).toContain('did not hit it');
});
test('high drift score (>=0.5) fires a narrative_drift flag', () => {
function v(i: number): Float32Array {
const a = new Float32Array(8);
a[i % 8] = 1.0;
return a;
}
const sc = computeFounderScorecard({
entitySlug: 'companies/drift',
windowSince: null, windowUntil: null,
points: [
pt({ id: 1, metric: 'mrr', value: 100, date: '2026-01-15', emb: v(0) }),
pt({ id: 2, metric: 'mrr', value: 101, date: '2026-04-12', emb: v(3) }),
pt({ id: 3, metric: 'mrr', value: 102, date: '2026-07-08', emb: v(6) }),
],
takes: [],
});
const drift = sc.red_flags.find(f => f.kind === 'narrative_drift');
expect(drift).toBeDefined();
});
test('clean trajectory + accurate takes + low drift = zero red flags', () => {
function v(): Float32Array {
const a = new Float32Array(8);
a[0] = 1.0;
return a;
}
const sc = computeFounderScorecard({
entitySlug: 'companies/clean',
windowSince: null, windowUntil: null,
points: [
pt({ id: 1, metric: 'mrr', value: 100, date: '2026-01-15', emb: v() }),
pt({ id: 2, metric: 'mrr', value: 110, date: '2026-04-12', emb: v() }),
pt({ id: 3, metric: 'mrr', value: 120, date: '2026-07-08', emb: v() }),
],
takes: [
take({ id: 1, claim: 'accurate prediction', resolved_outcome: true }),
],
});
expect(sc.red_flags).toEqual([]);
});
});