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>
321 lines
14 KiB
TypeScript
321 lines
14 KiB
TypeScript
/**
|
|
* v0.35.4 — BrainEngine.findTrajectory (T4) + trajectory.ts derived
|
|
* metrics tests.
|
|
*
|
|
* Pins:
|
|
* - Chronological ordering by (valid_from ASC, fact_id ASC) — R3.
|
|
* - Source scoping (scalar + federated array, D-CDX-6).
|
|
* - Visibility filter for remote callers (D-CDX-1) — R6.
|
|
* - Metric filter narrows results to a single canonical name.
|
|
* - since/until window honored.
|
|
* - Regression detection per locked threshold (D-ENG-2).
|
|
* - Drift score returns null when <3 embedded points (G3).
|
|
* - Empty entity returns {points: [], regressions: [], drift_score: null} (G1).
|
|
*/
|
|
|
|
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
|
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
|
import {
|
|
detectRegressions,
|
|
computeDriftScore,
|
|
computeTrajectoryStats,
|
|
DEFAULT_REGRESSION_THRESHOLD,
|
|
} from '../src/core/trajectory.ts';
|
|
import type { TrajectoryPoint } from '../src/core/engine.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 WHERE entity_slug LIKE 'traj-%'`);
|
|
await engine.executeRaw(`DELETE FROM sources WHERE id LIKE 'traj-%'`);
|
|
});
|
|
|
|
function vecForMetric(metric: string, offset: number): string {
|
|
// Deterministic per-metric/offset embedding: each metric gets a
|
|
// unit-vector in a different "direction" of the embedding space, with
|
|
// a small perturbation per offset so consecutive same-metric facts
|
|
// are very-similar-but-not-identical (drift score lands between 0 and
|
|
// some small value).
|
|
const a = new Float32Array(1536);
|
|
const idx = (metric.charCodeAt(0) + offset) % 1536;
|
|
a[idx] = 1.0;
|
|
a[(idx + 1) % 1536] = 0.05 * offset; // tiny drift between consecutive
|
|
return '[' + Array.from(a).join(',') + ']';
|
|
}
|
|
|
|
async function insertTyped(args: {
|
|
source_id?: string;
|
|
entity_slug: string;
|
|
metric: string;
|
|
value: number;
|
|
unit?: string;
|
|
period?: string;
|
|
valid_from: Date;
|
|
visibility?: 'private' | 'world';
|
|
offset?: number;
|
|
text?: string;
|
|
}): Promise<number> {
|
|
const sid = args.source_id ?? 'default';
|
|
await engine.executeRaw(
|
|
`INSERT INTO sources (id, name) VALUES ($1, $1) ON CONFLICT DO NOTHING`,
|
|
[sid],
|
|
);
|
|
const r = await engine.executeRaw<{ id: number }>(
|
|
`INSERT INTO facts (source_id, entity_slug, fact, kind, source, valid_from,
|
|
claim_metric, claim_value, claim_unit, claim_period,
|
|
visibility, embedding, embedded_at)
|
|
VALUES ($1, $2, $3, 'fact', 'test', $4::timestamptz,
|
|
$5, $6, $7, $8,
|
|
$9, $10::vector, $4::timestamptz)
|
|
RETURNING id`,
|
|
[
|
|
sid, args.entity_slug, args.text ?? `${args.metric} ${args.value}`,
|
|
args.valid_from.toISOString(),
|
|
args.metric, args.value, args.unit ?? null, args.period ?? null,
|
|
args.visibility ?? 'private',
|
|
vecForMetric(args.metric, args.offset ?? 0),
|
|
],
|
|
);
|
|
return r[0].id;
|
|
}
|
|
|
|
describe('findTrajectory — chronological ordering (R3)', () => {
|
|
test('returns points in (valid_from ASC, id ASC) order regardless of insert order', async () => {
|
|
// Insert out of order. Engine must re-order.
|
|
const idJul = await insertTyped({ entity_slug: 'traj-order', metric: 'mrr', value: 150000, valid_from: new Date('2026-07-08') });
|
|
const idJan = await insertTyped({ entity_slug: 'traj-order', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });
|
|
const idApr = await insertTyped({ entity_slug: 'traj-order', metric: 'mrr', value: 200000, valid_from: new Date('2026-04-12') });
|
|
|
|
const points = await engine.findTrajectory({ entitySlug: 'traj-order' });
|
|
expect(points.map(p => p.fact_id)).toEqual([idJan, idApr, idJul]);
|
|
expect(points[0].valid_from.toISOString().slice(0, 10)).toBe('2026-01-15');
|
|
expect(points[2].valid_from.toISOString().slice(0, 10)).toBe('2026-07-08');
|
|
});
|
|
});
|
|
|
|
describe('findTrajectory — source scoping (D-CDX-6)', () => {
|
|
test('scalar sourceId returns only that source', async () => {
|
|
await insertTyped({ source_id: 'traj-src-A', entity_slug: 'traj-srcscope', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });
|
|
await insertTyped({ source_id: 'traj-src-B', entity_slug: 'traj-srcscope', metric: 'mrr', value: 99999, valid_from: new Date('2026-01-15') });
|
|
|
|
const pointsA = await engine.findTrajectory({ entitySlug: 'traj-srcscope', sourceId: 'traj-src-A' });
|
|
expect(pointsA.length).toBe(1);
|
|
expect(pointsA[0].value).toBe(50000);
|
|
|
|
const pointsB = await engine.findTrajectory({ entitySlug: 'traj-srcscope', sourceId: 'traj-src-B' });
|
|
expect(pointsB.length).toBe(1);
|
|
expect(pointsB[0].value).toBe(99999);
|
|
});
|
|
|
|
test('federated sourceIds returns union across the array', async () => {
|
|
await insertTyped({ source_id: 'traj-src-A', entity_slug: 'traj-fed', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });
|
|
await insertTyped({ source_id: 'traj-src-B', entity_slug: 'traj-fed', metric: 'mrr', value: 99999, valid_from: new Date('2026-04-12') });
|
|
await insertTyped({ source_id: 'traj-src-C', entity_slug: 'traj-fed', metric: 'mrr', value: 11111, valid_from: new Date('2026-07-08') });
|
|
|
|
const points = await engine.findTrajectory({
|
|
entitySlug: 'traj-fed',
|
|
sourceIds: ['traj-src-A', 'traj-src-B'],
|
|
});
|
|
// Two of three sources visible, in chronological order.
|
|
expect(points.length).toBe(2);
|
|
expect(points.map(p => p.value)).toEqual([50000, 99999]);
|
|
});
|
|
});
|
|
|
|
describe('findTrajectory — visibility filter (D-CDX-1 / R6)', () => {
|
|
test('remote=true returns ONLY world-visibility points', async () => {
|
|
await insertTyped({ entity_slug: 'traj-vis', metric: 'mrr', value: 50000, visibility: 'private', valid_from: new Date('2026-01-15') });
|
|
await insertTyped({ entity_slug: 'traj-vis', metric: 'mrr', value: 99999, visibility: 'world', valid_from: new Date('2026-04-12') });
|
|
|
|
const trusted = await engine.findTrajectory({ entitySlug: 'traj-vis', remote: false });
|
|
expect(trusted.length).toBe(2); // local CLI sees both
|
|
|
|
const remote = await engine.findTrajectory({ entitySlug: 'traj-vis', remote: true });
|
|
expect(remote.length).toBe(1); // OAuth client sees world only
|
|
expect(remote[0].value).toBe(99999);
|
|
});
|
|
|
|
test('remote default (undefined) is treated as trusted — sees both', async () => {
|
|
await insertTyped({ entity_slug: 'traj-vis-default', metric: 'mrr', value: 50000, visibility: 'private', valid_from: new Date('2026-01-15') });
|
|
await insertTyped({ entity_slug: 'traj-vis-default', metric: 'mrr', value: 99999, visibility: 'world', valid_from: new Date('2026-04-12') });
|
|
|
|
// No `remote` field — engine default must be trusted.
|
|
const all = await engine.findTrajectory({ entitySlug: 'traj-vis-default' });
|
|
expect(all.length).toBe(2);
|
|
});
|
|
});
|
|
|
|
describe('findTrajectory — metric + since + until filters', () => {
|
|
test('metric filter narrows to one canonical name', async () => {
|
|
await insertTyped({ entity_slug: 'traj-m', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });
|
|
await insertTyped({ entity_slug: 'traj-m', metric: 'arr', value: 600000, valid_from: new Date('2026-01-15') });
|
|
|
|
const mrrOnly = await engine.findTrajectory({ entitySlug: 'traj-m', metric: 'mrr' });
|
|
expect(mrrOnly.length).toBe(1);
|
|
expect(mrrOnly[0].metric).toBe('mrr');
|
|
});
|
|
|
|
test('since/until window honored', async () => {
|
|
await insertTyped({ entity_slug: 'traj-w', metric: 'mrr', value: 50000, valid_from: new Date('2026-01-15') });
|
|
await insertTyped({ entity_slug: 'traj-w', metric: 'mrr', value: 99999, valid_from: new Date('2026-04-12') });
|
|
await insertTyped({ entity_slug: 'traj-w', metric: 'mrr', value: 11111, valid_from: new Date('2026-07-08') });
|
|
|
|
const inWindow = await engine.findTrajectory({
|
|
entitySlug: 'traj-w',
|
|
since: '2026-02-01',
|
|
until: '2026-05-01',
|
|
});
|
|
expect(inWindow.length).toBe(1);
|
|
expect(inWindow[0].value).toBe(99999);
|
|
});
|
|
|
|
test('unknown entity returns empty array', async () => {
|
|
const empty = await engine.findTrajectory({ entitySlug: 'traj-does-not-exist' });
|
|
expect(empty).toEqual([]);
|
|
});
|
|
});
|
|
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
// trajectory.ts pure-function tests
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
|
|
function makePoint(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,
|
|
};
|
|
}
|
|
|
|
describe('detectRegressions (D-ENG-2)', () => {
|
|
test('emits a regression when newer value drops by >= threshold', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 200000, date: '2026-04-12' }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 150000, date: '2026-07-08' }), // -25%
|
|
];
|
|
const regs = detectRegressions(points, DEFAULT_REGRESSION_THRESHOLD);
|
|
expect(regs.length).toBe(1);
|
|
expect(regs[0].metric).toBe('mrr');
|
|
expect(regs[0].delta_pct).toBeCloseTo(-0.25, 4);
|
|
expect(regs[0].from_date).toBe('2026-04-12');
|
|
expect(regs[0].to_date).toBe('2026-07-08');
|
|
});
|
|
|
|
test('skips when drop is below threshold (5% with default 10%)', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 100000, date: '2026-01-15' }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 95000, date: '2026-04-12' }), // -5%
|
|
];
|
|
expect(detectRegressions(points).length).toBe(0);
|
|
});
|
|
|
|
test('multiple metrics tracked independently', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 200000, date: '2026-04-12' }),
|
|
makePoint({ id: 2, metric: 'arr', value: 600000, date: '2026-04-12' }),
|
|
makePoint({ id: 3, metric: 'mrr', value: 150000, date: '2026-07-08' }), // -25% mrr
|
|
makePoint({ id: 4, metric: 'arr', value: 700000, date: '2026-07-08' }), // +16% arr → no regression
|
|
];
|
|
const regs = detectRegressions(points);
|
|
expect(regs.length).toBe(1);
|
|
expect(regs[0].metric).toBe('mrr');
|
|
});
|
|
|
|
test('skips points with null value', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 200000, date: '2026-04-12' }),
|
|
{ ...makePoint({ id: 2, metric: 'mrr', value: 0, date: '2026-07-08' }), value: null },
|
|
];
|
|
expect(detectRegressions(points).length).toBe(0);
|
|
});
|
|
|
|
test('skips when older value is 0 (division-by-zero guard)', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 0, date: '2026-04-12' }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 1000, date: '2026-07-08' }),
|
|
];
|
|
expect(detectRegressions(points).length).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('computeDriftScore (D-ENG-3 / G3)', () => {
|
|
function unitVec(dim: number, offset: number): Float32Array {
|
|
const a = new Float32Array(8);
|
|
a[offset % 8] = 1.0;
|
|
return a;
|
|
}
|
|
|
|
test('returns null with fewer than 3 embedded points', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 1, date: '2026-01-15', emb: unitVec(8, 0) }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 2, date: '2026-04-12', emb: unitVec(8, 1) }),
|
|
];
|
|
expect(computeDriftScore(points)).toBeNull();
|
|
});
|
|
|
|
test('returns null when no points have embeddings (G3 graceful fallback)', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 1, date: '2026-01-15' }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 2, date: '2026-04-12' }),
|
|
makePoint({ id: 3, metric: 'mrr', value: 3, date: '2026-07-08' }),
|
|
];
|
|
expect(computeDriftScore(points)).toBeNull();
|
|
});
|
|
|
|
test('identical consecutive embeddings → drift 0 (cohesive narrative)', () => {
|
|
const v = unitVec(8, 0);
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 1, date: '2026-01-15', emb: v }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 2, date: '2026-04-12', emb: v }),
|
|
makePoint({ id: 3, metric: 'mrr', value: 3, date: '2026-07-08', emb: v }),
|
|
];
|
|
expect(computeDriftScore(points)).toBe(0);
|
|
});
|
|
|
|
test('orthogonal consecutive embeddings → drift 1 (every claim unrelated)', () => {
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 1, date: '2026-01-15', emb: unitVec(8, 0) }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 2, date: '2026-04-12', emb: unitVec(8, 1) }),
|
|
makePoint({ id: 3, metric: 'mrr', value: 3, date: '2026-07-08', emb: unitVec(8, 2) }),
|
|
];
|
|
expect(computeDriftScore(points)).toBe(1);
|
|
});
|
|
});
|
|
|
|
describe('computeTrajectoryStats — composed shape', () => {
|
|
test('returns both regressions + drift_score in one call', () => {
|
|
const v = new Float32Array(4);
|
|
v[0] = 1;
|
|
const points: TrajectoryPoint[] = [
|
|
makePoint({ id: 1, metric: 'mrr', value: 200000, date: '2026-04-12', emb: v }),
|
|
makePoint({ id: 2, metric: 'mrr', value: 150000, date: '2026-07-08', emb: v }),
|
|
];
|
|
const stats = computeTrajectoryStats(points);
|
|
expect(stats.regressions.length).toBe(1);
|
|
expect(stats.drift_score).toBeNull(); // <3 embedded
|
|
});
|
|
});
|