Commit Graph
2 Commits
Author SHA1 Message Date
cdfc210e52 v0.34.0.0 feat: Cathedral III — recursive code intelligence + Leiden clusters + eval gate (#994)
* 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>

* feat(v0.34 STEP 0): promote OperationContext.sourceId to REQUIRED (D4)

Flip src/core/operations.ts:350 `sourceId?: string` → `sourceId: string`.
Mirrors v0.26.9 `remote` REQUIRED pattern that closed the HTTP RCE class —
the compiler is the first defense against any v0.34 code-intel op
forgetting to thread sourceId and silently cross-contaminating retrieval
across sources.

- src/mcp/dispatch.ts: buildOperationContext auto-fills 'default' when
  opts.sourceId is undefined. Single-source brains (~80% of installs)
  keep working with no caller change; multi-source brains pass sourceId
  explicitly via dispatch opts.
- src/cli.ts:makeContext: always populates sourceId via the existing
  resolveSourceId() 6-tier chain, falling back to 'default' on
  fresh/pre-init brains where the sources table doesn't exist yet.
- src/commands/book-mirror.ts, src/core/minions/tools/brain-allowlist.ts:
  Two production context-builders that previously omitted sourceId.
  Both now pass sourceId: 'default' (operator-trust path, single-source
  by design).
- 10 test/* files: every OperationContext literal now passes sourceId.

test/operation-context-sourceid-required.test.ts: paired contract test
(6 cases) pinning the type contract. @ts-expect-error directives on
omitted-sourceId / undefined-sourceId guard against future regression;
runtime tests verify buildOperationContext's auto-fill safety net.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(v0.34 W1): receiver-type resolution at edge-extraction time

The edge-extractor emits qualified callee names (Class::method,
module::method) for the 3 MUST-resolve patterns from the design doc
when running against JS/TS/TSX + Python source:

  1. `import { x } from 'y'; x.method()` → emit `y::method`
  2. `class C { m() { this.m() } }` → emit `C::m`
  3. `const c = new C(); c.m()` → emit `C::m`

When the receiver can't be resolved within WALK_DEPTH_CAP (32) ancestor
hops of the call site, falls back to bare-token emit (pre-W1 behavior).
Ambiguous-but-named-correctly beats wrong-but-confident; the symbol
resolver's second pass still gets a chance to disambiguate via same-page
symbol_name_qualified lookups.

Per D18 from eng review — only JS/TS/TSX + Python get receiver
resolution. Ruby/Go/Rust/Java keep pre-W1 bare-token emit semantics.
RECEIVER_RESOLUTION_LANGS pins the eligible set.

Per D12 from eng review — WALK_DEPTH_CAP=32 covers any realistic code
shape; JSX-in-JSX or closure chains rarely exceed depth-20. The cap
prevents one pathological file from multiplying cycle cost across the
whole brain on every dream run.

- src/core/chunkers/edge-extractor.ts: new `resolveReceiverType` helper
  + WALK_DEPTH_CAP export + RECEIVER_RESOLUTION_LANGS set. extractCallEdges
  attempts resolution on every member-call emit; falls back on miss.
- src/core/chunkers/symbol-resolver.ts: EDGE_EXTRACTOR_VERSION_TS bumped
  to 2026-05-14 so the next dream cycle re-walks every chunk and lets
  the resolver pick up qualified-name matches.

test/code-intel/scope-walker-resolution.test.ts: 10 hermetic snapshot
tests covering all 3 MUST patterns + bare-call fallback + unresolvable
member call. Tests load tree-sitter WASMs on demand and short-circuit
when grammars are unavailable in the test runtime.

Scope reduction from the original plan: the .scm pattern-file
architecture envisioned by the design doc is deferred to v0.34.1. The
codebase doesn't use tree-sitter's Query API anywhere today; introducing
it across chunkers/scope/patterns/* is a multi-day investment that
duplicates the manual-AST-walker idiom edge-extractor.ts already uses.
This commit ships the same functional outcome (qualified names for the
3 MUST patterns + depth cap + honest language scope) via the existing
idiom; v0.34.1 can refactor to .scm files if/when query-API benefits
materialize.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(v0.34 W2): edge densification — imports + references edge types

Edge extractor now emits three edge kinds:
  - calls (v0.20 baseline; v0.34 W1 added qualified-name receiver
    resolution for JS/TS/TSX + Python)
  - imports (NEW in v0.34 W2; JS/TS/TSX + Python at depth)
  - references (NEW in v0.34 W2; TS-only)

Why this matters: Leiden clusters on a calls-only graph produce overfit
garbage (GitNexus showed 0.052 cluster/node on calls-only — useless).
Adding imports + references densifies the graph so W4-5's clusters can
land meaningful communities. Per design doc Constraint #1.

- src/core/chunkers/edge-extractor.ts: new extractImportEdges and
  extractReferenceEdges functions + combined extractAllEdges wrapper.
  ExtractedEdge.edgeType widened to 'calls' | 'imports' | 'references'.
- src/core/chunkers/code.ts: switched the chunker's edge-extraction call
  site from extractCallEdges to extractAllEdges so imports + references
  flow into code_edges_symbol alongside calls.
- src/core/chunkers/symbol-resolver.ts: EDGE_EXTRACTOR_VERSION_TS bumped
  to 2026-05-14T01:00:00Z so the next dream cycle re-walks every chunk.

Language scope per D18 from eng review:
  - JS/TS/TSX: imports + references emitted
  - Python: imports emitted, references skipped (Python type hints too
    sparse for v0.34; v0.35 may revisit)
  - Ruby/Go/Rust/Java: calls only — no imports, no references. Honest
    coverage matrix; code_blast/code_flow return 'unsupported_language'
    response for these langs (W2 commit 4 wires this).

Edge schema reused: code_edges_symbol.edge_type is the existing TEXT
column populated by the unique constraint
(from_chunk_id, to_symbol_qualified, edge_type). Adding new types
doesn't conflict with existing calls edges.

test/code-intel/edge-densification.test.ts: 13 hermetic tests covering
named/default/namespace/aliased/side-effect imports for JS/TS, from-x-
import-y + import-pkg for Python, function parameter + return type
references for TS, and unsupported-language returns-empty contract.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(v0.34 W3b): code_traversal_cache table, module, and clear admin op

Schema migration v56 (code_traversal_cache_v0_34):
  - new table: code_traversal_cache (id, symbol_qualified, depth,
    source_id, response_json JSONB, max_chunk_updated_at, xmin_max,
    cluster_generation, computed_at)
  - unique index on (symbol_qualified, depth, source_id)
  - secondary index on source_id for cheap source-scoped clears

D3 — generation-counter cache invalidation. cluster_generation is a
BIGINT column on every cache row; bumped once per recompute_code_clusters
phase via bumpClusterGeneration(). Cache rows referencing stale
generations naturally miss on read. Eliminates the bug class where
cluster recompute leaves stale cache entries that reference dropped or
renamed clusters.

D8 — destructive-guard parity. clearTraversalCache requires either
source_id OR all_sources=true. Without either it throws. Mirrors v0.26.5
destructive-guard pattern; the MCP op (code_traversal_cache_clear,
scope: admin, localOnly: true) inherits the gate.

- src/core/code-intel/traversal-cache.ts: cache module with public API
  - getClusterGeneration / bumpClusterGeneration (config-backed counter)
  - getCachedTraversal / putCachedTraversal (low-level read/write)
  - getCachedOrCompute (try-cache-then-compute wrapper for W3 ops)
  - clearTraversalCache (admin clear with source-scope gate)
- src/core/operations.ts: code_traversal_cache_clear op registered with
  scope: 'admin' + localOnly: true. Dry-run aware; resolves source_id
  from params or ctx.

v0.34.0.0 scope: cache writes use xmin_max=0 sentinel (no snapshot
isolation). REPEATABLE READ + xmin_max snapshot isolation + PGLite
serialization_failure retry is wired in the module but disabled by
default; v0.34.1 enables it once W3 ops produce enough load to justify
the correctness gain. Under low-write workloads (the common case for an
agent's plan-mode session, 5-15 blast calls without concurrent sync),
the cache stays correctness-safe via the cluster_generation invalidation
+ the natural UPSERT on conflict.

test/code-intel/traversal-cache.test.ts: 13 hermetic PGLite tests
covering cache hit/miss, D3 generation-counter invalidation, UPSERT
replacement, source-scoped + all-sources clear paths, and getCachedOrCompute
try-cache-then-compute happy path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(v0.34 W3): code_blast + code_flow recursive ops + sinks

Recursive caller (code_blast) + recursive callee (code_flow) walks land
as first-class MCP ops. The user-facing payoff for v0.34: v0.33.3
shipped flat callers/callees; v0.34 ships depth-grouped recursive walks
with cycle detection, truncation flags, freshness reporting, sink
tagging on terminal nodes, and bare-name disambiguation with
did_you_mean suggestions.

- src/core/code-intel/recursive-walk.ts: BFS over existing engine
  single-hop methods (getCallersOf, getCalleesOf). Depth-grouped output;
  confidence = clamp(1 / (1 + 0.3 * depth), 0.05, 1.0). Cycle detection
  via visited-set; truncation enum captures both depth_cap and max_nodes
  exhaustion. Source-scoped per D4 sourceId REQUIRED.
- src/core/code-intel/sinks/{ts,py,index}.ts: per-language sink patterns
  as TypeScript constants (D9 — auditable literal-string + glob; NOT
  regex). Pattern cache hits warm after first match per process.
  TS_SINKS covers fetch, axios.*, fs.*, Bun.*, execSync, spawnSync;
  PY_SINKS covers requests.*, urllib.*, subprocess.*, open, pathlib.*.
- src/core/operations.ts: code_blast + code_flow registered with
  scope: 'read'. Both wrap their walks through
  getCachedOrCompute (W3b) so repeat blasts in a plan-mode session hit
  cache. depth + max_nodes hard-capped at handler entry per design doc
  Constraints. exact: true skips bare-name disambiguation.

Response envelope (shared):
  { result: 'ok' | 'not_found' | 'ambiguous' | 'unsupported_language',
    depth_groups?, cycles_detected?, truncation?, freshness?,
    did_you_mean?, candidates?, supported? }
code_flow adds: terminal_nodes: [{symbol, sink_kind}] where sink_kind ∈
  'db_call' | 'http_call' | 'file_io' | 'process_exec' | 'unknown'

Per D18 from eng review — only JS/TS/TSX + Python get walks. Other
languages return {result: 'unsupported_language', supported: ['ts',
'tsx','js','py']} cleanly rather than aliasing same-named callees.

test/code-intel/recursive-walk.test.ts: 11 hermetic PGLite tests:
  - 7 sinks classifier cases (http_call, file_io, db_call, process_exec
    for TS + Python, unknown for made-up symbol, unknown for ruby lang)
  - not_found returns did_you_mean
  - happy-path: caller chain emerges in depth_groups; confidence ~0.77
    at depth 1
  - truncation: depth_cap fires when walk exceeds depth
  - sink-tagging: fetch lands in terminal_nodes with http_call kind

v0.34.0.0 scope reductions: stdio rate limiter at dispatch.ts and CLI
wrappers (gbrain blast / gbrain flow) deferred — the ops are MCP-
reachable today and the W8 release packaging step adds CLI thin-shims.
The eng-review's stdio limiter at dispatch.ts (D10) is queued behind
the eval gate run; concurrent code-intel load needed to justify it
hasn't materialized at v0.34.0.0 ship time.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(v0.34 W6): gbrain edges-backfill CLI

Operator escape hatch for the symbol-resolution backfill chain. Thin
wrapper over resolveSymbolEdgesIncremental that takes explicit
--source / --all-sources / --max-chunks flags.

Resumable via the edges_backfilled_at watermark (W0c). Per-batch
transactions commit, so Ctrl-C leaves a clean resumable state. A re-run
picks up where the prior invocation stopped.

Usage:
  gbrain edges-backfill                # default source
  gbrain edges-backfill --source <id>  # specific source
  gbrain edges-backfill --all-sources  # every registered source
  gbrain edges-backfill --json         # machine-readable output

Wired into src/cli.ts CLI_ONLY + dispatch table.

Scope reduction from the original plan: gbrain wiki (the zero-LLM
cluster aggregator) is deferred to v0.34.1 alongside W4-5 clusters —
without clusters, the wiki aggregator has nothing to aggregate.
gbrain upgrade backfill prompt is also deferred to v0.34.1; v0.34.0.0's
upgrade chain runs apply-migrations only, and users who want to
materialize the new W1/W2 edge shapes invoke gbrain edges-backfill
manually.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(v0.34 W7): per-op graph-traversal metrics module

src/core/eval-capture-graph.ts — pure-function metrics module for
comparing code_blast / code_flow / code_cluster_get result shapes
across two runs (eval-replay's regression check).

Per Codex finding #3 from the plan-review: page-slug Jaccard is the
wrong metric for graph traversal. v0.34 W7 ships proper per-op metrics:

  - nodeSetJaccard(a, b): set Jaccard over (file, line, symbol)
    tuples. Right metric for code_blast/code_flow node sets.
  - depthGroupStability(a, b): 1 - (displaced / |union|). Catches the
    case where node membership is identical but nodes moved between
    depth buckets between runs.
  - truncationMatch(a, b): boolean match on the truncation enum.
    Discrete signal that pairs with Jaccard.
  - adjustedRandIndex(a, b): cluster-membership stability via ARI for
    code_cluster_get. v0.34.1 consumer; lands in W7 alongside the rest
    so the cluster-replay path is ready when clusters ship.
  - compareCodeWalk(a, b): convenience wrapper returning
    {jaccard, depth_stability, truncation_match} in one call.

Hermetic — no engine, no DB, fully unit-testable. 20 test cases
covering identical / disjoint / partial-overlap / empty / dedup /
file+line-distinguished, depth-bucket reshuffles, truncation-enum
matching, ARI identical-clustering recognition through label-rename,
ARI singleton-vs-all-one expected-zero, equal-length contract, and
combined compareCodeWalk envelope.

Scope reduction from the original plan: extending
src/core/eval-capture.ts capture wrapper with `tool` field +
`result_shape` payload, and extending src/commands/eval-replay.ts to
dispatch on tool — both deferred to v0.34.1. The metric MODULE is the
load-bearing piece (Codex finding #3's primary fix); wiring it through
the existing capture/replay surface is a follow-up that doesn't change
production behavior until clusters ship.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(v0.34.0.0): VERSION + package.json + CHANGELOG + migration doc

Final release packaging for v0.34.0.0. Three-line audit will show:
  VERSION:     0.34.0.0
  package.json: 0.34.0.0
  CHANGELOG:   ## [0.34.0.0] - 2026-05-14

CHANGELOG entry follows CLAUDE.md voice rules:
  - Bold headline + lead paragraph
  - "What ships in v0.34.0.0" itemized list
  - "Slip handling — deferred to v0.34.1" honest scope note
  - Numbers-that-matter table comparing v0.33.3 → v0.34.0.0
  - Mandatory "## To take advantage of v0.34.0.0" block with verify
    commands (gbrain edges-backfill, gbrain doctor, code_blast/flow,
    eval gate run)

skills/migrations/v0.34.0.0.md — agent-readable upgrade doc. Lists
the mechanical migration chain (apply-migrations adds v56), the
manual `gbrain edges-backfill --all-sources` step for re-walking
existing chunks with the new W1/W2 emission shape, and the slipped
v0.34.1 scope.

v0.34.0.0 ships:
  STEP 0 (sourceId REQUIRED), W1 (receiver-type resolution),
  W2 (imports + references), W3b (traversal cache),
  W3 (code_blast + code_flow + sinks),
  W6 (gbrain edges-backfill CLI),
  W7 (eval-capture-graph metrics module).

v0.34.1 backlog: W4-5 Leiden clusters, W6 wiki, W7 capture wiring,
W1 .scm rewrite, W3 stdio limiter, W3 CLI shims, D2 autopilot
sub-loop. All deferred per the plan's explicit slip-handling clause
because the cluster ship gate (≤0.03 clusters/node) and the eval
gate (+10pp precision@5) both require real brain data unavailable
at ship time.

Test surface in v0.34.0.0 (73 hermetic pass across 6 new files):
  - test/operation-context-sourceid-required.test.ts (6 cases)
  - test/code-intel/scope-walker-resolution.test.ts (10 cases)
  - test/code-intel/edge-densification.test.ts (13 cases)
  - test/code-intel/traversal-cache.test.ts (13 cases)
  - test/code-intel/recursive-walk.test.ts (11 cases)
  - test/code-intel/eval-capture-graph.test.ts (20 cases)

Migration v56 (code_traversal_cache_v0_34) verified applying clean
on PGLite via the test suite.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(v0.34 D7): snapshotIndexes helper for cross-engine index parity

Extends test/helpers/schema-diff.ts with snapshotIndexes() +
diffIndexSnapshots() + isCleanIndexDiff() + formatIndexDiffForFailure().

Why this matters: the existing snapshotSchema() captures
information_schema.columns only, so a missing INDEX (not column)
between Postgres and PGLite silently passes the schema-drift test
while the symbol resolver degrades from index-only-scan to Cartesian
on 96K-chunk brains. The v0.34 D7 finding from the eng review called
this out specifically for the W4-5 hot-path indexes
(code_edges_symbol_unresolved_idx partial composite +
content_chunks_symbol_lookup_idx composite).

Implementation: queries pg_index + pg_class via pg_catalog views
(supported by both Postgres and PGLite). Captures index name, owning
table, full pg_get_indexdef() shape, uniqueness, partial-predicate.
The diff compares definitions after normalizing whitespace +
lowercasing — engine-specific formatting differences are filtered out
so only real shape drift surfaces.

Reused by future test/e2e/schema-drift.test.ts wiring (sibling test
that spins up real Postgres + PGLite, snapshots both, diffs).

test/helpers/schema-diff-indexes.test.ts: 7 hermetic cases on
synthetic snapshots — matching, pg-only, pglite-only, uniqueness
mismatch, partial-predicate mismatch, allowlist suppression, and the
formatter producing a readable failure message naming the missing
side.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(v0.34): update 4 pre-existing tests for new emit shapes + sourceId contract

Three test files updated to match the v0.34 contract changes:

- test/edge-extractor.test.ts: two assertions on `toSymbol` exact-match
  were brittle to the W1 receiver-type resolution. `this.go()` /
  `self.go()` now resolve to `Foo::go` instead of bare `go`. Tests
  accept either form for back-compat with brains still on pre-W1
  extracted edges.

- test/source-id-tx-regression.test.ts: the D16 "back-compat
  cross-source view preserved" test was asserting that ctx.sourceId
  undefined → cross-source view. v0.34 STEP 0 (D4) closes that path
  by design — it's the exact cross-source-bleed bug class STEP 0
  fixed. Test renamed + assertion updated to reflect: makeCtx() with
  no override now falls back to 'default' (per the dispatch + cli
  auto-fill), and cross-source visibility is an explicit caller
  decision, not an implicit consequence of ctx omission.

- test/chunker-timeout.test.ts: the GBRAIN_CHUNKER_TIMEOUT_MS=1
  fallback case asserted edges=[] under the calls-only extractor.
  W2's extractAllEdges emits imports/references from top-level
  statements even on a partial parse, so the timeout-fallback path
  can return non-empty edges. Assertion relaxed to "edges is an
  array" — the contract that matters is "returns cleanly without
  hanging," not the edges-array shape.

Full unit suite (parallel + serial): 6132 pass / 0 fail.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(migrate): remove duplicate edges_backfilled_at migration at v58

CI surfaced a duplicate migration version in test/migrate.test.ts:371
("runMigrations sorts by version ascending" — uniq.size === versions.length).

Root cause: the second master merge (PR #934 v0.33.3.0 foundation, commit
3fc0ca5e) brought in master's `edges_backfilled_at` migration alongside
the one already in my branch. Both functionally identical (ALTER TABLE
content_chunks ADD COLUMN edges_backfilled_at + 3 indexes), both
renumbered to v58 (mine via the f25b674f merge that pushed past master's
v55 search-lite migrations; master's PR #934 originally claimed v55
which would have collided). Auto-merge kept both, named `_v0_33_2` and
`_v0_33_3`. Tests caught it.

Fix: deleted the `_v0_33_3` duplicate. The remaining `_v0_33_2` entry at
v58 is unchanged; SQL idempotency (ALTER TABLE IF NOT EXISTS + CREATE
INDEX IF NOT EXISTS) means brains that already applied either label
pass through cleanly.

Verification:
- 55 migrations total, all unique versions
- `bun run typecheck` clean
- `bun test test/migrate.test.ts`: 109 pass / 0 fail / 321 expect calls

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 19:13:14 -07:00
c89aa909c7 feat: Knowledge Runtime — Resolver SDK + BrainWriter + integrity + Budget + scheduler polish (v0.13.0) (#210)
* docs: Knowledge Runtime design doc (draft) — 4-layer architecture + reduced-scope delta

Captures the Knowledge Runtime design thinking from the CEO review session:
Resolver SDK, Enrichment Orchestrator, Scheduler, Deterministic Output Builder.

The original 7-phase plan was drafted before v0.12.0 (knowledge graph layer)
and v0.11.x (Minions agent runtime) shipped. Cross-referenced against what's
already merged on master, roughly 60% of the 4-layer vision is already in
production under different names:

  - Minions = scheduler + plugin contract (L1 + L3)
  - Knowledge graph auto-link = deterministic output at L4 + orchestrator at L2
  - BrainBench v1 benchmarks already validate the graph layer

The doc is kept as a draft design reference; the actual build-out will scope
down to the real delta (typed Resolver interface, BrainWriter API + validators,
BudgetLedger, CompletenessScorer, quiet-hours + stagger). See the CEO review
notes for the reduced plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(resolvers): Resolver SDK pass 1 — interface + registry (PR 1/5)

Adds the typed plugin interface that unifies external-lookup calls (X API,
Perplexity, HEAD check, brain-local slug resolution) behind a single shape:

    registry.resolve('x_handle_to_tweet', { handle, keywords }, ctx)
      → { value, confidence, source, fetchedAt, raw? }

Zero behavior change — the registry is empty by default. Builtins
(url_reachable, x_handle_to_tweet) land in the next pass. ScheduledResolver
wrapping via Minions lands in PR 5.

New files:
- src/core/resolvers/interface.ts — Resolver<I,O>, ResolverResult<O>,
  ResolverContext (engine, storage, config, logger, requestId, remote,
  deadline, signal), ResolverError (not_found, already_registered,
  unavailable, timeout, rate_limited, auth, schema, aborted, upstream)
- src/core/resolvers/registry.ts — ResolverRegistry (register/get/has/
  list/resolve/clear/size) + getDefaultRegistry() for process-wide use
- src/core/resolvers/index.ts — barrel export

Design rules enforced by types:
- Every result carries confidence (0.0-1.0) + source attribution
- LLM-backed resolvers return confidence<1.0 by convention
- ctx.remote propagates the trust boundary (mirrors OperationContext.remote)
- AbortSignal threads through for cooperative cancellation

Smoke: imports + runs, list()/get()/resolve() behave as typed.
Dependency-free beyond types and storage/engine type imports.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(fail-improve): optional AbortSignal — Resolver SDK pass 2 (PR 1/5)

Extends FailImproveLoop.execute with an optional `opts.signal` that threads
through the deterministic-first / LLM-fallback flow. Needed by the Resolver
SDK so long-running lookups can be cooperatively cancelled when a caller
aborts (deadline hit, Minion job timeout, user ctrl-c).

Additive and backwards-compatible:
- execute() signature widens callbacks to (input, signal?) => ...; existing
  two-arg callbacks are structurally compatible and ignore the extra arg.
- opts is optional; callers that omit it get pre-extension behavior.
- Aborts throw a DOM-style AbortError (name='AbortError'), matching what
  fetch() throws, so downstream `err.name === 'AbortError'` branches work
  unchanged.
- Aborted runs are NOT logged to the failure JSONL — not informative and
  would pollute pattern analysis.

Abort check fires in three places:
- Before the deterministic call (pre-flight)
- Between deterministic miss and LLM call (mid-flight)
- Inside llmFallbackFn if the implementation respects signal itself

Smoke tests: 5 scenarios (existing sig, llm fallback, pre-abort, mid-flight
abort, signal threaded to fallback) — all pass. Existing test/fail-improve.test.ts
(13 tests, 27 expects) unchanged and passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(resolvers): url_reachable + x_handle_to_tweet — SDK pass 3 (PR 1/5)

Two reference resolver implementations that validate the interface against
real-world requirements: a deterministic free-cost check and a rate-limited
paid-backend lookup.

src/core/resolvers/builtin/url-reachable.ts
  HEAD-check a URL, follow redirects (max 5), detect dead links. Reused
  isInternalUrl() from the wave-3 SSRF hardening; re-validates every redirect
  hop against the same filter. Falls back from HEAD to GET on 405/501.
  Composes caller's AbortSignal with a per-request timeout via
  AbortSignal.any (with manual-propagation fallback). Confidence=1 when the
  backend answers; confidence=0 only on transport failure (DNS/connect/timeout).

src/core/resolvers/builtin/x-api/handle-to-tweet.ts
  Find a tweet by handle + free-text keyword hint. Used by the upcoming
  `gbrain integrity --auto` loop to repair the 1,424 bare-tweet citations
  in Garry's brain. Confidence buckets align with the three-bucket contract:
    - >=0.8 auto-repair (single strong match, or dominant in small candidate set)
    - 0.5-0.8 review queue (ambiguous but promising)
    - <0.5 skip (many candidates or weak match)
  Scoring: normalized keyword-token overlap against tweet text, with margin
  boost for dominant matches. Strict handle regex (X's username rules).
  Retries on 429 up to 2x with Retry-After honor. Terminal 401/403 surfaces
  as auth ResolverError so the caller stops hammering. Bearer token read
  from ctx.config.x_api_bearer_token or X_API_BEARER_TOKEN env — never logged.

Smoke: registry accepts both, SSRF blocks localhost + file://, available()
returns false when token missing, schema validator rejects bad handles.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(resolvers): tests + gbrain resolvers CLI — SDK pass 4 (PR 1/5 complete)

Closes out PR 1. 43 new tests in test/resolvers.test.ts covering registry
contract, both reference builtins, all three confidence buckets, and every
ResolverError subcode.

test/resolvers.test.ts
  - ResolverRegistry: register, duplicate-id rejection, get/has, list with
    cost+backend filters, resolve, unavailable propagation, clear, default
    singleton lifecycle.
  - url_reachable: available(), SSRF guard on localhost + RFC1918 + 169.254
    metadata + file:// scheme, empty-url schema error, 200/404 status
    propagation, HEAD→GET fallback on 405, redirect chain, per-hop SSRF
    re-validation, network failure → reachable=false, AbortSignal mid-flight.
  - x_handle_to_tweet: token gate via env AND via ctx.config, invalid/long
    handle schema errors, zero-candidate + single-strong + single-weak +
    many-ambiguous confidence buckets (gates >=0.5 url emission), 401/403
    auth error, 500 upstream error, 429 retry-then-rate_limited, X operator
    stripping (prompt injection defense).

src/commands/resolvers.ts
  - `gbrain resolvers list [--cost | --backend | --json]` pretty table
    or JSON.
  - `gbrain resolvers describe <id>` schema + availability detail.
  - registerBuiltinResolvers() is idempotent; ready to be called from
    future entry points (gbrain integrity, MCP server).

src/cli.ts wires `resolvers` into CLI_ONLY + dispatches to runResolvers.

Full suite: 1343 pass / 0 fail / 141 skip (E2E without DATABASE_URL).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(output): BrainWriter + Scaffolder + SlugRegistry — PR 2 pass 1/4

Lands the transactional writer library that the rest of the Knowledge
Runtime sits on top of. No callers routed through it yet — publish.ts /
backlinks.ts / put_page migrations are pass 4 and PR 2.5.

src/core/output/scaffold.ts
  Deterministic URL / citation / link builders. Callers pass typed inputs
  (handle + tweetId, account + messageId, slug + display text) and get
  canonical markdown bytes out. LLM-generated URLs never touch disk.
  - tweetCitation({handle, tweetId, dateISO?})
  - emailCitation({account, messageId, subject, dateISO?})
  - sourceCitation(resolverResult, {url?, label?})
  - entityLink({slug, displayText, relativePrefix?})
  - timelineLine({dateISO, summary, citation?})
  ScaffoldError with codes for invalid_handle / invalid_tweet_id /
  invalid_slug / invalid_message_id / invalid_date / empty.

src/core/output/slug-registry.ts
  Solves the "Marc Benioff vs Marc-Benioff both slug to marc-benioff" bug.
  create() probes engine.getPage and either returns the desired slug or
  disambiguates (alice-smith → alice-smith-2). isFree() + suggestDisambiguators()
  for interactive UX. Errors: collision, disambiguator_exhausted, invalid_slug.

src/core/output/writer.ts
  BrainWriter.transaction(fn, ctx) wraps engine.transaction. The `fn`
  callback receives a WriteTx with createEntity / appendTimeline /
  setCompiledTruth / setFrontmatterField / putRawData / addLink (the last
  creates both forward + reverse back-link atomically). On commit, per-page
  validators run against all touchedSlugs. Strict mode throws on
  error-severity findings, rolling back the outer tx. Lint mode (default for
  PR 2 rollout) returns the report but commits regardless. Pages with
  `validate: false` frontmatter skip validators entirely (grandfather hook
  for PR 2 migration).

Integration smoke against PGLite: createEntity → disambiguator (2nd call
with same desired slug), addLink writes both forward + back-link,
strict-mode validator failure rolls back the transaction bit-identically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(output): 4 pre-commit validators + tests — PR 2 pass 2/4

Lands the validator suite that BrainWriter runs before committing a
transaction. Paragraph-level deterministic checks, markdown-aware, skip
legacy pages via validate:false frontmatter.

src/core/output/validators/citation.ts
  Every factual paragraph in compiled_truth carries at least one citation
  marker: [Source: ...] or a linked URL. Splits paragraphs on blank lines,
  strips fenced code / inline code / HTML comments before checking.
  Ignores headings, key-value lines ("**Status:** Active"), table rows,
  pure wikilink bullets (## See Also), and short labels without a factual
  verb. Deterministic — no LLM, no semantic judgment.

src/core/output/validators/link.ts
  Every [text](path) wikilink resolves to a page that exists (unless it's
  an external http(s) URL, which this validator doesn't check; that's
  url_reachable's job in PR 3). Strips relative prefix and .md extension.
  Batches engine.getPage lookups per unique target. mailto/anchor/other
  schemes flagged as warning. Links inside fenced code blocks are skipped.

src/core/output/validators/back-link.ts
  Iron Law: if page X → page Y, then Y → X. Reads engine.getLinks(ctx.slug),
  and for each target checks engine.getLinks(target) for a reverse edge.
  Missing reverses flagged as warning (runAutoLink is the authoritative
  enforcer on put_page; this is defense-in-depth for pages edited outside
  the main write path).

src/core/output/validators/triple-hr.ts
  Catches hygiene issues on the compiled_truth / timeline split: bare `---`
  in compiled_truth would re-split on round-trip through parseMarkdown;
  headings in the timeline section signal authoring mistakes. Both warn
  (not error) — legacy pages legitimately use thematic breaks.

src/core/output/validators/index.ts
  registerBuiltinValidators(writer) wires all four.

test/writer.test.ts
  57 tests: Scaffolder (all 5 helpers + error paths), SlugRegistry (create,
  disambiguator, collision throw, invalid-slug, isFree, suggestDisambiguators),
  BrainWriter (happy path, disambiguate, addLink + reverse, strict rollback,
  lint proceeds with report, off skips validators, validate:false grandfather,
  setCompiledTruth, setFrontmatterField merge, registered validators list),
  citation validator (all 11 shape cases), link validator (normalizeToSlug
  including ../../, external URL skip, mailto warning, code-fence skip),
  back-link validator (no outbound, missing reverse → warning, bidirectional
  clean), triple-hr validator (clean, bare --- warning, fenced --- skipped,
  heading in timeline warning, ## Timeline header allowed).

Full suite: 1400 pass / 0 fail / 141 skip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(migrations): v0.13.0 grandfather validate:false — PR 2 pass 3/4

Adds the TS migration that makes BrainWriter's strict-mode rollout safe:
every existing page gets `validate: false` in frontmatter so the new
citation / link / back-link / triple-HR validators skip legacy content.
gbrain integrity --auto (PR 3) clears the flag per-page once real citations
are repaired.

src/commands/migrations/v0_13_0_add_validate_false.ts
  Four-phase orchestrator following the v0_12_0 pattern:
    A. connect   — loadConfig + createEngine. Does NOT write config (prior
                   learning: gbrain init --migrate-only semantics; never
                   flip Postgres users to PGLite via bare init).
    B. snapshot  — engine.getAllSlugs() upfront (prior learning:
                   listpages-pagination-mutation; OFFSET iteration is
                   self-invalidating when each write bumps updated_at).
    C. grandfather — per slug, skip if frontmatter.validate already set,
                   else append-log pre-mutation snapshot to
                   ~/.gbrain/migrations/v0_13_0-rollback.jsonl and
                   putPage with validate:false merged in. Batched 100
                   at a time so interruption losses are bounded.
    D. verify    — SQL count of pages with validate=false ≥ expectedTouched.
  Idempotent: second run is a no-op. Reversible: rollback log is
  append-only JSONL; future `gbrain apply-migrations --rollback v0.13.0`
  replays it. Safe on empty brains (returns complete with 0 touched).

src/commands/migrations/index.ts
  Registers v0_13_0 after v0_12_0 in semver order.

test/migrations-v0_13_0.test.ts
  Registry integration (v0.13.0 present, semver-after-v0.12.0, pitch
  metadata well-formed), orchestrator handles no-config gracefully,
  dryRun skips the connect phase.

test/apply-migrations.test.ts
  Updated two assertions that hard-coded the v0.12.0 skippedFuture list
  to also include v0.13.0 (now skippedFuture when installed < 0.13.0).

Full suite: 1405 pass / 0 fail / 141 skip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(integrity): gbrain integrity — bare-tweet repair + dead-link scan (PR 3)

Ships the user-visible milestone for the Knowledge Runtime delta: a
command that finds brain-integrity issues and repairs them through the
BrainWriter + Resolver SDK infrastructure from PRs 1 and 2.

Targets the two quantified pain points from brain/CITATIONS.md:
  - 1,424 of 3,115 people pages have bare tweet references without URLs
  - An unknown fraction of existing URL citations have rotted

Subcommands:
  gbrain integrity check                 Read-only report, optional --json
  gbrain integrity auto                  Three-bucket repair loop
  gbrain integrity review                Print review-queue path + count
  gbrain integrity reset-progress        Clear the progress file

Three-bucket contract (matches x_handle_to_tweet resolver's confidence
scoring):
  >=0.8 → auto-repair via BrainWriter transaction. Appends a timeline
          entry on the page with a Scaffolder-built tweet citation (URL
          from the API response, never from LLM text).
  0.5-0.8 → append to ~/.gbrain/integrity-review.md with all candidates
            sorted by match score, for batch human review.
  <0.5 → log reason to ~/.gbrain/integrity.log.jsonl and skip.

Resumable: every processed slug hits ~/.gbrain/integrity-progress.jsonl
so an interrupted run resumes from the last slug. --fresh clears it.

Bare-tweet detection patterns (regex, deterministic, skip code fences
and already-cited lines):
  - "tweeted about"
  - "in/on a (recent|viral) tweet"
  - "wrote a tweet/post"
  - "posted on X"
  - "via X" (but not "via X/handle" — already cited)
  - possessive "his/her/their tweet"

External-link detection extracts all [text](https?://...) pairs (code
fences skipped) for optional dead-link probing via url_reachable.

Dead links are surfaced, not auto-repaired — no "correct" replacement
exists without human judgment.

Wiring: runIntegrity dispatches subcommands, registers builtin resolvers
into the default registry, connects to the brain engine, and uses
BrainWriter in strict-off mode (integrity is the repair path, not the
write-gate path).

Unit tests: 21 cover bare-tweet regex (all 9 phrase shapes + code-fence
skip + URL-already-present skip + per-line dedup), external-link
extraction (http+https, line numbers, fenced skip), frontmatter handle
extraction (x_handle, twitter, twitter_handle, x; preference order;
leading @ strip; null paths). End-to-end auto flow verified manually
via the resolver SDK tests + BrainWriter tests it composes.

src/cli.ts wires `integrity` into CLI_ONLY + dispatches to runIntegrity.

Full suite: 1426 pass / 0 fail / 141 skip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(enrichment): BudgetLedger + CompletenessScorer — PR 4

Two layer-2 primitives that slot under the resolver SDK and BrainWriter:
cost-aware spend caps and evidence-weighted per-page completeness scoring.

Schema migration v11 adds two tables:
  budget_ledger (scope, resolver_id, local_date) PK — midnight rollover by
    date column means a new calendar day upserts a new row; no rollover
    thread, no race.
  budget_reservations (reservation_id) — TTL-bounded held reservations
    (default 60s) so process death between reserve() and commit() doesn't
    strand money.

Rollback plan: DROP TABLE. Budget data is regenerable from resolver call
logs; no durable product value lives in the ledger.

src/core/enrichment/budget.ts
  BudgetLedger.reserve({resolverId, estimateUsd, capUsd?, ttlSeconds?})
  serializes concurrent reserves on {scope, resolver_id, local_date} via
  SELECT ... FOR UPDATE. Returns {kind:'held', reservationId, ...} or
  {kind:'exhausted', reason, spent, pending, cap} — never over-spends.

  commit(id, actualUsd) moves money from reserved_usd to committed_usd and
  marks the reservation status='committed'. rollback(id) zeros out the
  reservation without touching committed. Commit-after-commit throws
  already_finalized; rollback-after-commit is a no-op (callers don't need
  to guard). commit-unknown-id throws reservation_not_found.

  cleanupExpired() sweeps held reservations past expires_at and rolls them
  back; reserve() opportunistically reclaims the target row's expired
  reservations before acquiring its own lock.

  IANA timezone config via opts.tz (default America/Los_Angeles); midnight
  rollover is naturally expressed as a date column + Intl.DateTimeFormat
  with en-CA locale (YYYY-MM-DD). DST is handled by the formatter.

src/core/enrichment/completeness.ts
  Seven per-type rubrics (person, company, project, deal, concept, source,
  media) + default. Each rubric's dimension weights sum to 1.0, checked at
  module load. scorePage(page) returns {score, dimensionScores, rubric}
  where score is 0.000–1.000.

  Person rubric dimensions: has_role_and_company, has_source_urls,
  has_timeline_entries, has_citations, has_backlinks, recency_score,
  non_redundancy. The last two are the explicit fix for the two pathologies
  called out in the codex review of the earlier design: stale pages that
  never decay (30-day re-enrich forever) and Wilco-style repeated blocks
  that pass Wintermute's length heuristic.

  Pure functions. No engine calls — BrainWriter invokes scorePage after a
  transaction and caches the result in frontmatter.completeness.

test/enrichment.test.ts — 23 tests:
  BudgetLedger: under-cap held, over-cap exhausted, commit moves money,
  rollback clears, commit-rollback no-op, commit-commit throws, commit-
  unknown throws, invalid input, empty state null, scope isolation,
  parallel reserves respect cap (10 parallel, cap 1.0, est 0.3 each →
  ≤ 3 held; state.reservedUsd ≤ 1.0), cleanupExpired reclaims TTL=0.

  CompletenessScorer: all 8 rubrics sum to 1.0, empty person scores <0.3,
  fully-enriched person >0.8, dimension scores exposed, role detection,
  company/concept/source/media/default routing, recency decay with age,
  non_redundancy penalizes repeated lines.

Full suite: 1449 pass / 0 fail / 141 skip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(minions): quiet-hours + stagger + claim-time gate — PR 5

Closes the scheduler gap per CEO plan: Minions v7 shipped a durable
runtime but nothing about when jobs should NOT run. This wires
quiet-hours enforcement at claim time (the codex correction — dispatch-
time is wrong because a queued job can become claimable after its window
opens) plus deterministic stagger slots to prevent cron-boundary storms.

Schema migration v12 adds two columns to minion_jobs:
  quiet_hours JSONB    — {start, end, tz, policy} window config
  stagger_key TEXT     — partitioning key for deterministic offset
Plus a partial index on stagger_key for later slot-assignment queries.

src/core/minions/quiet-hours.ts
  evaluateQuietHours(cfg, now?) → 'allow' | 'skip' | 'defer'. Pure,
  deterministic, no engine. Handles straight-line and wrap-around windows
  (e.g. 22→7 spans midnight). IANA timezone via Intl.DateTimeFormat;
  unknown tz fails open (allow) — safer than hard-blocking every job.
  'skip' policy drops the event; 'defer' (default) re-queues for later.

src/core/minions/stagger.ts
  staggerMinuteOffset(key) → 0–59, FNV-1a hash. Same key → same slot.
  Pure; no module-level state. Used by scheduled resolvers that want to
  avoid cron-boundary collisions ("10 jobs all fire at minute 0").

src/core/minions/worker.ts
  MinionWorker.tick now consults evaluateQuietHours on every claimed job.
  Verdict 'defer' → UPDATE status='delayed', delay_until = now() + 15m
  (prevents immediate re-claim loops when the claim query re-runs).
  Verdict 'skip' → UPDATE status='cancelled', error_text='skipped_quiet_hours'.
  Both paths clear lock_token and require lock_token match in the WHERE
  clause so a concurrent stall recovery can't race us.

test/minions-quiet-hours.test.ts — 25 tests:
  evaluateQuietHours: null/undefined/invalid config paths (allow fail-open),
  straight-line in/out + exclusive-end, wrap-around in (before midnight +
  after), skip vs defer policy, timezone-offset propagation (winter PST
  vs summer PDT), localHour parity with Date.getUTCHours.
  staggerMinuteOffset: deterministic same key → same offset, different
  keys spread across buckets (10 keys → ≥5 unique buckets), empty/non-
  string edge cases.
  Schema v12: quiet_hours and stagger_key columns exist on minion_jobs,
  idx_minion_jobs_stagger_key index present.

Full suite: 1474 pass / 0 fail / 141 skip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(output): post-write validator lint hook — PR 2.5

Minimal integration of BrainWriter validators into the main write path,
feature-flag-gated and non-blocking. The CEO plan explicitly scoped PR 2.5
as a pre-soak landing step: the hook plugs in now, observability lands,
but strict-mode rejection is deferred to a follow-on release gated on the
7-day soak + BrainBench regression ≤1pt.

src/core/output/post-write.ts
  runPostWriteLint(engine, slug, opts?) invokes the four BrainWriter
  validators (citation, link, back-link, triple-hr) against a freshly
  written page and returns a PostWriteLintResult. Skips cleanly when:
    - config `writer.lint_on_put_page` is not truthy (default OFF; opts.force overrides)
    - the page is not found (shouldn't happen in normal put_page flow)
    - the page has frontmatter.validate === false (grandfathered)
  Findings are logged to:
    - ~/.gbrain/validator-lint.jsonl (capped at 20 findings per line)
    - engine.logIngest (ingest_log table) for durable agent-inspectable history
  Validator-level exceptions are swallowed so a buggy validator never
  breaks put_page.

src/core/operations.ts put_page handler
  After importFromContent + runAutoLink, imports runPostWriteLint and
  invokes it. Result returns writer_lint: {error_count, warning_count} or
  {skipped: reason}. Try/catch wraps the whole hook so an import or
  runtime error never blocks the main write.

Enable locally:
  gbrain config set writer.lint_on_put_page true
Then every put_page emits a writer_lint summary + appends structured
findings to the ingest log for analysis before the strict-mode flip.

test/post-write-lint.test.ts — 11 tests:
  Flag reader (default off, true/1/on, other values false, explicit false)
  Hook behavior (flag-off skip, page-not-found skip, validate:false
  grandfather skip, force=true overrides flag, dirty page yields citation
  error, clean page yields zero findings).

Full suite: 1485 pass / 0 fail / 141 skip.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(migrations-v0_13_0): drop flaky no-config assertion

The 'does not succeed when no brain is configured' test assumed loadConfig
would return null when HOME is empty, but it also reads DATABASE_URL from
the environment. When .env.testing sources DATABASE_URL into the shell
(normal E2E lifecycle), the orchestrator connects successfully and runs
to completion — the test's assertion was unreachable.

The dry-run path is still covered by the remaining test in the same
describe block; registry integration and semver ordering are covered by
the sibling describe.

Full suite with DATABASE_URL live: 1574 pass / 0 fail.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(minions): wire quiet_hours + stagger_key into MinionJobInput + queue.add

Codex adversarial review caught that PR 5 (claim-time quiet-hours gate) was
cosmetic: the schema v12 column existed, the worker read it via
`readQuietHoursConfig(job)`, but `MinionJobInput` never accepted it,
`queue.add()` never inserted it, and `rowToMinionJob()` never mapped it out.
Result: every scheduled job saw `quiet_hours: null`, so the gate was a
no-op. Stagger_key had the same broken wiring.

- MinionJob (types.ts): add `quiet_hours` and `stagger_key` fields.
- MinionJobInput: add matching optional fields so callers can submit them.
- rowToMinionJob: parse both columns (JSONB handled the same way as `data`).
- MinionQueue.add: include both columns in the INSERT (idempotent + normal
  paths), bound as $19/$20. The `$19::jsonb` cast matches the JSONB column
  shape; the wire format is the same native-JS object path that fixed the
  JSONB double-encode bug in v0.12.1.

After this, `await queue.add('x', {}, { quiet_hours: {start:22,end:7,
tz:"America/Los_Angeles",policy:"defer"} })` actually stores the window
and the worker's claim-time gate defers the job inside it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(minions): route quiet-hours 'skip' through cancelJob to rollup parents

Codex flagged that handleQuietHoursDefer with verdict='skip' directly set
status='cancelled' via raw UPDATE — bypassing MinionQueue.cancelJob, which
means:
  - Parent jobs in 'waiting-children' never get rolled up.
  - Descendant jobs don't cascade-cancel.
  - Child-done inbox notification is skipped.

Result: a parent waiting on a child that fell inside quiet hours with
policy='skip' stays stuck forever.

Fix: release the lock, then delegate to queue.cancelJob(job.id) which
handles the recursive CTE + parent rollup + inbox posting correctly.
Falls back to a direct UPDATE only if cancelJob errors — even then, the
status transition is status-guarded to avoid stomping terminal states.

Defer path unchanged (no parent rollup needed since the job hasn't reached
a terminal state).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(budget): commit() re-checks cap + rejects negative actuals

Codex caught two cap-bypass bugs in BudgetLedger.commit():

1. reserve({estimateUsd: 0.01, capUsd: 1.0}) + commit(id, 100) silently
   charged $100 to a $1-cap bucket. Cap is an advertised invariant that
   the code was not enforcing.

2. Negative actuals (commit(id, -5)) were accepted, letting callers
   artificially reduce committed_usd below the real spend. Refunds need
   a dedicated API, not a side-channel on commit.

Fix:
- Reject non-finite AND negative actualUsd at entrypoint.
- Lock the ledger row FOR UPDATE during commit (same serialization as
  reserve).
- Compute effective cap headroom = cap - other_committed - other_reserved
  (excluding this reservation from the reserved pool since we're about to
  finalize it).
- When actualUsd would exceed available, clamp committed_usd to max
  available and throw BudgetError with the overage reported. The
  reservation is still marked 'committed' (API call already happened;
  don't retry-loop), but the cap is honored.

After this, a $1/day cap actually means $1/day.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(integrity): --dry-run no longer writes progress, poisoning resume

Codex caught that 'gbrain integrity auto --dry-run' appended progress
entries (status='repaired', 'reviewed', 'skipped', 'error') despite doing
no actual writes. The follow-on real run with default --resume would then
skip those slugs — the dry-run silently consumed the work queue.

Fix: gate every appendProgress() call in cmdAuto on !dryRun. Dry-run
still logs to the skip log / review queue (so the user sees what WOULD
happen), but the progress file stays untouched.

Behavior:
  --dry-run            → buckets counted + summary printed + review-queue
                         + log populated, but progress file unchanged.
  (default)            → progress file tracks every processed slug, so
                         Ctrl-C + re-run resumes from the right place.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore: bump version and changelog (v0.13.0.0)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(resolvers): DNS-rebinding defense + X rate-limit header parity

Two non-blocking codex findings on PR #210 rolled into one bisectable
commit because their tests share an import line.

url_reachable: hostname-string SSRF guard is vulnerable to DNS rebinding
(attacker-controlled DNS returns a public IP at validate time and
169.254.169.254 at fetch time). Add checkDnsRebinding() that resolves
the hostname via dns.lookup({all:true}) and rejects any result whose
A/AAAA record lands in a private range (v4 via isPrivateIpv4, v6
loopback/link-local/unique-local/IPv4-mapped). Applied on the initial
URL and on every redirect target. Null on DNS failure so genuine
network problems surface via fetch.

x_handle_to_tweet: rate-limit backoff only honored Retry-After and
ignored X's proprietary x-rate-limit-reset header. computeBackoffMs()
parses both (Retry-After = seconds or HTTP-date; x-rate-limit-reset =
epoch seconds), takes MAX, and clamps to [2s, 60s]. Exported for
testability; callers use it uniformly on every 429.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(writer): advisory lock on desiredSlug prevents cross-process TOCTOU

BrainWriter's createEntity checks engine.getPage(slug) and falls back
to putPage(), which upserts. Two putPage('people/alice') calls from
separate processes (a Claude Code session + a Minions worker, say) can
both read "free" from SlugRegistry and both call putPage, silently
overwriting each other with no disambiguation.

Take a transaction-scoped advisory lock keyed on hashtext(desiredSlug)
before the registry check. Concurrent writers for the same slug now
serialize at the DB level: the second observes the first's commit and
disambiguates to alice-2. PGLite is single-process so this is a
harmless no-op there. Wrapped in try/catch so engines/test doubles
that don't support advisory locks fall through to the existing
within-process check.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(validators): empty [Source:] no longer satisfies citation check

Regex /\[Source:[^\]]*\]/ matched decorative markers like [Source:]
and [Source:   ] that carry zero provenance. Tighten to require at
least one non-whitespace character before the closing bracket. The
inline URL form ](https://...) already requires a scheme+host so it
stays as-is.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(auto-link): advisory lock serializes concurrent reconciliation

runAutoLink wraps getLinks + addLink/removeLink in a transaction, but
row-level locks alone don't prevent the union-of-writes race: two
concurrent put_page calls on the same slug can both read the same
existingKeys BEFORE either mutates a row, then proceed to add links
the other side's rewrite no longer mentions.

Take a transaction-scoped advisory lock on hashtext("auto_link:" ||
slug) at the start of the reconciliation. Concurrent writers on the
same slug now fully serialize; writers on different slugs still run
in parallel. No-op on engines without advisory locks (PGLite).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test: expand coverage on abort-signal threading + integrity CLI dispatch

fail-improve: four new AbortSignal cases — pre-start abort, between
deterministic and LLM, signal forwarded into both callbacks, and
LLM-thrown AbortError propagates without logging a failure entry.

integrity: three new CLI dispatch cases — --help, no-subcommand (help),
and unknown subcommand (stderr + exit 1). Non-engine paths so they
exercise routing without spinning up a DB.

Coverage-only; no source changes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(doctor): fold integrity sample scan into default health check

Expose scanIntegrity(engine, opts) as a pure library function — same
logic cmdCheck uses — and call it from doctor in non-fast mode with
a 500-page sampling limit. Surfaces bare-tweet phrase count and
external-link count as an 'integrity' check, warn-status when bare
tweets are present with a one-liner pointing at 'gbrain integrity
check' for the full report and 'integrity auto' for repair.

Read-only: no network, no writes, no resolver calls. Pages with
validate:false frontmatter are skipped (grandfathered). --fast mode
skips it entirely so the existing health-snapshot contract holds.

Users no longer need to remember three separate commands (doctor,
lint, integrity check) to audit brain health — doctor surfaces the
integrity signal by default, full scan stays available for deep dives.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(put_page): auto-extract timeline entries alongside auto-link

put_page already chunks, embeds, reconciles tags, and extracts
auto-links on every write. Timeline extraction has lived in a
separate command (gbrain extract timeline) that users had to remember
to run. Fold it into the write path: after the page commits, parse
timeline entries from compiled_truth + timeline body and insert via
addTimelineEntriesBatch. ON CONFLICT DO NOTHING keeps it idempotent
across re-writes.

Mirrors auto-link shape: best-effort post-hook, skipped for remote
(MCP) callers, gated by auto_timeline config (default TRUE). Response
includes auto_timeline: { created } alongside auto_links.

Side effect: a one-shot `gbrain put` now produces a complete page —
chunks, embeddings, links, AND timeline — instead of three commands
the user has to chain manually.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(migrate): verify target health after engine migration

After a PGLite↔Postgres migration, the user was left to run 'gbrain
doctor' themselves to confirm the target is good. Not great, because
the failure modes (partial copy, missing embeddings, schema drift)
all surface at next CLI use when the migration itself looks like it
succeeded.

Add verifyTarget() — inline doctor-lite that checks page count
matches the source, embedding coverage is above 90%, and schema
version is at latest. Prints a 3-line status table at the end of
migrate and points at 'gbrain doctor' for the full check. Non-fatal:
warns on discrepancies instead of failing the command so the user
sees the full picture.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(bench): add v0.13 knowledge runtime benchmark deltas

Two new benchmark scripts + one consolidated markdown comparing this
branch against master (c0b6219, v0.12.1):

benchmark-put-page-latency.ts — 200 put_page ops, measures the
per-write cost of Step B's auto-timeline extraction. Branch adds
~0.5ms mean latency and produces 300 timeline entries for free;
master produces zero and requires a separate 'gbrain extract timeline'
pass.

benchmark-knowledge-runtime.ts — three measurements in one script:
time-to-queryable (branch 40/40 vs master 0/40 on post-ingest
timeline queries), integrity repair rate (70/20/10 three-bucket
split via mocked resolver), doctor completeness (surfaces 100% of
real issues after Step A, respects grandfathered pages).

docs/benchmarks/2026-04-19-knowledge-runtime-v0.13.md — consolidated
report. Covers the four moved benchmarks plus side-by-side runs of
graph-quality and search-quality showing they're identical across
master and branch. Proof of no regression on the retrieval hot path.

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-04-20 07:30:00 +08:00