| Files | Last commit | Last update |
|---|---|---|
v0.33.3.0 feat(v0.33.3): code intelligence MCP foundation (v0.34 W0a-c + W3) (#934) * feat(v0.34 pre-w0): add code-retrieval eval harness for v0.34 ship gate Captures pre-v0.34 retrieval quality on the gbrain self-corpus before any code-intel work lands, so the v0.34 ship gate (precision@5 +10pp OR answered_rate +15pp on >=15/30 questions) measures real improvement rather than an after-the-fact retuned baseline. * src/eval/code-retrieval/harness.ts -- pure-function metrics (precision@k, recall@k, top-1 stability, gate evaluator) + EvalRunReport types stable across schema_version 1 * src/eval/code-retrieval/questions.json -- 30 questions across callers / callees / definition / references / blast_radius / execution_flow / cluster_membership kinds, expected_files captured against current gbrain layout * src/eval/code-retrieval/strategies.ts -- BaselineStrategy (hybridSearch) + WithCodeIntelStrategy stub (post-W3 fills in code_blast/code_flow/etc.) * src/commands/eval-code-retrieval.ts -- gbrain eval code-retrieval CLI with --baseline / --with-code-intel / --compare subcommands * test/code-retrieval-harness.test.ts -- 26 unit tests across metrics, loader, gate logic; no engine dependency PRE-V0.34 BASELINE WORKFLOW: gbrain eval code-retrieval --baseline --save /tmp/baseline-1.json (run 3x for noise floor) V0.34 SHIP GATE (after W3 lands): gbrain eval code-retrieval --with-code-intel --save /tmp/v034.json gbrain eval code-retrieval --compare /tmp/baseline-1.json /tmp/v034.json Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(v0.34 W0a): source-routing leak across query + two-pass Codex outside-voice review on the v0.34 plan caught two load-bearing sites where sourceId was advertised but never applied — multi-source brains silently cross-contaminated structural retrieval: * operations.ts ~323 — query op handler called hybridSearch without threading ctx.sourceId. Multi-source agents querying with a --source flag got cross-source results. * two-pass.ts:81 (nearSymbol lookup) and two-pass.ts:131 (unresolved edge resolution) — TwoPassOpts.sourceId was declared and threaded through hybridSearch's expandAnchors call, but the actual SQL ignored it. The walk window crossed source boundaries every time. Fix: * query op now reads ctx.sourceId AND accepts a new source_id param (with '__all__' as the explicit force-cross-source escape hatch). Per-call param wins over ctx context. * two-pass.ts both lookups join through pages.source_id when opts.sourceId is set; omitted opts.sourceId preserves the legacy cross-source contract for callers who want it. Regression test: test/e2e/source-routing.test.ts seeds two sources with the same parseMarkdown symbol + a cross-source caller edge. Pins: - nearSymbol + sourceId='source-a' returns ONLY source-a chunks - nearSymbol + sourceId='source-b' returns ONLY source-b chunks - nearSymbol with no sourceId still crosses sources (contract preserved) - walk_depth=1 unresolved-edge resolution stays in source-a PGLite in-memory, no DATABASE_URL needed. The fix proves out under realistic structural retrieval not just a contrived unit test. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(v0.34 W0b): flip CLI source-scoping default to truly source-scoped Codex outside-voice review (finding #7) caught that the v0.20.0 docstring claim "by default we only match the caller's source_id" contradicted the implementation in code-callers.ts:54 + code-callees.ts:43: allSources: allSources || !sourceId The right side made allSources TRUE whenever --source was omitted, INVERTING the documented default. Multi-source brains silently cross- contaminated structural retrieval; gbrain code-callers parseMarkdown on a brain with two repos returned callers from both even though the docstring promised per-source scoping. Fix: * New canonical helper resolveDefaultSource(engine) in sources-ops.ts. Contract per eng review D7: - exactly 1 source registered → return its id (single-source brains, the 80% case; --source flag is unnecessary friction there) - 2+ sources → throw SourceResolutionError(multiple_sources_ambiguous) with the list of valid ids - 0 sources → throw SourceResolutionError(no_sources) * code-callers.ts + code-callees.ts now resolve to the default source when both --source AND --all-sources are absent. To get the pre-v0.34 cross-source behavior, callers must pass --all-sources explicitly. * Same hint text on both commands. Pinned by test/e2e/cli-source-scoping-pglite.test.ts. IRON RULE regression R2: docstring promise now holds. Multi-source brain running gbrain code-callers <symbol> without --source gets a clear error listing valid source ids instead of silent cross-resolution. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W0c): within-file two-pass symbol resolver + edges_backfilled_at watermark Codex's outside-voice review caught that the v0.20.0 graph stores BARE callee tokens (render, find, execute) — not qualified names. Pre-v0.34 recursive blast/flow would alias every same-named function across classes. W0c is the foundation that fixes this: resolve code_edges_symbol rows by matching to_symbol_qualified against the SAME-FILE chunks' symbol_name_qualified, then write the outcome to edge_metadata. This commit is the resolver primitive + schema. The cycle-phase wiring that calls it on every quick-cycle tick lands in the next commit. Schema (v51 migration edges_backfilled_at_v0_34): * content_chunks.edges_backfilled_at TIMESTAMPTZ — resume watermark. Chunks where the column is NULL OR older than EDGE_EXTRACTOR_VERSION_TS get re-walked next tick. SIGINT/OOM/sleep mid-backfill loses at most one batch. * Indexes per D11 from eng review: - idx_code_edges_symbol_resolver(source_id, to_symbol_qualified) — composite for the resolver's per-source lookup. - idx_content_chunks_symbol_lookup(page_id, symbol_name_qualified) WHERE symbol_name_qualified IS NOT NULL — file-batched candidate fetch; also reused by W4-5 cluster recompute. - idx_content_chunks_edges_backfill(edges_backfilled_at) WHERE edges_backfilled_at IS NULL — fast unresumed-row scan. Module (src/core/chunkers/symbol-resolver.ts): * resolveSymbolEdgesIncremental(engine, {sourceId, maxChunks?, onProgress?}) walks stale chunks in 200-chunk batches. For each chunk, loads its unresolved edges, finds same-page candidates by symbol_name_qualified, and writes outcome to edge_metadata: - exactly 1 candidate → {resolved_chunk_id: <id>} - 2+ candidates → {ambiguous: true, candidates: [...]} - 0 candidates → unchanged (cross-file; two-pass.ts handles those) Each batch bumps edges_backfilled_at = NOW() for the chunks. * readEdgeResolution(metadata) — public helper for downstream code (two-pass.ts, code_blast op, eval-capture) to consume the resolver's output without parsing JSON directly. Returns a tagged union. * EDGE_EXTRACTOR_VERSION_TS exported constant — bump when extractor shape changes and the next cycle re-walks all chunks. Tests (5 E2E in test/e2e/symbol-resolver-pglite.test.ts, all PGLite, no DATABASE_URL): unambiguous match, ambiguous multi-match, no match, watermark advance + idempotency, source isolation (no cross-source candidate leak). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W0c): wire resolve_symbol_edges as a new cycle phase W0c's symbol resolver lands as a 12th cycle phase between extract and patterns. The autopilot's quick-cycle path (60s watchdog interval per D2 from eng review) now resolves stale chunks incrementally so agents see resolved edges within ~60s of writes rather than waiting on the slow full-walk path. * CyclePhase + ALL_PHASES + NEEDS_LOCK_PHASES extended with 'resolve_symbol_edges'. Position: between extract (which emits new bare-token edges from sync diffs) and patterns (which reads the graph). Acquires the cycle lock because it writes edge_metadata. * CycleReport.totals adds edges_resolved + edges_ambiguous so doctor and autopilot summaries surface the numbers. * runPhaseResolveSymbolEdges walks every registered source via listSources() + resolveSymbolEdgesIncremental(). Per-call cap is BATCH_SIZE*10 = 2000 chunks so a single watchdog tick stays bounded even on a 100K-chunk brain. Subsequent ticks pick up the leftovers via the edges_backfilled_at watermark. * Test count bumped from 11 → 12 phases in cycle.serial.test.ts and cycle.test.ts (both pinned by the regression guards). Existing 28 cycle tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(v0.34 W3): MCP-expose code_callers / code_callees / code_def / code_refs Pre-v0.34 these four code-intelligence commands lived in CLI_ONLY at cli.ts:30 — agents calling gbrain via MCP couldn't reach them and fell through to text search. This commit ships the agent-facing MCP surface for v0.34 against the existing v0.20+ tree-sitter call graph; recursive blast/flow and clusters land in subsequent commits. * code_callers(symbol, [limit, source_id, all_sources]) — wraps engine.getCallersOf. Reverse view of the A1 call graph. * code_callees(symbol, [limit, source_id, all_sources]) — wraps engine.getCalleesOf. Forward view. * code_def(symbol, [limit, lang]) — wraps findCodeDef. Returns definition sites with file/line/snippet. * code_refs(symbol, [limit, lang]) — wraps findCodeRefs. Returns every reference (comments, strings, imports, call sites). All four are scope:'read', source-scoped by default via ctx.sourceId (W0a contract). Per-call source_id param wins over ctx; pass '__all__' or all_sources=true to force cross-source. * operations-descriptions.ts: 4 new constants per the eng review D10 finding — every description carries an inline example response so agents don't burn first-call context discovering shape. Resolver-grade wording ("BEFORE editing any function, run code_callers...") routes plan-mode questions straight to the right op. * SEARCH_DESCRIPTION gains a cross-link clause pointing at the four new ops so agents stop falling through to text search for code-symbol questions. Tests (11 E2E in test/e2e/code-intel-mcp-ops-pglite.test.ts): - All four ops registered + scope:read + description pinned by constant - All four ops have required symbol param - code_callers / code_callees return the documented envelope shape - Source scoping honors ctx.sourceId - all_sources=true / source_id='__all__' force cross-source - code_def returns the def-site snippet Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(v0.33.0): agent-readable migration doc for the code-intel foundation skills/migrations/v0.33.0.md gives existing-user upgrade guidance for the v0.33.0 foundation pre-release (this branch's accumulated work toward v0.34 Cathedral III): * Source-routing fix (Codex #2) — query / two-pass now honor sourceId * CLI source-scoping default flipped (Codex #7) — gbrain code-callers defaults to source-scoped, --all-sources is the explicit opt-out * MCP exposure of code-callers / code-callees / code-def / code-refs with resolver-grade descriptions agents auto-route to * Within-file symbol resolver runs as a new resolve_symbol_edges cycle phase between extract and patterns * Schema migration v51: edges_backfilled_at watermark + 3 composite/ partial indexes for the resolver hot path * Verification commands the agent runs after gbrain upgrade Bumps the existing-user migration ladder so the auto-update agent (SKILLPACK Section 17) discovers + runs the v0.33.0 migration steps. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(v0.33.0): bump VERSION + package.json + CHANGELOG v0.33.0 ships the v0.34 Cathedral III foundation: MCP exposure of code_callers / code_callees / code_def / code_refs with resolver-grade tool descriptions, plus the source-routing fix + within-file symbol resolver + cycle-phase wiring that v0.34's recursive blast/flow and Leiden clusters will build on. Full release notes in CHANGELOG.md. Trio in lockstep: VERSION: 0.33.0 package.json: 0.33.0 CHANGELOG.md: ## [0.33.0] - 2026-05-11 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(v0.33.0): update dream-cycle phase-order assertions for resolve_symbol_edges E2E test pinned the canonical phase sequence as a regression guard. The v0.33.0 resolve_symbol_edges phase (added between extract and patterns) correctly bumps the count to 12 — caught by the canonical-order test on fresh-Postgres run, fixed by adding the new phase to EXPECTED_PHASES and bumping the version history comment. Both cycle.serial.test.ts and cycle.test.ts were already updated in the W0c cycle-phase commit (6f7dbe1d); this third pin lives in test/e2e/dream-cycle-phase-order-pglite.test.ts and was missed. Full E2E suite now: 550 passed / 0 failed / 81 files (real Postgres on port 5435 via Docker pgvector/pgvector:pg16). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(v0.33.3.0): rebump from v0.33.2.0 → v0.33.3.0 User asked to ship as v0.33.3.0 instead of v0.33.2.0. Single sweep: * VERSION + package.json bumped to 0.33.3.0 * CHANGELOG header + body rewritten to v0.33.3 * skills/migrations/v0.33.0.md → skills/migrations/v0.33.3.0.md (migration files use the version they ship FROM; renaming aligns with the v0.21.0.md / v0.31.0.md convention in CLAUDE.md) * Schema migration name edges_backfilled_at_v0_33_2 → edges_backfilled_at_v0_33_3 in src/core/migrate.ts (also bumps the in-code identifier so the registry name matches the version) * All v0.33.2 comment references swept to v0.33.3 in cycle.ts, operations.ts, operations-descriptions.ts, eval.ts, symbol-resolver.ts + cycle test phase-history comments * llms.txt + llms-full.txt regenerated Trio verified: VERSION: 0.33.3.0 package.json: 0.33.3.0 CHANGELOG.md: ## [0.33.3.0] - 2026-05-12 bun run verify clean; 90 v0.33.3-touched tests pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> | 6 months ago | |
v0.40.2.0 feat: trajectory routing for temporal + knowledge_update (gbrain think + LongMemEval) (#1296) * feat(facts): add event_type column + trajectory-format helper (v0.40.2.0 Commit 1) Substrate work for v0.40.2.0 Track B (trajectory routing for temporal + knowledge_update). This commit lands the schema + the shared formatter; think wiring + LongMemEval extractor + intent routing come in Commits 2-4. Migration v81 (facts_event_type_column): ALTER TABLE facts ADD COLUMN event_type TEXT (nullable, metadata-only). Lets the v0.35.4 typed-claim substrate carry event-shaped rows (event_type='meeting'/'job_change'/'location_change') alongside the metric-shaped rows (claim_metric/claim_value etc) it has carried since v67. Temporal-reasoning questions ("when did I last meet Marco") need the event shape; the metric shape doesn't fit them. Engine changes (pglite + postgres parity): - TrajectoryPoint.event_type: string | null added; projection in both findTrajectory SQL paths returns the column. - TrajectoryOpts.kind?: 'metric' | 'event' | 'all' added (default 'all'). Defensive opt that future-proofs filtering once event rows accumulate. - Both engines apply the new kind filter at SQL level when set. Back-compat (codex outside-voice concern): Existing callers (founder-scorecard, eval-trajectory) already defensively skip metric === null rows in their per-metric math. Event-only rows (metric=NULL, event_type='meeting') ride through invisibly to those callers — verified by the new regression test that asserts byte-identical computeFounderScorecard + computeTrajectoryStats output with and without event rows in the input. Both callers now pass kind:'metric' explicitly for call-site clarity (no behavior change). MCP find_trajectory op: - event_type added to the wire-shape map. - kind param added to the op declaration (enum metric/event/all). Shared formatter (src/core/trajectory-format.ts, new): formatTrajectoryBlock(points, entitySlug, opts) — sibling shape to renderTakesBlock + renderChatBlock. Groups by (metric ?? event_type). Per-metric cap 20, total cap 100 (prompt-budget guardrail). For knowledge_update intent, annotates value-change rows with "(superseded prior)" — the explicit signal codex flagged was missing from default RRF-ordered retrieval. Promoted to src/core/ so both gbrain think (Commit 2) and the LongMemEval harness (Commit 4) consume one source of truth. Prompt-injection coverage (codex Problem 10): src/core/think/sanitize.ts INJECTION_PATTERNS extended with three new entries — close-trajectory, open-trajectory, xml-attr-inject — so adversarial </trajectory> sequences in extracted text get escaped before reaching the model. Parity with the existing </take> coverage. Tests (all hermetic, no DATABASE_URL): - test/trajectory-format.test.ts (17 cases, all green): grouping, caps, sanitization, supersession annotation, determinism, provenance, text-cap, adversarial </trajectory> escape. - test/engine-parity-event-type.test.ts (6 cases): PGLite round-trip of the column + kind filter matrix. - test/regressions/v0_40_2_0-trajectory-backcompat.test.ts (4 cases): pins the byte-identical-output contract that founder-scorecard's per-metric math ignores event rows. - test/migrate.test.ts: v81 round-trip verified via existing structural assertion harness. - 209 tests across 5 impacted suites pass; bun run verify clean (17 pre-checks including privacy, jsonb, type, fuzz purity). Plan: ~/.claude/plans/system-instruction-you-are-working-crystalline-owl.md GSTACK REVIEW REPORT: CEO + ENG + CODEX CLEARED. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(think): trajectory injection for temporal + knowledge_update (v0.40.2.0 Commit 2) Wires the v0.40.2.0 substrate (Commit 1's facts.event_type column + formatTrajectoryBlock) into the production gbrain think surface. Default ON; flip think.trajectory_enabled=false to opt out. New pure modules (zero engine dependency): - src/core/think/intent.ts — classifyIntent(question): regex-first routing into 'temporal' | 'knowledge_update' | 'other'. KU wins over temporal when both match. The 'other' fast path short-circuits with zero SQL. - src/core/think/entity-extract.ts — extractCandidateEntities() pulls high-precision candidates from retrieval slugs (people/, companies/, organizations/, deals/) and medium-precision noun phrases from the question. Word-level tokenization + stop-word boundaries stitch "Blue Bottle" as one candidate while splitting "I last meet Marco" correctly. Leading-verb stripper drops "meet", "visit" etc so "marco" surfaces cleanly. Cap of 5 per question. Engine-touching wiring (src/core/think/index.ts): - RunThinkOpts gains 4 fields: withTrajectory (default true), sourceId, allowedSources, remote. - readThinkTrajectoryEnabled() reads the config kill switch; default true; survives missing config table on legacy brains. - Trajectory orchestration sits between gather and prompt assembly: intent classify → extract candidates → per-candidate resolveEntitySlugWithSource → skip fallback_slugify → 5s timeout Promise.race + 3-wide concurrency cap → formatTrajectoryBlock. Any error degrades to "no block" + TRAJECTORY_INJECTION_FAILED warning; the think call itself never crashes from trajectory. - On success, TRAJECTORY_INJECTED_<N>_POINTS warning records the count for downstream telemetry. Prompt placement (src/core/think/prompt.ts) — Codex Problem 6 fix: buildThinkUserMessage's trajectoryBlock slot honors BOTH existing orderings — calibration mode inserts trajectory between calibration and question; default mode inserts between retrieval and the output instruction. NO third ordering is introduced. Empty trajectoryBlock skips the "Known trajectory:" header entirely (don't cue the model we tried). Resolution-source signal (src/core/entities/resolve.ts) — Codex Problem 5: New companion resolveEntitySlugWithSource() returns {slug, source: 'exact_page' | 'fuzzy_match' | 'fallback_slugify'} so trajectory routing can skip fallback-only resolutions — querying findTrajectory on an invented slug always returns [] and wastes a SQL round-trip. The original resolveEntitySlug keeps its contract for pre-v0.40 callers. MCP think op handler (src/core/operations.ts): Extracts sourceScopeOpts(ctx) into scalar sourceId + allowedSources + remote, threads through to runThink. CLI callers omit (engine default source, remote=false). Mirrors the same source-scope discipline applied to all other read paths in v0.34.1.0. Sanitization (Commit 1 already extended INJECTION_PATTERNS for </trajectory> — consumed here). Test coverage (all hermetic, no DATABASE_URL, no API keys): - test/think-intent.test.ts (14 cases) — temporal, KU, other, precedence (KU wins when both match), defensive non-string inputs. - test/think-entity-extract.test.ts (10 cases) — retrieved-slug source, noun-phrase source, stop-word stripping, leading-verb stripping, dedup across sources, 5-candidate cap. - test/think-trajectory-injection.test.ts (7 cases against PGLite in-memory) — temporal intent injection happy path with superseded- prior annotation, "other" intent short-circuit, withTrajectory: false bypass, think.trajectory_enabled=false config bypass, empty-trajectory skip, engine.findTrajectory throw is caught (Promise.allSettled defense), TRAJECTORY_INJECTED warning count. - Existing test/think-pipeline.serial.test.ts re-asserted unchanged (10 cases — calibration mode parity, gather, sanitization, cite-render all intact). 72 tests pass across 7 impacted suites; bun run verify clean (17 pre- checks). Defaulted on per CEO + Eng D1; kill switch via config. Plan: ~/.claude/plans/system-instruction-you-are-working-crystalline-owl.md Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(longmemeval): inline Haiku claim extractor + content-hash cache (v0.40.2.0 Commit 3) Populates the LongMemEval benchmark brain's facts table inline at import time so Commit 4's intent routing has data to retrieve. Per the CHANGELOG D1 decision, this is full-haystack preprocessing — disclosed explicitly in the benchmark output's methodology_note field (Commit 4). New module src/eval/longmemeval/extract.ts: extractAndInsertClaims({engine, client, model, sessionSlug, sessionId, sessionBody, sourceId, aliasMap}) - Hashes the session body (sha256) for cache lookup. - Cache hit → reuses parsed claims (cuts a 3-iteration benchmark run from $1.50 to $0.50 when sessions repeat across questions, as they do in LongMemEval). - Cache miss → one Haiku call. System prompt asks for {entity, metric, value, unit, period, event_type, valid_from, text}[] JSON. New parseExtractedJsonArray() helper does fence-strip + parse (parseModelJSON from cross-modal-eval is shaped for scored objects, not arrays — different parser needed here). - Per-record validateClaim() drops malformed records (missing entity, bad date) silently; the rest land in NewFact rows. - Per-question AliasMap (Codex Problem 4 — semantics pinned): "Marco" + "Marco Smith" + "marco" in the SAME question collapse to one slug via first-mention-wins canonicalization. Across questions, the harness creates a fresh map (no leak). - Real-page-aware entity resolution via the v0.40.2.0 resolveEntitySlugWithSource (Commit 2). Slugify-fallback rows still insert (we need the data); the resolution_source signal is only consulted at trajectory retrieval time (Commit 4). - Bulk insert via engine.insertFacts with the gbrain-allow-direct-insert allow-list comment per the check-system-of-record CI guard contract — benchmark brain is ephemeral in-memory PGLite, no markdown source-of-truth applies. - Fail-open posture: Haiku throw, malformed JSON, insert collision all return inserted=0 without throwing. One bad session never kills the per-question loop. - getCacheStats() exposes hits/misses/size for the per-run stderr telemetry Codex Problem 14 asked for (empirical hit-rate reporting; the optimistic claim self-verifies). Substrate plumbing (extends Commit 1): - NewFact.event_type?: string | null added in engine.ts so the extractor can pass event-shaped rows through to insertFacts. - PGLite engine + Postgres engine insertFacts() now persist event_type. Param-positional dispatch extended to 20/21 placeholders (null-embedding vs embedding-present); tx.unsafe vector cast on Postgres path unchanged. Test coverage (test/longmemeval-extract.test.ts, 13 cases, hermetic): - Happy path: typed-claim + event rows both insert with correct kind (event_type='meeting' → kind='event'; claim_metric='mrr' → kind='fact'). - Alias map: per-session collapsing ("Marco" + "Marco Smith"), cross-session persistence within one question, fresh map per question (caller-clears semantics pinned). - Content-hash cache: identical body → cache hit, only ONE Haiku call across two sessions; different bodies miss; getCacheStats reports hits/misses/size. - Fail-open: malformed JSON, Haiku throw, empty array output, invalid records (missing entity, bad date) — none crash; 0 inserted in each case. 55 tests pass across 4 impacted suites; bun run verify clean. Plan: ~/.claude/plans/system-instruction-you-are-working-crystalline-owl.md Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(longmemeval): trajectory intent routing + prompt splice + methodology disclosure (v0.40.2.0 Commit 4) The final wiring: per-question intent classification + trajectory call + block splice into the answer-gen prompt. Plus the methodology disclosure stamps that close out the Codex D1 contract. New module src/eval/longmemeval/intent.ts: classifyIntent(q): prefers q.question_type from the dataset (LongMemEval ships labels like 'temporal-reasoning', 'knowledge-update', 'single-session-user') before falling back to the SHARED regex set imported from src/core/think/intent.ts. Single source of truth for the regex — think and longmemeval cannot drift. Harness wiring in src/commands/eval-longmemeval.ts: - runEvalLongMemEval() spawns an extractor model via resolveModel (tier:'utility' → haiku) when trajectory routing is enabled. Calls resetExtractorState() once per benchmark run so the content-hash cache + counters start clean. - runOneQuestion() creates a FRESH per-question AliasMap (Codex Problem 4 — first-mention-wins canonicalization stays scoped to one question, never leaks across). - Per session: after importFromContent lands, extractAndInsertClaims populates the facts table. Fail-open if the Haiku call errors; next session keeps going. - After hybridSearch returns: classifyIntent(q) routes temporal/knowledge_update through extractCandidateEntities (the SHARED helper from Commit 2's think/entity-extract) → per-candidate findTrajectory with 5s Promise.race timeout → formatTrajectoryBlock. First candidate with a non-empty trajectory wins. - generateAnswer() splices the trajectory block BEFORE the Retrieved sessions block. Empty block (no entity match / no points) → no "Known trajectory:" header (don't cue the model we tried). - JSON envelope gains 5 fields per question when trajectory routing is on: intent, trajectory_points, entity_resolved, resolution_source, methodology_note. methodology_note also written to stderr at run completion. Resolution-source gate DIVERGES from think (intentional): In the think production path, fallback_slugify results are skipped because querying invented slugs wastes SQL — production brains have canonical pages. In the LongMemEval benchmark, there ARE no canonical pages; both the extractor and the lookup go through slugify-fallback on the same free-form name, so they cohere on the same slug. Applying the think-path gate here would permanently block trajectory injection on the benchmark. Comment in runOneQuestion documents the divergence. New CLI flag --no-trajectory: Bypasses BOTH the Haiku extractor AND the per-question intent routing. Used by the measurement protocol to baseline default-on vs no-trajectory across 3 seeds per condition with paired-bootstrap CI. Documented in the help text. New RunOpts fields: - extractorClient?: ThinkLLMClient — separate stub from the answer-gen client so tests can isolate the two surfaces. - extractorModel?: string — model override for the Haiku call. methodology_note = 'extractor=haiku-preprocess-full-haystack-v1' stamped on: - Every per-question JSON envelope row. - Stderr summary at run completion. This is the Codex D1 contract: the temporal-reasoning delta we publish is "gbrain + Haiku-preprocess pipeline" vs "gbrain alone", not directly comparable to LongMemEval's published baselines without that disclosure. Extractor cache hit-rate stderr summary (Codex Problem 14): '[longmemeval] extractor.cache_hits: 412 / 489 sessions (84.2%, cached_bodies=412)' — empirical verification of the optimistic hit-rate claim. The optimistic number self-verifies per run. Test coverage (all hermetic, no API keys): - test/longmemeval-intent.test.ts (9 cases) — dataset question_type → Intent mapping for all six LongMemEval labels; dataset label trumps question-text signal; unknown labels fall through to the regex classifier. - test/longmemeval-trajectory-routing.test.ts (4 cases) — end-to-end through runEvalLongMemEval with both clients stubbed: trajectory block lands in answer-gen prompt for temporal intent + absent for 'other'; --no-trajectory bypasses extractor AND injection AND omits envelope fields; methodology_note stamped on every routed row; perf gate preserved (< 10s for 2-question fixture). 118 tests pass across 11 impacted suites; bun run verify clean. Wave complete. CHANGELOG draft + measurement plan live in the plan file. v0.40.2.0 ready for /ship after a real-LLM spot-check run. Plan: ~/.claude/plans/system-instruction-you-are-working-crystalline-owl.md Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v0.40.2.0) v0.40.2.0 trajectory routing wave — gbrain think now grounds answers about temporal/knowledge-update questions in the typed-claim timeline the brain has been quietly building via the extract_facts cycle phase. Default ON; flip think.trajectory_enabled=false to opt out. LongMemEval-side wiring lands the same plumbing in the benchmark harness with explicit methodology disclosure (extractor=haiku-preprocess- full-haystack-v1) in the JSON envelope and stderr summary — the published temporal-reasoning number is "gbrain + Haiku-preprocess" vs "gbrain alone", not directly comparable to LongMemEval's published baselines without that disclosure. Plan: ~/.claude/plans/system-instruction-you-are-working-crystalline-owl.md 3 review passes: CEO + ENG + CODEX all CLEARED. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: sync project docs for v0.40.2.0 trajectory routing CLAUDE.md, README.md, AGENTS.md extended with the v0.40.2.0 trajectory routing surface: gbrain think integration (default ON via think.trajectory_enabled config key), facts.event_type schema column + TrajectoryPoint.event_type + TrajectoryOpts.kind filter, shared formatTrajectoryBlock helper in src/core/trajectory-format.ts, LongMemEval extractor + intent routing + methodology disclosure, migration v82. llms-full.txt regenerated to match CLAUDE.md edits (CI test/build-llms gate). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: fill v0.40.2.0 unit + e2e gaps (71 new tests across 7 gap areas) Audit of the trajectory-routing wave's test surface vs the shipped code surfaced 7 gaps. All filled, all green. Total: 343 tests across 17 impacted suites (was 272 pre-fill). Gap 1 — Migration v86 structural tests (11 new in test/migrate.test.ts): - v86 entry exists with documented name + idempotent - exactly one event_type column add to facts - IF NOT EXISTS guard - column is nullable (no NOT NULL, no DEFAULT regression guard) - does NOT create any index (event_type is selectivity-poor) - does NOT touch any other table (blast-radius pin) - does NOT carry a sqlFor override (engine-shared SQL contract) - PGLite round-trip: column exists with right type + nullable - event_type INSERT/SELECT round-trip - NULL round-trip for legacy + metric-only rows - LATEST_VERSION >= 86 contract pin Gap 2 — resolveEntitySlugWithSource branch coverage (12 new in test/entity-resolve.test.ts): - exact_page branch (full slug, slug-shape match) - fuzzy_match branch (Title-cased display name, bare first name via prefix expansion) - fallback_slugify branch (unseeded name, multi-word non-match phrase, accented input) - null tail (empty + whitespace) - back-compat parity with resolveEntitySlug for both exact_page and fallback_slugify branches Gap 3 — INJECTION_PATTERNS dedicated coverage for new entries (18 new in test/think-sanitize-trajectory.test.ts): - close-trajectory entry registered + matches canonical and whitespace/case variations - open-trajectory entry registered + matches both no-attr and with-attrs forms - xml-attr-inject strips entity=/metric=/event_type=/kind= - does NOT strip non-trajectory attribute names (class/id/title) - combined multi-vector attack: all three patterns fire - formatTrajectoryBlock end-to-end with adversarial extractor text: one live </trajectory> (the wrapper, not the injection); one entity= attribute (the wrapper, not the injection) - pattern ordering invariant: new entries land after close-take Gap 4 — runThink calibration-mode placement contract (3 new in test/think-trajectory-injection.test.ts): - default mode: question → pages → takes → trajectory → instruction - calibration mode: pages → takes → calibration → trajectory → question → instruction (Codex P6 — no third ordering invented) - empty trajectory in calibration mode preserves the existing calibration shape (no false-positive cue) Gap 5 — runThink resolution_source != fallback_slugify gate (1 new in test/think-trajectory-injection.test.ts): - candidate that only matches via fallback_slugify is NOT queried (think-path divergence from longmemeval-path which accepts it) Gap 6 — E2E for runThink trajectory injection (7 new in test/e2e/think-trajectory-pglite.test.ts): - full pipeline lands <trajectory> block in answer-gen prompt - knowledge_update intent annotates value-change rows with (superseded prior) - 'other' intent short-circuits (no block, no SQL) - think.trajectory_enabled=false config bypasses entire path - empty brain → graceful no-op (no crash, no block) - multi-entity deterministic ordering - adversarial </trajectory> in seeded fact text is escaped before reaching the LLM (end-to-end sanitization gate) Gap 7 — longmemeval extractor stress + persistence pins (6 new in test/longmemeval-extract.test.ts): - alias map cross-session stress with 12 sessions in one question; all 12 rows collapse under ONE entity_slug - different entities stay separate across many sessions - embedding + embedded_at both NULL on benchmark-inserted rows (regression guard against accidental embed-on-write) - row_num sequential + source_markdown_slug stamped per session (v0.32.2 partial UNIQUE index contract) - source field stamped "longmemeval:extractor" (audit-tag pin) - cache key invariance: same body hash hits cache across different sessionId/slug bun run verify clean (17 pre-checks). No regressions in any of the 14 non-new impacted suites. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: exempt facts.event_type from schema-bootstrap-coverage CI guard The schema-bootstrap-coverage CI guard (test/schema-bootstrap-coverage.test.ts) enforces that every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap OR by PGLITE_SCHEMA_SQL's CREATE TABLE bodies OR by COLUMN_EXEMPTIONS. v0.40.2.0's migration v87 adds facts.event_type but deliberately ships without a bootstrap probe because: - No CREATE INDEX in PGLITE_SCHEMA_SQL references event_type - No FK references event_type - All existing callers (founder-scorecard, eval-trajectory, gbrain think trajectory injection) defensively skip NULL-metric rows in per-metric math, so event_type=NULL on pre-v87 brains is invisible - Pre-v87 brains land event_type=NULL via the migration ALTER Exactly mirrors the precedent set by facts.claim_metric / claim_value / claim_unit / claim_period exemptions (v67 typed-claim columns) which are exempted for the same structural reason: column-only migration, no forward-reference index, no downstream filter breaks on old brains. Adding facts.event_type to COLUMN_EXEMPTIONS with a brief rationale comment matching the existing v0.35.6 entry shape. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com> | 5 months ago | |
v0.42.34.0 feat(search): typed-edge relational retrieval — relationship questions get relationship answers (#1959) * feat(search): deterministic relational-query parser Pure, ReDoS-bounded parser that detects relationship queries ("who invested in X", "who at X works on Y", "who introduced me to X", "what connects A and B") and maps them to typed edges. Schema-pack-extensible vocab with subset validation against the link types ingest produces, so query-side and ingest-side relation vocabularies can't drift. No-match / pronoun-seed / adjacency guards keep it precision-first (a candidate only; the arm fires only when a real seed also resolves). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(engine): relationalFanout typed-edge fan-out (both engines) Generalizes traversePaths to a SEED ARRAY, aggregating to ranked NODES (shortest hop, edge-richness count, via-link-types, shortest connecting path, canonical chunk id) instead of edges. Within-source traversal (never crosses a source boundary even across a federated scope), link_source= 'mentions' excluded by default, deleted_at filtered at seed + every neighbor + every node, bounded depth (<=3) + candidate cap. Adds RelationalFanoutRow / RelationalFanoutOpts + the relational SearchResult/SearchOpts fields to types. Lands in lockstep in postgres + pglite engines, pinned by a DATABASE_URL- gated parity block in engine-parity.test.ts; a PGLite unit test exercises the SQL (typed-edge filter, mentions exclusion, deleted_at, canonical chunk, multi-seed connects, determinism) in default CI. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(search): relational recall arm + federation key hardening Wires edge-derived candidates into bare hybridSearch as a FOURTH RRF arm (relational-recall.ts): parse the original query -> scope-aware, confidence-gated seed resolution (drops fallback_slugify; never traverses from a guess) -> relationalFanout -> batch-hydrate, reinforcing each page's REAL canonical chunk (page-level key for chunkless entity pages) -> --explain attribution + fail-open audit row. Text-only (no-op in image mode); pure no-op for non-relational queries; rides every downstream stage (cosine, post-fusion boosts, dedup, reranker, autocut, token budget). Mode wiring: relationalRetrieval + relational_retrieval_depth knobs (conservative off; balanced/tokenmax on; depth 2), per-call thread-through in both bare + cached paths, KNOBS_HASH_VERSION 9->10 (rel=/reld=), config keys, modes-dashboard descriptions, and a relational param on the query op. Federation hardening (structural, engine-wide): the RRF/dedup key now carries source_id via a shared rrfKey() (fixes a latent cross-source collapse where same-slug pages in different sources merged), and the query cache scopes by a canonical source-set key (cacheScopeKey) so a federated read can't be served a single-source row. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(eval): relational benchmark + recall@k harness metrics NamedThingBench harness gains recall@k / recall@10 (the relational headline metric) on QuestionResult + FamilyReport, plus typed seed/linkTypes/kind on NamedThingQuestion so the graph-relationship family is machine-checkable. Adds the relational benchmark corpus (test/fixtures/retrieval-quality/ relational/): a small entity graph whose answers are LEXICALLY UNRECOVERABLE — every page body is generic and never names the entity it relates to, so only the typed edge connects query to answer. corpus.ts is the canonical source for both the seed loader and the 38-question gold set; relational.jsonl is generated from it (a drift test pins them equal). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(eval): relational A/B proof + arm fires on all retrieval paths Fixes the integration bug the eval caught: the relational arm was only injected on the main RRF path, so it silently did nothing whenever vector was unavailable — no embedding provider configured (the default in many deployments) OR embed failure. The arm is now built once and fused via RRF on ALL THREE hybridSearch return paths (no-embedding-provider, embed-failed keyword fallback, main path). Without this it would have been dead in exactly the setups that most need it. Adds gbrain eval retrieval-quality --ab-relational: runs the gold set twice (arm off vs on) in a fixed mode and reports the graph-relationship recall@10 lift + Hit@3 + latency add. The CI A/B test pins the headline result — recall@10 jumps from <25% (lexically unrecoverable) to >75% with the arm on — and a non-relational query returns identical results arm-on vs off (the no-op / no-regression gate). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v0.42.34.0) Relational retrieval feature: typed-edge recall arm + federation key hardening. Also updates the KNOBS_HASH_VERSION 9→10 assertions across the remaining search test files (the bump invalidates relational-off cache rows). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * docs: document typed-edge relational retrieval (v0.42.34.0) CLAUDE.md Search Mode: add relationalRetrieval to the knob table, the knobs_hash v=9→10 note, and a relational-retrieval summary. RETRIEVAL.md: add the relational recall arm to the pipeline diagram. Regenerate llms bundles (build:llms). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(test): size relational fixtures to the actual embedding-column dim CI shard runs with the ZeroEntropy gateway default (1280-d), but the relational test fixtures hardcoded 1536-d embeddings, so chunk inserts were rejected with "expected 1280 dimensions, not 1536" (CheckExpectedDim) — the test (6) shard + test-status failures. The column width tracks the configured gateway default and can shift with shard order, so fixtures now probe content_chunks.embedding's actual atttypmod after initSchema and size embeddings to it (the pglite-engine.test.ts pattern), via a shared probeEmbeddingDim helper. Verified passing at a forced 1280-d column. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> | 5 months ago |
| Files | Last commit | Last update |
|---|---|---|
| 6 months ago | ||
| 5 months ago | ||
| 5 months ago |