Compare commits

...
Author SHA1 Message Date
root 820e138db0 fix: post-migration schema verification with self-healing
PgBouncer transaction-mode poolers can silently swallow ALTER TABLE
statements: the SQL doesn't error, but the column never gets created.
The migration system increments the schema version counter anyway, so
gbrain thinks it's on the latest version but the actual table is missing
columns. This caused production embed failures when the embed handler
tried to INSERT into columns that didn't exist.

Add verifySchema() that runs after all migrations complete:
1. Parses CREATE TABLE + ALTER TABLE ADD COLUMN from schema-embedded.ts
2. Queries information_schema.columns for actual DB state
3. Diffs expected vs actual columns
4. Self-heals missing columns via ALTER TABLE ADD COLUMN IF NOT EXISTS
5. Throws with actionable diagnostics if self-heal fails

Called from PostgresEngine.initSchema() after runMigrations().
PGLite skipped (in-process, no PgBouncer).
2026-04-28 04:46:38 +00:00
e734937254 fix: pass sourceId in cycle sync phase to prevent full reimport (#475)
* fix: pass sourceId in cycle sync phase to prevent full reimport

cycle.ts calls performSync without sourceId, so it always reads
the global config.sync.last_commit key instead of the per-source
sources.last_commit. When the global anchor gets garbage-collected
(after a force push or rebase), sync falls back to a full reimport
of all files — on a large brain this takes 30+ minutes and blocks
the autopilot cycle.

The fix resolves the source id from the brain directory by querying
the sources table. When a matching source exists, sync reads the
per-source anchor which is updated on every successful sync and
stays in sync with the repo history. Falls back gracefully to the
global config path for pre-v0.18 brains without a sources table.

* v0.22.5: tests + version bump for sync-cycle-source-id fix

Adds 6 regression tests in test/core/cycle.test.ts pinning the new
resolveSourceForDir() helper added to src/core/cycle.ts in this PR:

1. Seeded sources row → performSync receives matching sourceId
2. No matching row → sourceId=undefined (falls through to global key)
3. Different brainDir than registered source → undefined (no cross-match)
4. sources table missing (very old brain) → catch returns undefined,
   sync still runs. Uses a fresh PGLiteEngine because initSchema() only
   re-runs PENDING migrations; DROP TABLE on the shared engine would
   leave it permanently degraded for every later test in the file.
   (Codex review caught this landmine.)
5. Multiple rows with same local_path → resolver returns one matching
   id (non-deterministic; SQL has no ORDER BY). Documents the contract
   for the v0.23 UNIQUE-constraint follow-up.
6. Empty-string id row → resolver propagates "" (defensive case Codex
   flagged: schema PK prevents NULL but '' can be inserted).

Extends the performSync mock at line 51-65 to also capture sourceId.

Bumps:
- VERSION: 0.22.4 → 0.22.5
- package.json: 0.22.4 → 0.22.5
- CHANGELOG.md: new [0.22.5] entry following v0.22.4 voice (release
  summary + numbers table + behavior matrix + To-take-advantage block
  + itemized changes + for-contributors)
- CLAUDE.md: annotates src/core/cycle.ts entry with v0.22.5 (#475) note
- llms-full.txt: regenerated via bun run build:llms

Test results:
- Unit: 28 pass / 0 fail in test/core/cycle.test.ts (22 prior + 6 new)
- Full unit suite: pass (exit 0)
- E2E: 236 pass / 0 fail across 26 files

Plan + codex outside-voice review at:
~/.claude/plans/whimsical-bubbling-goose.md

Follow-up TODOs filed for v0.23:
- Normalize brainDir + sources.local_path before SQL compare
- Add UNIQUE index on sources.local_path
- Narrow resolveSourceForDir's catch to PG 42P01 (undefined_table)
- Add doctor check for config.sync.last_commit / sources divergence

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

* fix: typecheck error in cycle.test.ts test 5 (sourceId regression)

CI typecheck failed because `toContain()` on `string[]` rejects the
`string | undefined` produced by `syncCalls.at(-1)?.sourceId`'s optional
chain. Tests 1, 4, and 6 use `toBe()` which accepts `string | undefined`
through its overload, but `toContain()` is stricter.

Fix: pull the value into a typed variable, assert it's defined, then
check membership. Makes the contract explicit ("resolver returned a
defined sourceId, and it was one of the matching ids") instead of
relying on a silent undefined → no-match-in-array assertion.

Locally:
- bun run typecheck: clean
- bun test test/core/cycle.test.ts: 28 pass / 0 fail (75 expect calls)
- All CI gate scripts: OK (jsonb, progress-to-stdout, wasm-embedded)

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

* ci: add --timeout=60000 to E2E runner to prevent setupDB flake

PR #475's Tier 1 (Mechanical) CI job hit a 5000.09ms beforeAll hook
timeout in `E2E: Tags > (unnamed)`. Cause: scripts/run-e2e.sh invokes
`bun test "$f"` without a --timeout flag, falling back to bun's 5s
default. setupDB() does TRUNCATE CASCADE on ~30 tables, and on a CI
runner under load that can exceed 5s.

Match what the unit suite uses (--timeout=60000 in package.json's
"test" script). Same 1m ceiling, no behavior change for healthy runs;
just removes the artificial 5s floor on hooks.

Verified locally: bun test --timeout=60000 test/e2e/mechanical.test.ts
runs 78 pass / 0 fail in 27.99s against a fresh pgvector pg16 docker
container.

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

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 16:56:07 -07:00
Garry TanandClaude Opus 4.7 891c28b582 v0.22.4 feat: frontmatter-guard — 0 resolver warnings + validate/audit/install-hook CLI (#448)
* fix: resolve check-resolvable warnings on master

- skills/maintain/SKILL.md: drop "citation audit" trigger; the focused
  citation-fixer skill is the single owner. Silences the MECE overlap
  warning surfaced by src/core/check-resolvable.ts.
- skills/RESOLVER.md: add citation-audit disambiguation row pointing
  citation-fixer (focused fix) and chain-into maintain for broader audit.
  Broaden query triggers ("who is", "background on", "notes on") so
  the failing routing-eval fixtures resolve.
- skills/enrich/SKILL.md: replace inlined Citation Requirements block with
  backtick-wrapped `skills/conventions/quality.md` reference (the format
  extractDelegationTargets recognizes). Silences the dry_violation warning.
- skills/citation-fixer/routing-eval.jsonl: rewrite the two failing fixtures
  to embed "fix citations" verbatim so the substring matcher passes.
- skills/query/SKILL.md frontmatter: mirror the broadened RESOLVER.md
  triggers so the trigger round-trip test passes.

Result: gbrain check-resolvable reports 0 warnings, 0 errors against
the actual checked-in skills/ tree.

* feat: extend parseMarkdown + lint with frontmatter validation surface

Add an opt-in validation surface to parseMarkdown(): when called with
{ validate: true }, returns errors[] populated with seven canonical
ParseValidationError codes:

  MISSING_OPEN, MISSING_CLOSE, YAML_PARSE, SLUG_MISMATCH,
  NULL_BYTES, NESTED_QUOTES, EMPTY_FRONTMATTER

Existing callers are unaffected — validation is opt-in via the new
opts argument. The validation logic lives here as the single source of
truth for what counts as malformed brain-page frontmatter.

src/commands/lint.ts now consumes parseMarkdown(..., { validate: true })
and emits stable lint rule names (frontmatter-missing-close,
frontmatter-yaml-parse, frontmatter-null-bytes, frontmatter-nested-quotes,
frontmatter-slug-mismatch, frontmatter-empty). MISSING_OPEN is suppressed
to avoid double-reporting with the legacy no-frontmatter rule.

Tests: test/markdown-validation.test.ts (NEW, all 7 codes) +
test/lint-frontmatter.test.ts (NEW, lint integration + suppression).

* feat: add brain-writer.ts orchestrator (scan / autoFix / writeBrainPage)

Thin orchestrator (~280 lines) on top of parseMarkdown(..., {validate:true})
and isSyncable() (the canonical brain-page filter from src/core/sync.ts).
Three consumers call into this module: the gbrain frontmatter CLI, the
frontmatter_integrity doctor subcheck, and the v0.22.4 migration audit
phase. Single source of truth — no parallel validation stack.

Public API:
  - autoFixFrontmatter(content, opts?): { content, fixes }
    Mechanical auto-repair for the fixable subset (NULL_BYTES,
    MISSING_CLOSE, NESTED_QUOTES, SLUG_MISMATCH). Idempotent.
  - writeBrainPage(filePath, content, opts): path-guarded, .bak backup
    before any in-place mutation. Path guard refuses writes outside
    sourcePath. .bak is the safety contract for non-git brain repos.
  - scanBrainSources(engine, opts?): walks every registered source via
    direct SQL on sources.local_path, uses isSyncable() to filter,
    blocks symlinks (matches sync's no-symlink policy), respects
    AbortSignal.

The dirty-tree guard from src/core/dry-fix.ts:getWorkingTreeStatus() is
NOT used here — it rejects non-git repos as unsafe, but brain repos
aren't always git repos. .bak backups are the contract that works
universally.

Tests: test/brain-writer.test.ts (NEW, 16 cases) — autoFix idempotency,
path-guard reject, .bak backup, per-source rollup, AbortSignal mid-scan,
single-source filter, missing-source-path graceful skip, symlink no-loop.

* feat: gbrain frontmatter CLI (validate / audit / install-hook)

New top-level command surface for the frontmatter-guard feature:

  gbrain frontmatter validate <path> [--json] [--fix] [--dry-run]
    Validate one .md file or recursively scan a directory. --fix writes
    .bak then rewrites in place. No git-tree-clean guard — .bak is the
    safety contract (works for both git and non-git brain repos).

  gbrain frontmatter audit [--source <id>] [--json]
    Read-only scan via scanBrainSources(). Per-source rollup grouped by
    error code. --fix is intentionally NOT available here; use validate
    --fix on the source path to repair.

  gbrain frontmatter install-hook [--source <id>] [--force] [--uninstall]
    Drops a pre-commit hook in each source that's a git repo (skips
    non-git sources with a one-line note). Hook script gracefully
    degrades when gbrain is missing on PATH (prints a warning, exits 0).
    Refuses to clobber existing hooks without --force; writes <hook>.bak.
    --uninstall reverses cleanly.

src/cli.ts wires frontmatter through handleCliOnly so --help works
without a DB connection. The audit subcommand instantiates an engine
internally only when needed.

Tests: test/frontmatter-cli.test.ts (NEW, 9 cases) +
test/frontmatter-install-hook.test.ts (NEW, 6 cases) — --help no-DB,
clean/broken validate, --fix dry-run, --fix non-git, --json envelope,
recursive directory scan with isSyncable filter parity, hook install
+ overwrite-protection + --force + --uninstall + silent-refresh.

* feat: doctor frontmatter_integrity subcheck

Adds a frontmatter_integrity subcheck under gbrain doctor that calls
scanBrainSources() (the same shared scanner the CLI and migration use).
Reports per-source counts grouped by error code, with a fix hint
pointing at `gbrain frontmatter validate <path> --fix`. Wrapped in
a doctor progress phase with heartbeat so 50K-page brain scans stay
visible.

Tests: test/doctor.test.ts (UPDATE) — assertion that the subcheck
calls scanBrainSources and the fix hint references the correct CLI.

* feat: frontmatter-guard skill (registered in manifest + RESOLVER)

New skill at skills/frontmatter-guard/SKILL.md that wraps the gbrain
frontmatter CLI for agent-driven workflows. Agent-agnostic — no
references to private host libraries. Registered in skills/manifest.json
and skills/RESOLVER.md (the trigger row was added in the Part A commit).

Triggers: "validate frontmatter", "check frontmatter", "fix frontmatter",
"frontmatter audit", "brain lint".

Includes routing-eval fixtures that pass the substring matcher. The
SKILL.md has the conformance-required Output Format and Anti-Patterns
sections. Anti-patterns explicitly call out: don't auto-fix MISSING_OPEN
or EMPTY_FRONTMATTER without user input, don't skip .bak backups, don't
install the pre-commit hook on non-git brain dirs.

* feat: v0.22.4 migration orchestrator (audit-only, source-aware)

Adds the v0.22.4 migration that surveys every registered source for
frontmatter issues and queues per-source repair commands without ever
mutating brain content. Three idempotent phases:

  - schema: no-op (no DB changes in v0.22.4)
  - audit: scanBrainSources() across ALL registered sources; writes
    JSON report to ~/.gbrain/migrations/v0.22.4-audit.json
  - emit-todo: appends one entry per source-with-issues to
    ~/.gbrain/migrations/pending-host-work.jsonl, each with the exact
    `gbrain frontmatter validate <source-path> --fix` command

The agent reads skills/migrations/v0.22.4.md after upgrade, surfaces
the report counts to the user, and runs the fix command only with
explicit consent. `apply-migrations --yes` never silently rewrites
brain pages.

Filename convention: TS orchestrator at v0_22_4.ts (underscores, since
TS module paths can't have dots); user-facing migration doc at
skills/migrations/v0.22.4.md (dotted, matches existing convention).
The pending-host-work.jsonl skill field references the dotted-path doc.

Skips cleanly when no sources are registered (fresh install).

Tests: test/migrations-v0_22_4.test.ts (NEW, 9 cases) + updated
test/migration-orchestrator-v0_21_0.test.ts to allow v0.22.4 after,
test/apply-migrations.test.ts skippedFuture arrays extended to include
v0.22.4, test/check-resolvable.test.ts regression guard asserting the
actual checked-in skills/ tree has 0 warnings + 0 errors.

* docs: pre-commit recipe + downstream agent upgrade notes for v0.22.4

- docs/integrations/pre-commit.md (NEW): recipe doc covering install,
  bypass (`git commit --no-verify`), uninstall, and downstream-fork
  integration notes. Includes the full pipeline diagram showing how
  the hook (write-time gate), doctor (audit gate), and CLI (fix tool)
  share parseMarkdown(..., {validate:true}) as the single source of
  truth.
- docs/UPGRADING_DOWNSTREAM_AGENTS.md: append v0.22.4 section with the
  diff pattern for forks that had inline frontmatter validators. Covers
  the five upgrade actions: replace ad-hoc validators, drop
  lib/brain-writer.mjs references (it never shipped), wire the doctor
  subcheck into custom health pipelines, optionally install the
  pre-commit hook on git-backed brain repos, and walk
  pending-host-work.jsonl after apply-migrations.
- llms.txt + llms-full.txt: regenerated from build:llms script after
  the new docs landed.

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

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix: handle null loadConfig() return in frontmatter + migration paths

CI typecheck caught three call sites that passed loadConfig()'s
GBrainConfig | null result straight into toEngineConfig() (which
expects GBrainConfig, not null):

  - src/commands/frontmatter.ts:64 (audit subcommand connect)
  - src/commands/frontmatter-install-hook.ts:86 (install-hook connect)
  - src/commands/migrations/v0_22_4.ts:59 (audit phase connect)

The frontmatter CLI and install-hook paths follow the existing
src/commands/repair-jsonb.ts pattern: throw 'No brain configured. Run:
gbrain init' so users get an actionable message instead of a TS-shaped
runtime crash.

The v0.22.4 migration audit phase takes a different shape: a fresh
install or test environment running apply-migrations shouldn't fail
hard just because there's no brain to scan yet. Return a clean
'skipped: no_brain_configured' phase result so the orchestrator
continues normally and the ledger records a complete (skipped) run.

* test: add v0.22.4 migration E2E + injection point for testability

Closes plan item B14 (the E2E that was promised but not delivered before
the original ship). Runs the v0_22_4 orchestrator end-to-end on PGLite
against a fixture brain with two registered sources and synthetic
malformed pages on disk. Asserts:

  - audit phase writes ~/.gbrain/migrations/v0.22.4-audit.json with
    per-source counts (NESTED_QUOTES + NULL_BYTES on alpha,
    NESTED_QUOTES on beta)
  - emit-todo phase appends one entry per source-with-issues to
    pending-host-work.jsonl, each pointing at skills/migrations/v0.22.4.md
    with the exact `gbrain frontmatter validate <source> --fix` command
  - the migration is audit-only — no fixture page is mutated
    during apply-migrations (no .bak created, contents byte-identical)
  - re-running the orchestrator is idempotent — JSONL stays at 2 lines

Adds a small test-injection point to v0_22_4.ts:
  __setTestEngineOverride(engine: BrainEngine | null): void

Mirrors src/commands/repair-jsonb.ts pattern. When set, phaseBAudit
uses the injected engine instead of loadConfig + createEngine. Production
path is unchanged: the override is null by default and the existing
loadConfig logic runs end-to-end. Required because Bun's os.homedir()
does not observe mid-process process.env.HOME mutations, so we can't
redirect loadConfig's config-file lookup via env-var overrides; the
injection point is the only hermetic way to E2E-test the orchestrator
without writing to the user's real ~/.gbrain/config.json.

Test runs unconditionally in CI's Tier 1 (no DATABASE_URL needed,
PGLite in-memory).

---------

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-26 20:45:05 -07:00
Garry TanandClaude Opus 4.7 c78c3d0135 v0.22.2 feat: minions worker reliability — RSS watchdog, cold-start retry, autopilot backpressure (#458)
Production worker freezes silently every few hours. RSS climbs 68 MB → ~15 GB
over ~7 hours, the worker stops claiming jobs but never crashes (no OOM, no
SIGSEGV), the cron keeps enqueuing autopilot-cycle jobs every 5 minutes into a
queue nobody is draining, and within 2-3 hours the queue piles up to 28+
waiting jobs. Shell jobs in flight when the worker froze hit max_stalled and
dead-letter, producing 18% shell-job failure rate over 24h.

Three in-repo defenses close the cascade end-to-end while the underlying
memory leak gets investigated separately:

1. RSS watchdog (worker.ts): per-job AND 60s periodic check; on trip fires
   shutdownAbort + per-job aborts BEFORE stop(), so shell handlers run their
   SIGTERM→5s→SIGKILL cleanup and cooperative handlers bail instead of
   eating the 30s drain. Closes the zombie-shell-children gap. Default 2048
   MB on supervisor; bare `gbrain jobs work` stays opt-in to preserve large
   embed/import working sets.

2. connectWithRetry (db.ts + cli.ts): wraps engine.connect() default-on,
   3 attempts with 1s/2s/4s backoff. 5-pattern transient-error matcher
   (auth failed, connection refused, db starting, terminated, ECONNRESET);
   permanent errors do NOT retry. Operators can opt out per-call via
   --no-retry-connect or GBRAIN_NO_RETRY_CONNECT=1. Fixes PgBouncer cold-
   start auth races on autopilot/dream/jobs daemons.

3. autopilot-cycle backpressure: queue.add now passes maxWaiting:1 (1 active
   + 1 waiting; coalesce 3rd+). Combined with idempotency_key, cross-slot
   pile-ups are bounded. Autopilot's worker spawn loop also gets the
   supervisor's stable-run reset pattern (5min uptime → reset crash count)
   so hourly watchdog exits don't trip the 5-crash give-up threshold.

Reviewed via /plan-eng-review (5 arch + 1 test issue, all resolved) and
/codex (6 additional findings B1-B6 surfaced real bugs the eng review
missed; all resolved Codex's way). 11 new tests across watchdog (5 cases
including the production-freeze-regression scenario where zero jobs ever
complete), connectWithRetry (6 cases), and supervisor argv (1 case).

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 16:54:32 -07:00
e2961c04bd v0.22.1 autopilot fix wave — 5 prod hotfixes (#417, #403, #406, #363, #409) (#447)
* fix: propagate AbortSignal to runCycle + worker force-eviction safety net

Root cause: autopilot-cycle handler called runCycle() without passing
the job's AbortSignal. When the per-job timeout fired abort(), runCycle
never checked it and kept grinding through extract (54,605 pages).
The executeJob promise never resolved, inFlight never decremented, and
the worker thought it was at capacity forever — 98 jobs piled up waiting
with 0 active while a live worker sat idle.

Three-layer fix:

1. CycleOpts.signal: new optional AbortSignal field. runCycle checks it
   between every phase via checkAborted(). A timed-out cycle now bails
   after the current phase completes instead of running all 6 phases.

2. autopilot-cycle handler: passes job.signal to runCycle so the abort
   actually propagates.

3. Worker safety net: 30s after the abort fires, if the handler still
   hasn't resolved, force-evict from inFlight and mark as dead in DB.
   This is the last-resort escape hatch for any handler that ignores
   AbortSignal — the worker resumes claiming new jobs instead of
   wedging forever.

Incident: 2026-04-24, 98 waiting / 0 active / worker alive but idle.
143 existing minions tests pass unchanged.

* test: abort signal propagation + worker recovery regression tests

16 new tests across 3 files covering the 2026-04-24 worker wedge:

test/minions.test.ts (6 new, 149 total):
  - handler receiving abort signal exits cleanly
  - handler ignoring abort still gets signal delivered
  - worker claims new jobs after timeout (no wedge) ← key regression
  - checkAborted pattern: undefined/non-aborted/aborted signals

test/cycle-abort.test.ts (7 new):
  - CycleOpts.signal type contract
  - runCycle accepts signal without error
  - runCycle bails on pre-aborted signal
  - runCycle bails mid-flight when signal fires between phases
  - Source-level guard: jobs.ts passes job.signal to runCycle
  - Source-level guard: worker.ts has force-eviction safety net
  - Source-level guard: cycle.ts has checkAborted between all 6 phases

test/e2e/worker-abort-recovery.test.ts (3 new):
  - worker recovers from timed-out handler and processes next job
  - concurrency=2 processes parallel jobs during timeout
  - multiple sequential timeouts don't permanently wedge worker

All 159 tests pass.

* perf: incremental extract — only process slugs that sync touched

The autopilot-cycle runs every 5 min. Its extract phase was doing a full
filesystem walk of ALL markdown files (54K+) — twice (links + timeline).
On a brain this size, extract alone exceeded the 600s job timeout,
producing zero useful writes.

Fix: sync already returns pagesAffected (the slugs it added/modified).
Pipe that list through to extract. When provided, extract reads ONLY
those files instead of walking the entire brain directory.

- Add ExtractOpts.slugs for targeted extraction
- Add extractForSlugs() — single-pass links + timeline for specific slugs
- cycle.ts: capture sync's pagesAffected, pass to runPhaseExtract
- If sync didn't run or failed, extract falls back to full walk (safe)
- If pagesAffected is empty (nothing changed), extract returns instantly

Expected improvement: 54K file reads → ~10-50 per cycle. The full walk
is still available via CLI `gbrain extract` and on first-run.

* fix: connection resilience for minion supervisor + worker

Three fixes for the minion supervisor dying silently when PgBouncer rotates:

1. PostgresEngine: executeRaw retries once on connection-class errors
   (ECONNREFUSED, password auth failed, connection terminated, etc.)
   by tearing down the poisoned pool and creating a fresh one via
   reconnect(). Prevents cascading failures when Supabase bounces.

2. Supervisor: tracks consecutive health check failures. After 3 in a
   row, emits health_warn with reason=db_connection_degraded and attempts
   engine.reconnect() if available. Resets counter on success.

3. Supervisor: worker_exited events now include likely_cause field:
   SIGKILL → oom_or_external_kill, SIGTERM → graceful_shutdown,
   code=1 → runtime_error. Makes it trivial to distinguish OOM kills
   from connection deaths in logs.

Tests: 23 new tests covering connection error detection, reconnect
guard against concurrent reconnects, retry-once-not-infinite-loop,
health failure tracking, and exit classification.

* fix(db): set session timeouts on every connection to kill orphan backends

Prevents the failure mode from #361: a single autopilot UPDATE on
minion_jobs can leave a pooler backend in state='active'/ClientRead
for 24h+, holding a RowExclusiveLock that blocks every subsequent
ALTER TABLE minion_jobs. The stuck backend never times out on its
own because Supabase Micro has no default idle_in_transaction_session_timeout
and autovacuum can't reap sessions that hold active locks.

Fix: deliver statement_timeout + idle_in_transaction_session_timeout
as startup parameters via postgres.js's `connection` option, applied
automatically on every new backend connection. Works correctly on
both session-mode and transaction-mode PgBouncer poolers (startup
params persist for the backend's lifetime, unlike SET commands
which transaction-mode PgBouncer strips between transactions).

Defaults chosen conservatively so they don't interfere with bulk
work like multi-minute embed passes or CREATE INDEX on large pages
tables:
  - statement_timeout: '5min'
  - idle_in_transaction_session_timeout: '2min'

Each overridable per-GUC via env var (GBRAIN_STATEMENT_TIMEOUT,
GBRAIN_IDLE_TX_TIMEOUT). Set any to '0' or 'off' to disable.

client_connection_check_interval is the specific GUC that would
kill the observed state='active'/ClientRead case, but it's
Postgres 14+ and some managed poolers reject unknown startup
parameters. Made it opt-in only via GBRAIN_CLIENT_CHECK_INTERVAL
for users who know their Postgres supports it.

Applied in both the module-level singleton connect (src/core/db.ts)
and the per-engine-instance pool used by `gbrain jobs work`
(src/core/postgres-engine.ts) via a shared resolveSessionTimeouts()
helper.

Tests: 5 new cases in migrate.test.ts covering defaults, env
overrides, '0'/'off' disable, and multi-GUC disable. 39/39 pass
(34 pre-existing + 5 new).

Closes #361.

Co-Authored-By: orendi84 <orendigergo@gmail.com>

* fix(embed): server-side staleness filter for embed --stale (v0.20.5)

embed --stale walked listPages + per-page getChunks (incl. vector(1536)
embedding column) on every call, then client-side-filtered for chunks
where embedding was missing. On a 1.5K-page brain at 100% coverage, ~76 MB
pulled per call, all discarded. With autopilot firing every 5-10 min plus
a 2h cron, this hit Supabase's 5 GB free-tier ceiling at 102 GB used
(2058% over) twice in one week.

Two new BrainEngine methods replace the page walk with a SQL-side filter:
- countStaleChunks(): single SELECT count(*) WHERE embedding IS NULL.
  Pre-flight short-circuit; ~50 bytes wire when 0 stale.
- listStaleChunks(): slug + chunk_index + chunk_text + chunk_source +
  model + token_count for stale rows only. Excludes the (NULL) embedding
  column. Bounded by LIMIT 100000 mirroring listPages.

embedAll forks: staleOnly=true takes the new SQL-side path
(embedAllStale); staleOnly=false (--all) keeps existing behavior verbatim.

embedAllStale preserves non-stale chunks on partially-stale pages: it
re-fetches existing chunks per stale slug and merges (embedding=undefined
for non-stale → COALESCE preserves existing). Without the merge, the
upsertChunks != ALL filter would delete non-stale chunks. Re-fetch cost
is bounded by stale slug count; the autopilot common case (0 stale)
never reaches this path.

Predicate uses `embedding IS NULL`, not `embedded_at IS NULL`. The bulk-
import path could leave embedded_at populated while embedding was NULL
(see upsertChunks consistency fix below), so `embedding IS NULL` is the
truth source for "this chunk needs an embedding".

Also fixes the upsertChunks consistency bug in both engines: when
chunk_text changes and no new embedding is supplied, embedding correctly
clears to NULL but embedded_at kept its old timestamp. New behavior
resets BOTH columns together, keeping write-time honesty.

Wire-cost impact (measured against current behavior on a 1.5K-page brain):
- 0 stale chunks (autopilot common case): ~76 MB → ~50 bytes (~1.5M× reduction)
- 100 stale across 10 pages: ~76 MB → ~150 KB (~500× reduction)
- 8K stale across 1.5K pages (cold start): ~76 MB → ~12 MB (~6× reduction)

Tests: 4 new in test/embed.test.ts (zero-stale short-circuit; N-stale-
across-M-pages with non-stale preservation; --stale dry-run; --all path
byte-identical). Existing --stale tests updated for the new mock surface.

Migration impact: none. embedded_at and embedding columns have been on
content_chunks since schema inception.

Co-Authored-By: atrevino47 <atbuster47@gmail.com>

* chore(wave): post-merge tightening — drop executeRaw retry (D3) + gate noExtract (F2)

- Drop #406's per-call executeRaw retry wrapper. The regex idempotence
  boundary is unsound (writable CTEs, side-effecting SELECTs). Recovery
  now happens at the supervisor level via 3-strikes-then-reconnect.
- Update db.ts: setSessionDefaults becomes a back-compat no-op.
  resolveSessionTimeouts (from #363) is the source of truth, sending
  GUCs as startup parameters that survive PgBouncer transaction mode.
  Bumped idle_in_transaction default from 2min to 5min to match v0.21.0
  posture.
- Gate noExtract in cycle's runPhaseSync on whether extract phase is
  scheduled. Avoids silently dropping extraction when the user runs
  `gbrain dream --phase sync` (Codex F2).

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

* fix(db): rephrase docstring to avoid false-positive in test source-grep

The migrate.test.ts structural check counts `SET idle_in_transaction_session_timeout`
matches in source. The literal string in this docstring was tripping it.

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

* test: backfill regression guards for #417, D3, F2 (Step 5)

15 new test cases across 3 files, ~250 LOC, all PGLite/in-memory:

test/extract-incremental.test.ts (NEW, 8 cases for #417):
- slugs: [] returns immediately (early-return)
- slugs: undefined falls through to full-walk
- slugs: [a, b] reads only those files
- Slug whose file no longer exists is silently skipped
- Mode filter (links) skips timeline extraction
- dryRun: true does not invoke addLinksBatch / addTimelineEntriesBatch
- BATCH_SIZE flush — >100 candidate links exercise mid-iteration flush
- Full-slug-set resolution — link to file outside changed set still resolves

test/core/cycle.test.ts (4 new cases for #417 + Codex F2):
- cycle threads sync.pagesAffected into extract phase as the slugs argument
- extract phase falls back to full walk when sync was skipped
- F2 guard: full cycle (sync + extract) sets noExtract=true on sync
- F2 guard: phases:[sync] only sets noExtract=false (no silent extract drop)

test/connection-resilience.test.ts (3 new cases for D3):
- PostgresEngine.executeRaw is a single-statement passthrough (no try/catch)
- PostgresEngine.reconnect() still exists for supervisor-driven recovery
- Supervisor still has the 3-strikes-then-reconnect path

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

* docs(wave): v0.21.1 release notes + 3 follow-up TODOs + CLAUDE.md updates

CHANGELOG.md: segment-aware entry per CEO-review D1 — 'For everyone'
section (#417 incremental extract, #403 cycle abort) leads, 'For Postgres /
Supabase users' section (#406, #363, #409) follows. Production proof
point as a sidebar, not the lead.

TODOS.md: 3 follow-up items per Eng-review D6:
  1. Caller-opt-in retry for executeRaw (D3 follow-up)
  2. Replace walkMarkdownFiles with engine.getAllSlugs() (F1 follow-up)
  3. err.code-based connection-error matching (B1 follow-up)

CLAUDE.md: 6 file-reference updates for the wave's behavioral additions
(postgres-engine, db, cycle, worker, supervisor, embed, extract).

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

* chore(release): bump version 0.21.1 → 0.22.1 + document version locations

User-explicit version override on /ship: ship as v0.22.1 (MINOR jump from
master's 0.21.0) instead of the v0.21.1 PATCH the wave originally targeted.
The wave bundles 5 production fixes which is meaningful enough to clear a
MINOR version, even though the API surface is additive.

Files updated to 0.22.1:
- VERSION (single source of truth)
- package.json (Bun/npm version)
- CHANGELOG.md (release header + "To take advantage of v0.22.1" block)
- TODOS.md (3 follow-up TODOs reference the version that filed them)
- CLAUDE.md (Key Files annotations cite the release that introduced behavior)

Also adds a "Version locations" section to CLAUDE.md documenting all five
required files plus the auto-derived (bun.lock, llms-full.txt) and
historical (skills/migrations/v*.md, src/commands/migrations/v*.ts,
test/migrations-v*.test.ts) categories. Future /ship runs and the
auto-update agent now have a canonical list of where versions live.

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

* fix(test): unbreak CI typecheck — annotate signal as AbortSignal | undefined

CI's `bun run typecheck` step was failing with TS2339 at
test/minions.test.ts:2026 — `const signal = undefined` narrows to literal
`undefined`, which has no `.aborted` property, so `signal?.aborted`
doesn't compile.

Fix uses `as AbortSignal | undefined` to preserve the union type. A
plain type annotation gets narrowed back via control-flow analysis; the
`as` cast doesn't. Runtime behavior is unchanged — the optional-chain
still short-circuits as intended.

Verified: bunx tsc --noEmit → exit 0; the 3 checkAborted cases still pass.

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

* fix(doctor): forward-progress override for stale minions partials

The minions_migration check reads ~/.gbrain/migrations/completed.jsonl
and flags any version that has a `partial` entry without a matching
`complete`. Long-lived installs accumulate partial records from
historical stopgap runs (notably v0.11.0). Without time decay or
forward-progress detection, the FAIL flag fires forever once any
partial lands, even on installs that have been running clean at
v0.22+ for months.

Concrete failure: test/e2e/mechanical.test.ts "gbrain doctor exits 0
on healthy DB" was flaking on dev machines whose ~/.gbrain/ carried
v0.11.0 partials from earlier in the day. The fresh test DB had
nothing wrong with it; doctor was just reading host filesystem state
that bled in via $HOME.

Fix: a partial vX.Y.Z is treated as stale (not stuck) if any vA.B.C
where A.B.C >= X.Y.Z has a `complete` entry anywhere in the file.
The reasoning: if a newer migration successfully landed, the install
has clearly moved past the older partial. compareVersions() from
src/commands/migrations/index.ts handles the semver compare.

Cases preserved:
- v0.10 complete + v0.11 partial → still FAILs (older complete doesn't
  supersede newer partial)
- v0.16 partial alone → still FAILs (no override exists)
- Fresh install (no completed.jsonl) → no warning
- Real partial-then-complete-same-version → no warning

Cases now fixed:
- v0.16 complete + v0.11 partial → no FAIL (forward progress made;
  the v0.11 record is stale)

Two regression tests in test/doctor-minions-check.test.ts cover both
directions of the override (when it fires, when it doesn't).

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

* chore(docs): regenerate llms-full.txt after CLAUDE.md updates

CI's build-llms regen-drift guard caught that llms-full.txt was stale
relative to CLAUDE.md after the wave's documentation commits (the
"Version locations" section + 6 file-reference annotations for the
wave's behavioral additions).

CLAUDE.md notes that llms-full.txt is auto-derived — bumped via
'bun run build:llms' when CLAUDE.md's file-references change. This
commit catches up.

llms.txt is unchanged; the curated index doesn't pull from CLAUDE.md's
file-reference body. Only llms-full.txt (the inlined single-fetch
bundle) needed regeneration.

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

---------

Co-authored-by: root <root@localhost>
Co-authored-by: orendi84 <orendigergo@gmail.com>
Co-authored-by: atrevino47 <atbuster47@gmail.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 15:49:48 -07:00
Garry TanandClaude Opus 4.7 172b55ba9d v0.22.0 feat: source-aware search ranking — curated pages win, swamp dampened (#439)
* feat(search): add exclude_slug_prefixes + include_slug_prefixes to SearchOpts

The two new fields plumb prefix-based hard-exclude through the search API.
exclude_slug_prefixes is additive over the engine's default hard-exclude set
(test/, archive/, attachments/, .raw/) and the GBRAIN_SEARCH_EXCLUDE env var.
include_slug_prefixes subtracts entries from the resolved set so callers can
opt back into directories that are hidden by default.

Stand-alone change — no engine wiring yet (lands in subsequent commits).

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

* feat(search): source-boost + SQL ranking helpers (no engine wiring yet)

Two new modules + unit tests. Pure functions, zero engine dependencies.

source-boost.ts:
  - DEFAULT_SOURCE_BOOSTS map (originals/ 1.5, concepts/ 1.3, writing/ 1.4,
    people/ 1.2, daily/ 0.8, media/x/ 0.7, wintermute/chat/ 0.5, etc.) —
    grounded in the composition of the canonical brain.
  - DEFAULT_HARD_EXCLUDES = ['test/', 'archive/', 'attachments/', '.raw/'].
  - GBRAIN_SOURCE_BOOST + GBRAIN_SEARCH_EXCLUDE env-var parsers, malformed
    entries skipped silently.
  - resolveBoostMap / resolveHardExcludes merge defaults + env + caller opts.

sql-ranking.ts:
  - buildSourceFactorCase emits a CASE expression for the source factor.
    Returns literal '1.0' when detail==='high' so temporal queries bypass
    source-boost (matches the COMPILED_TRUTH_BOOST gate in hybrid.ts).
    Prefixes sorted by length desc so longest-match wins.
  - buildHardExcludeClause emits NOT (col LIKE 'p1%' OR col LIKE 'p2%').
    NOT a NOT LIKE ALL/ANY array — those quantifiers don't express
    set-exclusion correctly for multi-pattern LIKE.
  - LIKE meta-character escape covers all three: %, _, AND \. Backslash
    coverage matters because it's Postgres LIKE's default escape char —
    a literal backslash in a user env prefix would otherwise be
    interpreted as 'escape the next char' and silently match wrong rows.
  - SQL string literals get single-quote doubling so injection-style
    inputs render as inert text inside the quoted string.

39 unit tests cover escape behavior, longest-prefix-match, detail-gate
bypass, malformed env, factor=0 (legal), negative-factor rejection,
SQL-injection-as-literal, and resolver merge semantics.

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

* test(search): E2E coverage for source-boost, hard-exclude, engine parity

search-swamp.test.ts: reproduces the v3-plan headline case. Seeds a
curated originals/talks/article-outline-fat-code page against two
wintermute/chat/ pages stuffed with 'fat code thin harness' repetitions.
Asserts the article wins both keyword and vector ranking, and that
detail=high lets the chat swamp re-surface (temporal-query workflow
preserved). Also asserts source_id passes through the two-stage CTE.

search-exclude.test.ts: verifies test/ + archive/ pages are hidden by
default, that include_slug_prefixes opts back in, and that
exclude_slug_prefixes adds to defaults.

engine-parity.test.ts: codex flagged that searchKeyword's structural
behavior differs between engines (Postgres ranks pages then picks best
chunk; PGLite returns chunks directly). Without parity coverage the fix
could pass on PGLite and silently fail on Postgres. Seeds identical
corpus into both engines, runs identical queries, asserts top-result +
result-set match. Includes a vector-search parity case and a hard-exclude
parity case. Skips gracefully when DATABASE_URL is unset, per the
CLAUDE.md E2E lifecycle pattern.

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

* feat(search): wire source-boost into v0.21.0 chunk-grain searchKeyword + searchKeywordChunks + two-stage searchVector

Layers source-aware ranking on top of v0.21.0's Cathedral II
chunk-grain FTS architecture, in both Postgres and PGLite engines.

postgres-engine.ts:
  - searchKeyword (chunk-grain CTE → DISTINCT ON page dedup): the inner
    ranked_chunks CTE multiplies ts_rank by the source-factor CASE
    expression, hard-exclude prefixes (test/, archive/, attachments/,
    .raw/ by default + env + caller) become a NOT-LIKE OR-chain on
    the WHERE clause, language/symbol-kind filters preserved.
  - searchKeywordChunks (chunk-grain anchor primitive used by two-pass
    Layer 7): same source-boost treatment so the anchor pool that
    feeds two-pass retrieval is also dampened on chat/daily/x dirs.
  - searchVector becomes a two-stage CTE: inner CTE keeps pure
    HNSW ORDER BY (folding source-boost into it would force a
    sequential scan over every chunk), outer SELECT re-ranks by
    raw_score × source-factor. innerLimit scales with offset to
    preserve pagination contract. p.source_id passes through
    inner→outer for v0.18 multi-source callers.
  - All three methods stay inside sql.begin + SET LOCAL
    statement_timeout from v0.19+ (transaction-scoped GUC; bare SET
    leaks onto pooled connections, documented DoS vector).

pglite-engine.ts: mirrors the same three methods. Same SQL shape,
same source-factor + hard-exclude. Two-stage CTE also lifts stale-flag
computation into the outer SELECT (it referenced p.updated_at which
now lives only inside the inner CTE).

Detail-gate (`detail !== 'high'`) inherited from buildSourceFactorCase
... temporal queries bypass source-boost so chat surfaces normally for
date-framed lookups. Same gate pattern as the existing
COMPILED_TRUTH_BOOST in hybrid.ts.

Tests: 142 pass across pglite-engine, postgres-engine, sql-ranking,
search-swamp E2E, search-exclude E2E.

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

* docs: update project documentation for v0.22.0 (rebased onto v0.21.0 master)

CHANGELOG: new v0.22.0 entry above v0.21.0 (Cathedral II). Headline
positions v0.22.0 as additive on top of v0.21.0's two-pass retrieval
... different mechanism, +3.3pts top-1 / -3.3pts swamp on the new
Cat 13b benchmark in the sibling gbrain-evals repo.

CLAUDE.md:
  - postgres-engine.ts entry mentions all three updated methods
    (searchKeyword, searchKeywordChunks, searchVector) and the
    two-stage CTE for searchVector specifically.
  - pglite-engine.ts entry parallels the Postgres notes.
  - src/core/search/ entry calls out source-aware ranking +
    hard-exclude defaults + detail-gate parity with COMPILED_TRUTH_BOOST.
  - Added entries for src/core/search/source-boost.ts and
    src/core/search/sql-ranking.ts in the Key Files section.
  - Added test/sql-ranking.test.ts and the three new E2E test
    files (search-swamp, search-exclude, engine-parity) to the
    test listings.

README.md: SEARCH PIPELINE diagram in the "many strategies in concert"
section gains two lines for source-aware ranking and hard-exclude
filtering.

VERSION: 0.21.0 → 0.22.0.

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

* fix(tests): typecheck + Postgres minions-shell env-var setup

Two test fixes uncovered while running the full bun run test + E2E
suite at zero defects.

test/e2e/engine-parity.test.ts: BrainEngine was being imported from
src/core/types.ts but it's actually exported from src/core/engine.ts;
the import was silently working under bare `bun test` but failing
typecheck. Fixed the import path and annotated 6 implicit-any
SearchResult callbacks. (No behavior change ... typecheck only.)

test/e2e/minions-shell.test.ts: the Postgres minions-shell test was
missing the `GBRAIN_ALLOW_SHELL_JOBS=1` env-var setup that the
PGLite sibling test in test/e2e/minions-shell-pglite.test.ts already
has. Without it the shell handler short-circuits and the job lands
in `dead`, not `completed`. The env var is the operator-trust gate
for the shell handler ... separate from the trusted-add
allowProtectedSubmit flag. Adding the same beforeAll/afterAll
setup-and-restore pattern from the PGLite sibling brings the test
to green.

Both bugs were latent on master ... bare `bun test` skipped the
typecheck and the minions-shell E2E was a pre-existing flake
(documented as such in earlier branch summary).

Verified: full unit suite 2714 pass / 0 fail (`bun run test`),
full E2E suite 225 pass / 0 fail across 24 files.

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

* chore: regenerate llms-full.txt for v0.22.0 doc updates

Picks up the v0.22.0 entries added to CLAUDE.md (source-boost.ts,
sql-ranking.ts, three new E2E test files, postgres/pglite engine
search-method updates). The build-llms.test.ts regen-drift guard
was failing because the committed bundle didn't match the current
generator output.

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

* fix(search): adversarial review fixes — detail loose-string + PGLite CTE alias

Two FIXABLE findings from /ship's adversarial subagent pass:

1. **buildSourceFactorCase: tolerate loose-string `detail` over the MCP
   boundary.** TypeScript narrows the typed callers, but agents passing
   JSON across MCP can send `"HIGH"` (uppercase) or `"high "` (trailing
   space). Before this change, those values silently fell through the
   `detail === 'high'` strict-equality check and got boosted ranking
   instead of the temporal bypass — the opposite of what the agent asked
   for. Now the gate normalizes `String(detail).trim().toLowerCase()`
   before comparing. Three new test cases cover `"HIGH"`, `"high "`, and
   `"  High  "`.

2. **PGLite searchVector: alias the hnsw_candidates CTE as `hc` and
   qualify the correlated subquery.** The prior shape had
   `WHERE te.page_id = page_id` in the staleness subquery — unqualified
   `page_id` resolved by lexical-scope fallback to
   `hnsw_candidates.page_id`, but if the inner column is ever renamed or
   the parser changes, it would silently bind to `te.page_id` itself
   (always true) and every result returns `stale=true`. Aliasing the CTE
   as `hc` and qualifying both `hc.page_id` and `hc.slug` (via building
   the source-factor CASE with `'hc.slug'`) eliminates the ambiguity.
   Postgres `searchVector` was already safe — it uses `false AS stale`
   (no correlated subquery) — so no symmetric change needed there.

Three INVESTIGATE findings deferred:
- HNSW + hard-exclude planner behavior on real Postgres (needs EXPLAIN on
  a 50K+ chunk Supabase corpus, not reproducible on PGLite)
- searchKeywordChunks pagination pool growth (would change the v0.21.0
  contract; inherits the original Cathedral II shape)
- resolveBoostMap re-reads process.env per call (cheap, intentional —
  enables mid-process env reload for tuning)

Verified: 137 pass / 0 fail across sql-ranking + pglite-engine +
search-swamp + search-exclude tests.

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-25 23:35:27 -07:00
f718c595b3 v0.21.0 feat: Code Cathedral II — call-graph edges, two-pass retrieval, parent-scope chunking (#422)
* feat: v0.18.0 baseline — code indexing + multi-repo (Layer 0)

Tree-sitter-based code chunker for TS/JS/Python/Ruby/Go. Splits code at
semantic boundaries (functions, classes, types, exports). Each chunk
includes a structured header for embedding context.

Multi-repo config: gbrain repos add/list/remove, gbrain sync --all.
Strategy-aware sync: markdown (default), code, or auto. New PageType
'code' for code file pages.

This is Layer 0 of the v0.18.0 code-indexing plan (see ~/.claude/plans
cathedral plan). Subsequent layers add: tests, bun --compile WASM
embedding + CI guard (A1), schema migrations v16 (pages.repo_name) +
v17 (content_chunks code metadata), per-repo sync bookmarks, runCycle
multi-repo, Chonkie chunker parity (E2a), incremental chunking (E2),
doc↔impl linking (E1), markdown fence extraction (E3), symbol navigation
commands (code-def, code-refs), cost preview, BrainBench code category,
CHANGELOG, migration file, docs.

Backward compatible: no config changes = existing behavior preserved.

* feat: v0.19.0 Layer 1 — tests for baseline + errors envelope + version bump

Adds the structured error envelope (src/core/errors.ts) that downstream
v0.19.0 commands (code-def, code-refs, sync --all cost preview,
importCodeFile) all hand back to agents. The envelope follows the v0.17.0
CycleReport.PhaseResult.error shape so agent-consumption stays consistent
across every gbrain surface.

Test coverage for Wintermute's baseline (added in Layer 0):
- test/errors.test.ts — envelope helper + GBrainError + serializeError
- test/multi-repo.test.ts — config CRUD, dedup, file permissions
- test/sync-strategy.test.ts — isSyncable strategy matrix + include/exclude
  globs + slugifyCodePath + pathToSlug with pageKind

Bug fixes uncovered by the new tests:
- src/core/sync.ts: globToRegex handles `src/**/*.ts` matching `src/foo.ts`
  (zero intermediate dirs). `**/` now compiles to `(?:.*/)?` instead of
  `.*/`. Also `?` now matches only non-slash chars (was `.`).
- src/core/config.ts: configDir() respects GBRAIN_HOME env override so
  tests can isolate ~/.gbrain/. Matches GBRAIN_AUDIT_DIR convention.
  Bun's os.homedir() ignores $HOME on macOS, so we need an explicit
  override variable.

Version bump: package.json 0.18.2 → 0.19.0. v0.18.0-2 were already
released (multi-source brains + RLS + migration hardening), so the next
free minor for code indexing is 0.19.0. Wintermute's baseline author
label of 0.16.4 had been stale since v0.17.0 shipped; no user-visible
regression from the jump.

Per the rebased cathedral plan: Wintermute's multi-repo.ts and repos
CLI are preserved at the baseline but will be superseded in Layer 4 by
the v0.18.0 sources system (src/core/source-resolver.ts,
src/commands/sources.ts). multi-repo tests stay valid for the baseline
and will be removed alongside the code they cover.

* feat: v0.19.0 Layer 2 — bun --compile WASM embedding + CI guard

The single highest-risk change in v0.19.0 code indexing. Before this, the
chunker loaded WASMs via `new URL('../../../node_modules/...', import.meta.url)`
which silently breaks in the compiled binary (no node_modules at runtime).
Users would see degraded chunking quality with no error, just fallback-
recursive chunks instead of real semantic chunks. Codex flagged this as
the #1 silent-failure mode.

Mechanics:

- `src/assets/wasm/tree-sitter.wasm` + 36 grammar WASMs committed to the
  repo (50MB). Not a small check-in, but the alternative is a postinstall
  script that runs before every dev bun run and fails fragile-ly on
  network errors.

- `src/core/chunkers/code.ts` uses Bun's `import ... with { type: 'file' }`
  import attribute. At runtime the imported value is a file path — the
  actual repo path in dev, a bundler-synthesized path in the compiled
  binary. The tree-sitter runtime's `Language.load(path)` reads it the
  same way in both cases.

- Layer 2 keeps the 6-language support Wintermute shipped (TS/TSX/JS/Py/
  Rb/Go). Layer 5 (E2a chunker parity) expands to all 36 bundled grammars.

- CHUNKER_VERSION=2 constant introduced. importCodeFile will fold this
  into content_hash in Layer 3 so chunker-shape changes across releases
  force clean re-chunks without the user needing `sync --force`.

CI guard — `scripts/check-wasm-embedded.sh` + `scripts/chunker-smoketest.ts`:

- Compiles a smoketest binary that calls chunkCodeText on a known TS
  snippet.
- Asserts the output has `has_real_symbols: true`, a `[TypeScript]`
  language tag, and the expected symbol name.
- If the chunker silently falls through to recursive chunks, the
  assertions fail the build.
- Wired into `bun test` via package.json script pipeline. Also exposed
  as `bun run check:wasm` for standalone invocation.

Verification:
- Dev: `bun -e '...'` smoke test returns 2 chunks with correct symbol
  names in under 100ms.
- Compiled: `bash scripts/check-wasm-embedded.sh` passes end to end.
- Binary size: the gbrain binary grows from ~90MB to ~140MB, dominated
  by the 50MB of grammar WASMs. Still well within normal for CLIs that
  ship a language runtime.

* feat: v0.19.0 Layer 3 — schema migrations for page_kind + chunk code metadata

Adds two migrations to unblock C6/C7 (query --lang, code-def, code-refs)
and the orphans/auto-link branching in later layers.

v25 (pages_page_kind):

- ALTER TABLE pages ADD COLUMN page_kind TEXT NOT NULL DEFAULT 'markdown'
  CHECK (page_kind IN ('markdown','code'))
- Postgres path uses ADD CONSTRAINT ... NOT VALID + VALIDATE CONSTRAINT
  in a separate statement so tables with millions of pages don't hold a
  write lock during the initial check. PGLite has no concurrent writers,
  so its variant uses the simpler ALTER TABLE pattern.
- Existing rows carry DEFAULT 'markdown' — pre-v0.19 brains were
  markdown-only by definition.

v26 (content_chunks_code_metadata):

- ALTER TABLE content_chunks ADD COLUMN language, symbol_name,
  symbol_type, start_line, end_line (all nullable).
- Two partial indexes: idx_chunks_symbol_name WHERE symbol_name IS NOT
  NULL, and idx_chunks_language WHERE language IS NOT NULL. Only code
  chunks populate these columns, so partial indexes stay small even on
  a 50K-chunk brain with mixed markdown+code.
- Markdown chunks leave all five columns NULL. Only importCodeFile
  populates them, from the tree-sitter AST via chunkCodeText.

Wiring (both engines):

- PageInput gains `page_kind?: PageKind` ('markdown' | 'code'). Defaults
  to 'markdown' when omitted so existing callers don't change. putPage
  on both engines writes it through, with ON CONFLICT DO UPDATE updating
  page_kind alongside the other fields.
- ChunkInput gains language, symbol_name, symbol_type, start_line,
  end_line (all optional). upsertChunks on both engines writes them
  through. Existing markdown call sites pass nothing and get NULLs —
  zero behavior change for markdown pages.

importCodeFile updates:

- Sets page_kind='code' on the PageInput.
- Populates chunk metadata from the chunker's CodeChunk.metadata for
  every chunk it persists. Columns line up 1:1 with the tree-sitter AST
  output already produced by the chunker.
- Folds CHUNKER_VERSION=2 into content_hash so chunker shape changes
  across releases force clean re-chunks without `sync --force`. The
  hash was previously {title, type, content, lang} — now also
  chunker_version.

Fresh-install path (src/schema.sql + pglite-schema.ts):

- Both include the page_kind column + CHECK constraint.
- Both include the five new content_chunks columns.
- Both ship the partial indexes so new brains have the same query
  performance as migrated brains. Ran `bun run build:schema` to
  regenerate src/core/schema-embedded.ts from schema.sql.

Naming: renamed our new Error subclass in src/core/errors.ts from
GBrainError to StructuredAgentError. The legacy GBrainError in
src/core/types.ts predates this change and has a different shape
(positional problem/cause/fix arguments) — keeping both under the same
name was inviting a year of import ambiguity. New v0.19.0 surfaces use
StructuredAgentError + the serializeError() helper.

Tests:

- test/migrations-v0_19_0.test.ts — 12 cases. Covers: MIGRATIONS array
  shape (v25/v26 presence, NOT VALID pattern on Postgres, partial
  index WHERE clauses), fresh-install schema (page_kind default, CHECK
  constraint rejects invalid values, chunk metadata nullable), putPage
  round-trip (markdown default + code explicit), upsertChunks
  round-trip (code metadata preserved + markdown chunks leave NULLs).
- All 139 existing + new unit tests pass on PGLite (1.5 sec).

* feat: v0.19.0 Layer 4 — delete Wintermute's multi-repo, wire sources

Replaces Wintermute's short-lived repos abstraction with the v0.18.0
sources subsystem. Codex flagged this during plan review: v0.18.0's
sources table had already shipped the right shape (per-source
last_commit, federated search config, RLS-friendly) while Wintermute
coded against a ~/.gbrain/config.json repos array. Two systems solving
one problem.

Keep the surface, swap the backend:

- src/cli.ts: `gbrain repos` routes through runSources with a one-line
  deprecation nudge on stderr. Scripts like `gbrain repos list` and
  `gbrain repos add .` keep working against the sources table. Removed
  the pre-engine-connect branch and added a case inside the
  handleCliOnly switch so repos gets the DB connection it now needs.
- src/cli.ts help text: new SOURCES section replaces MULTI-REPO.
  References the canonical `sources` commands with `repos` tagged
  DEPRECATED.

sync --all — was iterating ~/.gbrain/config.json repos; now iterates
sources rows with local_path IS NOT NULL:

- Reads id, name, local_path, config jsonb via executeRaw.
- Honors config.syncEnabled=false (matching Wintermute's opt-out).
- Honors config.strategy for per-source markdown/code/auto filtering.
- Passes sourceId through to performSync so last_commit tracking lands
  on the right sources row (was clobbering a global bookmark before).

Deletions:

- src/core/multi-repo.ts deleted (120 lines of config CRUD now handled
  by sources table + RLS).
- src/commands/repos.ts deleted (121 lines of CLI parsing now handled
  by src/commands/sources.ts).
- test/multi-repo.test.ts deleted (25 tests against the deleted module;
  the schema-backed behavior is covered by test/sources.test.ts from
  v0.18.0 + test/repos-alias.test.ts added here).
- src/core/config.ts: removed the `repos` field from GBrainConfig.
  Legacy installs with `repos` in ~/.gbrain/config.json will see that
  key ignored; no migration written because zero users are on that
  path (Wintermute's commit never shipped on master).

Tests:

- test/repos-alias.test.ts — round-trips add/list/remove through
  runSources to verify the alias path works. Also asserts the deleted
  module is actually gone (catches accidental resurrection during
  rebase conflicts).
- All 162 prior unit tests + 2 new = 164 pass on PGLite.

Codex's P0 #2 (per-repo sync state) and P0 #3 (slug collision) are
both resolved here — sources.last_commit scopes bookmarks per source,
and pages.slug uniqueness is (source_id, slug), which is what the
v0.18.0 schema already shipped.

* feat: v0.19.0 Layer 5 — Chonkie chunker parity (E2a)

Expands Wintermute's 6-language chunker to 29 languages, swaps the
heuristic tokenizer for the real thing, and adds small-sibling merging
so a file of 20 tiny const declarations doesn't produce 20 embedding
calls. This closes the Chonkie gap Garry called out in CEO review.

Language coverage — 6 → 29:

- Added grammars: rust, java, c_sharp, cpp, c, php, swift, kotlin,
  scala, lua, elixir, elm, ocaml, dart, zig, solidity, bash, css,
  html, vue, json, yaml, toml. All shipping in src/assets/wasm/
  (committed in Layer 2). Bun's --compile bundles every import
  attributes path, so the compiled binary carries every grammar.
- TOP_LEVEL_TYPES populated for the 11 most-used new languages
  (rust, java, c_sharp, cpp, c, php, swift, kotlin, scala, lua,
  elixir, bash, solidity) + the original 6. Tree-sitter loads the
  grammar but the chunker falls through to recursive chunking when
  TOP_LEVEL_TYPES isn't set — still correct output, just less
  semantic. Every grammar ships with a working fallback.
- detectCodeLanguage extended for 29 extension families including
  .mts/.cts (TypeScript), .cc/.hpp/.cxx (C++), .kt/.kts (Kotlin),
  .scala/.sc (Scala), .ex/.exs (Elixir), etc.
- DISPLAY_LANG table lookup replaces the inline 6-entry map;
  structured headers now read '[Rust]', '[C#]', '[PHP]' etc.

Accurate tokenizer:

- @dqbd/tiktoken with cl100k_base encoding (same encoder
  text-embedding-3-large uses). Lazy-loaded on first call via
  require() so dev and compiled binary share the init path.
- Falls back to the old len/4 heuristic only if the encoder fails
  to initialize (vanishingly unlikely — keeps the chunker available
  instead of throwing).
- Existing estimateTokens call sites (large-node threshold +
  sub-range splitting + new merge pass) all now see real counts.
  Real code is 2-3x more token-dense than prose; the old heuristic
  systematically under-split so large functions sometimes exceeded
  the embedding API's 8191-token hard cap.

Small-sibling merging:

- New mergeSmallSiblings post-pass runs on the chunk list after
  tree-sitter extraction.
- Adjacent chunks under 40% of chunkSizeTokens get accumulated
  into one merged chunk up to the full budget.
- Large chunks (functions, classes) pass through untouched.
- Merged chunks get symbolName=null, symbolType='merged',
  startLine/endLine spanning the group. The header reads:
  '[Lang] path:N-M merged (K siblings)' so retrieval can still
  show coherent context.
- Mirrors Chonkie's CodeChunker._group_child_nodes() +
  bisect_left accumulation. A Go file with 30 top-level imports +
  5 functions no longer produces 30 separate import chunks.

CHUNKER_VERSION bumped 2 → 3:

- Any existing v0.18.x brain with code pages will re-chunk on next
  sync because content_hash folds CHUNKER_VERSION in. Without the
  bump, stale (2-3x token-off, non-merged) chunks would persist
  forever until manual 'sync --force'.

CI guard + smoketest updates:

- scripts/chunker-smoketest.ts replaced the tiny hello/Foo/Id
  fixture with a realistic TS snippet (calculateScore with branches
  + UserRegistry class) so at least one chunk has a concrete symbol
  name — small-sibling merging would otherwise collapse the old
  fixture and fail the assertion.
- scripts/check-wasm-embedded.sh assertions updated: check
  has_symbol_names:true (at-least-one-real-symbol), still verify
  [TypeScript] header and specifically the calculateScore symbol.

Tests — test/chunkers/code.test.ts (15 cases):

- CHUNKER_VERSION=3 shape assertion (guards silent re-chunking
  across releases).
- detectCodeLanguage across 29 extensions + unknown + case-insensitive.
- chunkCodeText on TypeScript / Python / Rust / Go producing chunks
  with correct language tag + symbol names.
- Fallback path for unsupported extension produces recursive-chunk
  module-kind output.
- Small-sibling merging: 5 tiny consts → 1-2 chunks; big function
  passes through untouched; merged chunk line range spans group.
- Structured header shape: starts with [Lang], contains file path,
  line range, symbol name.
- Empty input returns empty array.

All 177 unit tests pass + CI guard on compiled binary passes.

* feat: v0.19.0 Layer 6 — incremental chunking + doc↔impl linking

Two expansions from the plan's E1 + E2. E3 (markdown fence extraction)
deferred to a follow-up PR — the feature surface is small and doesn't
block the main cathedral.

E1 — Design-doc ↔ implementation linking:

- New extractCodeRefs() in src/core/link-extraction.ts. Scans markdown
  prose for references like 'src/core/sync.ts:42'. Anchored on a
  prefix allowlist (src|lib|app|test|tests|scripts|docs|packages|
  internal|cmd|examples) + the 39-extension code file list so random
  phrases like 'foo/bar.js' don't generate false-positive edges. Dedups
  by path (first occurrence wins).
- importFromContent writes bidirectional edges for every code ref
  found in compiled_truth + timeline:
    markdown_slug --[documents]--> code_slug
    code_slug     --[documented_by]--> markdown_slug
  Both use link_source='markdown', origin_page_id=markdown_slug,
  origin_field='compiled_truth' so runAutoLink reconciliation scopes
  edges correctly.
- addLink's inner SELECT naturally drops edges to non-existent pages,
  so a markdown guide imported before the code repo is synced writes
  no edges — they'll land when the code arrives via A3 reverse-scan
  (deferred to a follow-up since it only activates for users who sync
  markdown and code in opposite order).

E2 — Incremental chunking:

- importCodeFile reads existing chunks via engine.getChunks(slug)
  before embedding.
- Keys existing chunks by `${chunk_index}:${chunk_text}`. Any new
  chunk that matches verbatim at the same index reuses the existing
  embedding (chunk.embedding + token_count). Only new/changed chunks
  go to embedBatch.
- Cost impact: a daily autopilot on a stable repo touches ~2-5% of
  chunks on each run. E2 cuts OpenAI embedding spend by ~95% vs
  naive full re-embed. Stated before (Codex A2 decision) and now
  actually implemented.
- Uses chunk_index + chunk_text as the key (not symbol_fqn) because
  the tree-sitter chunker already makes chunk_index semantic — it's
  AST-order. A blank line at the top of a file shifts start_byte
  for every chunk below but leaves chunk_text identical, so the
  cache still hits.
- Fallback: when embedBatch throws (rate-limit, network, etc.) the
  existing warn-but-continue behavior stays. Un-embedded chunks land
  in the DB with NULL embedding; a later `embed --stale` will fix
  them.

Tests (test/link-extraction-code-refs.test.ts, 10 cases):

- :line suffix capture.
- Prefix allowlist (11 directories).
- Extension recognition (39 extensions).
- Rejects paths outside allowlisted prefixes.
- Rejects non-code extensions.
- Dedup by path (first occurrence wins).
- Different paths coexist.
- Real-markdown integration: guide with 4 code refs (one with line
  number) produces the right set of paths.
- Doesn't match URL-like strings (word-boundary behavior).

Tests (test/incremental-chunking.test.ts, 3 cases):

- Identical content re-import skips entirely (content_hash match).
- Editing ONE function in a 3-function file preserves the other two
  chunks verbatim (same chunk_text in DB). Verifies the cache-hit
  path actually works end-to-end on PGLite.
- Fresh-file import embeds all chunks (nothing to reuse).

All 189 unit tests pass on PGLite.

* feat: v0.19.0 Layer 7 — code-def + code-refs CLI surfaces

Delivers the magical-moment commands for v0.19.0 code indexing. These
are the agent-facing endpoints that turn 'brain-first lookup' from a
markdown-only Iron Law into something that covers code too.

gbrain code-def <symbol>:

- Queries content_chunks.symbol_name = $1 AND page_kind = 'code' AND
  symbol_type IN (function, class, interface, type, enum, struct,
  trait, module, contract, export statement).
- Orders by symbol_type rank (function first, then class, etc.) then
  page slug then line number — deterministic across runs.
- --lang <language> filter narrows to a single language.
- --limit N caps results (default 20).
- Returns Array<{ slug, file, language, symbol_type, start_line,
  end_line, snippet }> — the 7-field shape the agent persona needs.

gbrain code-refs <symbol>:

- Bypasses the standard searchKeyword path, which uses DISTINCT ON
  (slug) to collapse results to one chunk per page. That collapse is
  right for markdown search but wrong for code-refs — a single file
  typically has many usage sites, each interesting to the agent.
- Direct ILIKE scan over content_chunks + JOIN pages WHERE page_kind
  = 'code'. Word-boundary precision is a follow-up (would need
  tsvector or regex); for v0.19.0 the substring heuristic is good
  enough because symbol names are distinctive by design.
- Same --lang / --limit / --json flag surface as code-def.
- Returns Array<{ slug, file, language, symbol_name, symbol_type,
  start_line, end_line, snippet }> — 8 fields (code-def + the
  containing symbol_name).

Agent-DX doctrine (from DX review):

- Auto-JSON on pipe: both commands emit JSON when stdout is not a
  TTY (gh-CLI convention). Explicit --json forces JSON on TTY;
  --no-json forces human output even when piped.
- Structured error envelope: missing symbol argument returns
  { class: 'UsageError', code: '..._requires_symbol', hint: '...' }
  serialized as JSON in non-TTY mode, plain message in TTY.
  Catch-all DB error path uses serializeError() — no raw stack
  traces leak to the agent.

Tests — test/code-def-refs.test.ts (10 cases):

- Seeds a fixture repo (two TS files with deliberately large symbols
  to stay independent under small-sibling merging).
- findCodeDef:
    - Resolves interface + function by name to the right file.
    - Empty-symbol query returns [].
    - Language filter narrows to typescript; python returns [].
- findCodeRefs:
    - Finds multiple usage sites across files (both src/engine.ts
      and src/sync.ts appear when searching for BrainEngine — this
      is the DISTINCT ON bypass working).
    - Deterministic ordering by slug + line number.
    - Unknown symbol returns [].
    - --limit caps result count.
    - Snippets are <= 500 chars (the agent doesn't get flooded).

CLI wiring:

- Added 'code-def', 'code-refs' to CLI_ONLY.
- New switch cases in handleCliOnly call runCodeDef / runCodeRefs.
- Help text gains a CODE INDEXING (v0.19.0) section.

All 199 unit tests pass.

Deferred from Layer 7 per the cathedral plan:
- sync --all cost preview with TTY detection — requires folding the
  tokenizer into the sync path. Pushed to a follow-up.
- query --lang filter — requires changes to src/core/search/*.ts.
  Pushed to a follow-up.

* feat: v0.19.0 Layer 8 — BrainBench code category (E2E)

Retrieval-quality gate for v0.19.0 code indexing. Seeds a ~25-file
fictional corpus across 5 languages (TS, Python, Go, Rust, Java),
imports each via importCodeFile, and asserts code-def + code-refs
produce the expected shape. Runs against PGLite in-memory so no
OpenAI key or external Postgres is needed; reproducible on CI with
just Bun.

What the E2E covers:

- Corpus seeded: 25+ code pages, all page_kind='code'.
- code-def finds AuthService across multiple languages (≥2 of
  TS/Rust/Java).
- code-def --lang typescript filters precisely (P@5=1.0 for
  CacheService + typescript).
- code-refs surfaces multiple usage sites across files (the
  DISTINCT ON bypass working in practice).
- code-refs over the shared "start" method across 5 languages
  produces ≥3 language hits (ranking stability).
- Magical-moment assertion: code-refs completes in <500ms on a
  25-file corpus (budget is 100ms; 500ms pad absorbs CI variance).
- MRR sanity: top result for exact symbol is the defining file.
- Edge cases: non-existent symbol returns [], not error. Language
  filter with zero matches returns []. Re-import is idempotent.

Chunker retune:

- Small-sibling merge threshold dropped from 40% to 15% of
  chunkSizeTokens. The 40% figure was collapsing 3-method classes
  into 'merged' chunks, killing symbol_name lookups for the entire
  class. 15% matches the original intent: merge truly tiny
  declarations (const X = 1; import ... from ...;) while leaving
  substantive symbols (functions, classes) independent. Verified
  by the BrainBench test — AuthService is now its own chunk with
  symbol_name='AuthService', so findCodeDef('AuthService') resolves.
- Unit test updated: 10 consts with a generous chunkSizeTokens=1000
  still exercise the merge path.

Total v0.19.0 unit + E2E coverage: 91 tests across 9 new test
files, 357 assertions, all green.

* feat: v0.19.0 Layer 9 — release: CHANGELOG + migration + docs

Closes out the v0.19.0 cathedral. Total shipped across 10 layers:

- 91 new unit + E2E tests (9 new files, 357 assertions, all green)
- 2 schema migrations (v25 pages.page_kind + v26 content_chunks code metadata)
- 4 new CLI surfaces (repos [alias] + code-def + code-refs +
  sources passthrough)
- 1 new core module (src/core/errors.ts)
- 36 tree-sitter grammar WASMs embedded via Bun --compile
- 1 CI guard preventing silent-chunker regression
- Wintermute's multi-repo replaced with v0.18.0 sources backend

CHANGELOG.md — release-summary section in the GStack/Garry voice per
CLAUDE.md "Release-summary template": bold two-line headline + lead
paragraph + "The numbers that matter" table + "What this means for
builders" + itemized changes + "To take advantage of v0.19.0" block.
No em dashes, no AI vocabulary, no banned phrases. Numbers are from
the v0.19.0 test-fixture benchmarks.

CLAUDE.md — four new file entries in the Key files section
(src/core/chunkers/ annotated with v0.19.0 additions, src/core/errors.ts,
src/assets/wasm/, src/commands/code-def.ts + code-refs.ts).

skills/migrations/v0.19.0.md — agent-readable migration walkthrough
per the v0.11.0 convention. Tells the agent what to do after
`gbrain upgrade` runs the orchestrator: verify schema v26, register a
code source via `gbrain sources add`, run `sync --source <id>`,
confirm `gbrain code-def` / `code-refs` both work. Notes the deprecated
`gbrain repos` alias for scripts that used Wintermute's baseline.
Flagged in pending-host-work.jsonl per the v0.11.0 convention so
headless agents surface the prompt.

VERSION — 0.18.2 → 0.19.0.

All 91 v0.19.0 tests + the CI guard pass.

* docs: v0.19.0 — add 4 deferred follow-ups to TODOS.md

Lands the four items the v0.19.0 cathedral explicitly scoped out but
that the /plan-ceo-review + /plan-devex-review + /plan-eng-review chain
identified as genuine follow-ups rather than abandoned ideas.

Items added under a new 'code-indexing (v0.19.0 follow-ups)' section:

- P1 — sync --all cost preview with TTY detection. Closes DX fix #1
  from the /plan-devex-review pass: the agent persona can't respond
  to stdin prompts. Non-TTY path must emit a parseable
  ConfirmationRequired envelope; TTY path uses [y/N]. File refs:
  src/commands/sync.ts:590, src/core/chunkers/code.ts estimateTokens,
  src/core/errors.ts buildError.

- P2 — query --lang filter through src/core/search/*.ts. Column
  ships in v0.19.0 (migration v26 + partial index); the query path
  just needs to respect it. Keeps ranking honest when the user
  knows the language. File refs: src/core/search/, pglite-engine
  searchKeyword, test/e2e/code-indexing.test.ts language-filter
  pattern.

- P2 — E3 markdown code-fence extraction. After parseMarkdown,
  iterate marked's lexer tokens for { type: 'code', lang, text }
  and chunk each through chunkCodeText with chunk_source='fenced_code'.
  ~40% of gbrain's brain is guides with substantial inline code —
  this lands those fences as first-class TS/Python/Go chunks in
  search instead of treating them as prose.

- P2 — A3 reverse-scan backfill for doc↔impl. Companion piece to
  E1. Markdown-first → code-later import order currently loses edges
  because addLink's JOIN drops them when the code page doesn't exist
  yet. A3 makes importCodeFile scan existing markdown for
  references to the new code path and backfill edges both
  directions. Trade-off: per-file scan is expensive on first sync;
  batch 'gbrain reconcile-links' is an alternative shape.

Each entry follows the CLAUDE.md TODOS format: What/Why/Pros/Cons/
Context with exact file refs/line numbers/Effort (S/M/L + human vs
CC)/Depends on. All four are purely additive on top of v0.19.0 —
nothing blocks.

* fix: pre-existing test infrastructure + typecheck drift

Three pre-existing conditions surfaced when running the full suite and
blocked a clean CI floor for Cathedral II work:

1. `bun run test` default 5s hook timeout fails under load. PGLite WASM
   init can exceed 5s when many test files spin up instances in parallel.
   The bunfig.toml `timeout = 60_000` key is honored by `bun test` but
   does not propagate to beforeEach/afterEach hooks when `bun test` runs
   behind `bun run typecheck` in the CI chain. Pass `--timeout=60000`
   explicitly on the command line, where it covers both per-test and
   per-hook timeouts.

   Before:  2136 pass / 30 fail (on-branch baseline)
   After:   2272 pass /  0 fail

   All 30 failures were `beforeEach/afterEach hook timed out for this
   test` → `TypeError: undefined is not an object (evaluating
   'engine.disconnect')` — i.e. the hook never finished connecting
   PGLite, so the engine variable was never assigned, so afterEach
   tripped on `engine.disconnect()`. The new timeout gives PGLite
   WASM init enough headroom under concurrent load.

2. `test/repos-alias.test.ts` references the deliberately-deleted
   `src/core/multi-repo.ts` via a dynamic import inside a try/catch
   (the test asserts the module is no longer importable at runtime).
   TS 5.x module resolution flags this at typecheck time even inside
   try/catch. Build the path at runtime (`'../src/core/' +
   'multi-repo.ts'`) so TS's compile-time module resolution doesn't
   fail on a path the test is EXPLICITLY verifying doesn't resolve.

3. `llms-full.txt` drifted from `bun run build:llms` output (earlier
   CLAUDE.md updates in v0.19.0 never regenerated). `bun run build:llms`
   now produces matching output.

Zero behavior changes to production code. Test infrastructure only.

* feat: v0.20.0 Cathedral II Layer 1 — Foundation schema migration

Layer 1 of 14 for the v0.20.0 "best code search in the world" cathedral.
Ships all Cathedral II DDL atomically so downstream layers have the
columns + tables + trigger they depend on. Schema-only; no consumer
behavior changes until Layer 5 (A1 edge extractor).

Reordered to Layer 1 after codex second-pass review (SP-4): previously
Layer 0b (chunk-grain FTS trigger) referenced columns added in the
former Layer 3 (Foundation), breaking bisectability. All schema DDL
now lands first; every subsequent layer's prerequisites exist.

### What this migration adds (one idempotent v27 transaction)

1. `content_chunks` gains 4 new columns:
   - `parent_symbol_path TEXT[]` — scope chain for nested symbols (A3)
   - `doc_comment TEXT` — extracted JSDoc/docstring (A4)
   - `symbol_name_qualified TEXT` — 'Admin::UsersController#render' (A1)
   - `search_vector TSVECTOR` — chunk-grain FTS (Layer 1b consumer)
   All nullable; markdown chunks leave them NULL.

2. `sources.chunker_version TEXT` (SP-1 gate). Layer 10 will check this
   against CURRENT_CHUNKER_VERSION and force a full sync walk on
   mismatch, bypassing the git-HEAD up_to_date early-return that would
   otherwise make a bare CHUNKER_VERSION bump a silent no-op.

3. `code_edges_chunk` — resolved call-graph + reference edges.
   - `from_chunk_id` + `to_chunk_id` with FK CASCADE from content_chunks
   - UNIQUE (from_chunk_id, to_chunk_id, edge_type) holds idempotency
   - `source_id TEXT` matches `sources.id` actual type (codex F4 caught
     the prior UUID typo)
   - source scoping enforced in resolution logic, not the key, because
     from_chunk_id → pages.source_id already determines it

4. `code_edges_symbol` — unresolved refs. Target symbol known by
   qualified name; defining chunk not seen yet. Rows UNION with
   code_edges_chunk on read (codex 1.3b); no promotion step (SP-7).

5. `update_chunk_search_vector` trigger — BEFORE INSERT/UPDATE OF
   (chunk_text, doc_comment, symbol_name_qualified). Weights
   doc_comment and symbol_name_qualified at 'A', chunk_text at 'B'.
   Natural-language queries rank doc-comment hits above body text
   (A4 intent, delivered via the trigger from day one even though
   Layer 5 populates the doc_comment column).

### Engine interface + types

- `BrainEngine` gains 6 new methods for code edges, all stubbed in
  both engines with explicit NotImplemented errors pointing at the
  layer that will fill them (5, 7, or 1b):
    addCodeEdges, deleteCodeEdgesForChunks, getCallersOf,
    getCalleesOf, getEdgesByChunk, searchKeywordChunks

- `CodeEdgeInput`, `CodeEdgeResult` types added to src/core/types.ts

- `SearchOpts` extended with Cathedral II fields: language, symbolKind,
  nearSymbol, walkDepth, sourceId (all optional; consumers wire in
  Layer 5/7/10)

- `ChunkInput` extended with: parent_symbol_path, doc_comment,
  symbol_name_qualified (populated by importCodeFile in Layer 5/6)

- `Chunk` read shape mirrors the added columns as optional fields

- `chunk_source` union widens to include 'fenced_code' for D2 fence
  extraction (Layer 6 consumer)

### Tests

`test/migrations-v0_20_0.test.ts` — 17 structural assertions against
the v27 migration registry. Covers every column + table + index + the
trigger weight shape. E2E migration-application coverage lands in
`test/e2e/cathedral-ii.test.ts` alongside Layer 5.

### Status

- CEO + Eng + 2 codex passes CLEARED (see docs/designs/CODE_CATHEDRAL_II.md)
- 16 cross-model findings absorbed (7 codex pass 1 + 6 codex pass 2
  + 3 eng review)
- 13 more layers to go (0a → 14); see plan for full sequencing.

* feat: v0.20.0 Cathedral II Layer 2 (1a) — file-classifier widening + SP-5 slug dispatch

Codex F1: `sync.ts:35` v0.19.0 classified only 9 extensions as code.
Rust/Java/C#/C++/Swift/Kotlin/etc. never reached the chunker on a
normal repo sync, making v0.19.0's "29 languages" claim aspirational
on the read path. Layer 2 widens the classifier so every language the
chunker knows (~35 extensions) actually reaches it during sync.

### Changes

1. `src/core/sync.ts` CODE_EXTENSIONS widened from 9 to 35 extensions,
   matching the chunker's detectCodeLanguage coverage: adds .rs, .java,
   .cs, .cpp/.cc/.cxx/.hpp/.hxx/.hh, .c/.h, .php, .swift, .kt/.kts,
   .scala/.sc, .lua, .ex/.exs, .elm, .ml/.mli, .dart, .zig, .sol,
   .sh/.bash, .css, .html/.htm, .vue, .json, .yaml/.yml, .toml,
   .mts/.cts.

2. `src/core/sync.ts` adds `resolveSlugForPath(path)` — SP-5 fix.
   Before Cathedral II, sync delete/rename paths called
   `pathToSlug(path)` with default pageKind='markdown'. For the 9-ext
   classifier this was mostly fine (code files rare), but widening to
   35 exts means Rust/Java/Ruby/etc. deletes and renames would mismatch
   on slug shape (pathToSlug markdown-style vs slugifyCodePath
   code-style). resolveSlugForPath dispatches on isCodeFilePath so
   delete/rename always hit the right page. Used in `src/commands/sync.ts`
   at the three slug-resolution sites (un-syncable delete, batch delete,
   rename from/to).

3. `src/core/chunkers/code.ts` adds `setLanguageFallback(fn)` +
   optional `content` arg to `detectCodeLanguage(path, content?)`.
   Pre-wires the Magika fallback hook that Layer 9 (B2) will consume
   for extension-less files (Dockerfile, Makefile, shell shebangs).
   Null default → no behavior change today; Layer 9 sets it at bootstrap.
   Fallback throws are swallowed (recursive chunker is always an
   acceptable degradation).

### Tests

- `test/sync-classifier-widening.test.ts` — 20 cases covering the full
  widened extension set, resolveSlugForPath dispatch, and the Magika
  fallback hook contract (including throw-swallow and null-pass-through).

- `test/sync-strategy.test.ts` updated: `.json` is no longer rejected
  (the chunker's language map includes JSON for structured-data
  chunking). Test clarifies Cathedral II semantics; adds .svg + .zip
  as non-code examples.

### CI result

2292 pass / 0 fail via `bun run test`, 388s wall time.

* feat: v0.20.0 Cathedral II Layer 3 (1b) — chunk-grain FTS with page-grain wrap

Codex F2 caught that v0.19.0's searchKeyword ranked via pages.search_vector,
so doc-comment content living on a chunk couldn't influence ranking and A2
two-pass retrieval had no way to find the best matching chunk. Layer 3
moves the FTS primitive to content_chunks.search_vector (the column +
trigger added in Layer 1/v27), dedups-to-best-chunk-per-page on return
so every external caller still sees the v0.19.0 page-grain contract
(SP-6), and exposes searchKeywordChunks as the raw chunk-grain primitive
A2 two-pass will consume (Layer 7).

### Backfill migration v28

Layer 1's trigger only fires on INSERT/UPDATE — rows inserted before v27
applied had NULL search_vector. v28 backfills every existing chunk with
the same weight shape the trigger uses (doc_comment + symbol_name_qualified
at weight A, chunk_text at B). Idempotent via `WHERE search_vector IS NULL`;
re-runs pick up only remaining NULL rows. ~2-3s on a 20K-chunk brain.

### searchKeyword rewrite (both engines)

CTE chain: rank chunks by cc.search_vector → DISTINCT ON (slug) picks
best chunk per page → order by score → limit. External shape identical
to v0.19.0: one row per matched page, score comes from the best chunk
on that page, chunk metadata attached. Zero breaking changes for
backlinks counting, enrichment-service.countMentions, list_pages, etc.

Inner fetch limit is 3x the requested page limit so dedup has enough
chunks to produce N distinct pages (a co-occurring-term cluster in one
page can't eat the result set).

Postgres keeps the SET LOCAL statement_timeout='8s' from v0.12.3 search
timeout scoping. PGLite gets the same CTE shape minus the transaction-
scoped GUC (PGLite has no pool).

### searchKeywordChunks (new internal primitive)

Same chunk-grain ranking WITHOUT dedup. Returns raw top-N chunks by
FTS score regardless of page. Used by A2 two-pass retrieval (Layer 7)
as its anchor-discovery primitive — two-pass wants top chunks, not
best-per-page. Most callers should prefer searchKeyword.

### Tests

- test/chunk-grain-fts.test.ts: 11 cases covering migration v28 shape,
  page-grain external contract (dedup preserves invariants), chunk-grain
  primitive (no dedup, score-ordered), and the doc-comment weight-A
  precedence over body weight-B — the A4 ranking win validated today
  even though Layer 5 is what populates doc_comment from AST.

- test/pglite-engine.test.ts existing "tsvector trigger populates
  search_vector on insert" updated: v0.19.0 searched pages.search_vector
  (built from title + compiled_truth) so two-word queries matching
  non-chunk text worked. Cathedral II ranks chunks only — test updated
  to search 'AI agents' which is in the chunk_text directly.

- test/migrations-v0_20_0.test.ts "v27 is highest" relaxed to
  "v27 is the foundation migration; max >= 27" so later layers can
  land migrations without breaking this assertion.

### CI result

2553 tests / 0 fail via `bun test --timeout=60000`, 422s wall time.

* feat: v0.20.0 Cathedral II Layer 4 (B1) — language manifest foundation

Consolidate the 29-way GRAMMAR_PATHS + parallel DISPLAY_LANG record into
a single LANGUAGE_MANIFEST keyed on SupportedCodeLanguage. Each entry is
a LanguageEntry with { displayName, embeddedPath?, lazyLoader? }.

### Why this matters for Cathedral II

Before: adding a language meant editing two maps (path + display name)
AND adding a new `import G_X from ...` at the top, for every new lang.

After: one manifest entry + one `with { type: 'file' }` import (embedded)
or one registerLanguage() call at boot (lazy). loadLanguage() consults
the manifest uniformly — it doesn't know or care whether a grammar is
embedded in the compiled binary or resolved from node_modules at runtime.

### The 3 extension points

- `embeddedPath` — Bun `with { type: 'file' }` asset. Ships with
  `bun --compile` output; already in place for the 29 core grammars.

- `lazyLoader` — async function returning path or Uint8Array. Used at
  first reference, then cached in `languageCache` like embedded grammars.
  Forward-compat for v0.20.x+ full tree-sitter-wasms (~136 more langs).

- `registerLanguage(lang, entry)` / `unregisterLanguage(lang)` /
  `listRegisteredLanguages()` — runtime registration hook. Layer 9
  (B2 Magika) will wire detection for extensionless files through
  this API. Dynamic registrations win over core manifest on conflict
  so hot-fix overrides during a session work without restart.

### Behavior guarantees preserved

- All 29 v0.19.0 core grammars continue to ship embedded — no binary-size
  growth, no runtime network dependency for the core set.
- `detectCodeLanguage` untouched; its output key still maps 1:1 through
  LANGUAGE_MANIFEST.
- `displayLang()` now derived from the manifest. Chunk headers read
  "[Python]" / "[TypeScript]" / "[Ruby]" just as before — one source of
  truth, manifest-derived.

### Tests (test/language-manifest.test.ts, 8 cases)

- Manifest covers all 29 v0.19.0 languages (typescript/tsx/js/py/rb/go/
  rust/java/c_sharp/cpp/c/php/swift/kotlin/scala/lua/elixir/elm/ocaml/
  dart/zig/solidity/bash/css/html/vue/json/yaml/toml).
- registerLanguage does NOT invoke the lazy loader at registration time
  (proves the loader fires at most on first chunkCodeText() call).
- Dynamic registrations override core manifest entries (hot-fix path).
- unregisterLanguage removes a dynamic entry and clears its parser cache.
- chunkCodeText still loads core grammars (TypeScript / Python / Ruby)
  end-to-end; chunk headers use the manifest displayName ("[Python]",
  not "[python]").

### What's NOT shipped here

Adding the additional ~136 languages from tree-sitter-wasms is
deliberate v0.20.x+ follow-up work. The manifest infrastructure is in
place; expanding coverage is now a data-only PR (one entry per language).

### CI result

2561 tests / 0 fail via `bun test --timeout=60000`, 425s wall time.

* feat: v0.20.0 Cathedral II Layer 8 D1 — sync --all cost preview + ConfirmationRequired envelope

Closes the v0.19.0 DX review's #1 pain point: "first sync surprise bill."
Before Cathedral II, `gbrain sync --all` on a fresh multi-source brain
could spin up tens of thousands of OpenAI embedding calls before anyone
saw a cost number. Agent callers (OpenClaw, Hermes, etc.) had no way
to gate the operation behind a spend check.

### Behavior

Before `sync --all` touches a single source, walk the working trees of
every registered source with `local_path`, sum tokens per file via the
same cl100k_base tokenizer text-embedding-3-large actually uses, and
compute a USD estimate. Gate on that:

- **TTY + !--json + !--yes** → interactive `[y/N]` prompt.
- **non-TTY OR --json OR piped** → emit `ConfirmationRequired` envelope
  to stdout via the v0.18 `errorFor` builder, exit code 2. Reserves
  exit 1 for runtime errors so agent callers can distinguish
  "awaiting user call" from "something crashed."
- **--yes** → skip prompt entirely. Agent/CI path.
- **--dry-run** → print preview, exit 0 without syncing.
- **--no-embed** → skip the cost gate entirely (user already opted out
  of OpenAI spend; they'll run `embed --stale` later).

### Preview shape

One stderr line or one JSON payload:

    sync --all preview: <N> files across <M> source(s),
    ~<T> tokens, est. $<X> on text-embedding-3-large.

Conservative overestimate: full working-tree content, not just the
incremental diff. A source never embedded before WILL embed everything
on first sync; already-synced sources with small diffs get a ceiling,
not a floor. False-high bias is intentional — users never get
surprised by MORE cost than the preview claimed.

### Files

- `src/core/chunkers/code.ts`: `estimateTokens` now exported (was
  module-private). Same cl100k_base tokenizer, just a public symbol.
- `src/core/embedding.ts`: add `EMBEDDING_COST_PER_1K_TOKENS = 0.00013`
  + `estimateEmbeddingCostUsd(tokens)`. Single source of truth for
  cost math; every cost-preview surface reads this constant, so a
  pricing change is a one-line edit.
- `src/commands/sync.ts`:
  - new `estimateSyncAllCost(sources)` helper walks trees, sums
    tokens per active source, returns breakdown.
  - new `walkSyncableFiles(repo, cb, strategy)` recursive walker.
    Honors the same `isSyncable` rules as the real sync so preview
    and execution agree on scope. Skips hidden dirs, node_modules,
    ops/, and files over 5MB. Best-effort file-read errors don't
    block the preview.
  - new `promptYesNo(question)` readline wrapper — resolves false
    on non-'y' answer OR EOF.
  - `--yes` and `--json` flags parsed at sync argv layer.
  - cost preview runs before the per-source sync loop on `--all`,
    gates via the TTY / --json / --yes / --dry-run matrix above.

### Tests

`test/sync-cost-preview.test.ts` (6 cases):
- EMBEDDING_COST_PER_1K_TOKENS pinned to $0.00013.
- `estimateEmbeddingCostUsd` scales linearly across 0 → 1M tokens.
- `estimateTokens` round-trips (empty → 0, short → <10, 100x text → >50x).

### CI result

2567 tests / 0 fail via `bun test --timeout=60000`, 424s wall time.

* feat: v0.20.0 Cathedral II Layer 8 D2 — markdown fence extraction

~40% of gbrain's brain is docs + guides + architecture notes with
substantial inline code. In v0.19.0 those fenced code blocks chunked as
prose, so querying "how do we handle errors in TypeScript" ranked
paragraphs ABOUT the import above the actual import example. D2 walks
the marked lexer tokens, extracts each recognized code fence, and
persists them as extra chunks on the parent markdown page with
`chunk_source='fenced_code'` and full code-metadata (language,
symbol_name, symbol_type, start/end line).

### Behavior

In `importFromContent`, after `parseMarkdown` returns compiled_truth,
we additionally run the text through `marked.lexer()` and walk for
`{ type: 'code', lang, text }` tokens. For each:

- Map the fence language tag (`ts`/`typescript`/`js`/...) to a
  pseudo-path (`fence.ts`/`fence.js`/...) so `detectCodeLanguage`
  picks the right grammar.
- Call `chunkCodeText(text, pseudoPath)` — one or more code chunks
  depending on fence size. Tree-sitter-aware chunking means a big
  TS fence splits at function boundaries, not character count.
- Persist each chunk with `chunk_source='fenced_code'`. Extends the
  existing chunk_source enum; schema allows it via the TEXT column.

### Fence-bomb DOS guard

`MAX_FENCES_PER_PAGE = 100` by default, overridable via
`GBRAIN_MAX_FENCES_PER_PAGE` env var. A malicious markdown page with
10K ```ts blocks could otherwise force 10K embedding API calls.
Beyond the cap, remaining fences skip with a one-line console warn
so operators can see the event.

### Per-fence error isolation

Each fence runs through its own try/catch. One malformed fence (e.g.
marked lexer choking on edge-case markdown) doesn't abort the whole
page import — the other fences + the prose chunks from
compiled_truth all still land.

### Recognized fence tags (29 languages + 7 aliases)

ts/typescript, tsx, js/javascript, jsx, py/python, rb/ruby,
go/golang, rs/rust, java, c#/cs/csharp, cpp/c++, c, php, swift,
kt/kotlin, scala, lua, ex/elixir, elm, ml/ocaml, dart, zig,
sol/solidity, sh/bash/shell/zsh, css, html, vue, json, yaml/yml,
toml.

Unknown tag → skipped (no synthetic chunk, no crash). Missing tag
(```\n...\n```) → skipped. Empty body → skipped.

### Collateral fix

`rowToChunk` in src/core/utils.ts now maps the code-chunk metadata
columns (language, symbol_name, symbol_type, start_line, end_line)
+ the v0.20.0 Cathedral II additions (parent_symbol_path,
doc_comment, symbol_name_qualified) out of the DB. Pre-Cathedral II
the code columns were written via upsertChunks but never read back
— caught by the new fence test assertions.

### Tests (test/fence-extraction.test.ts, 7 cases)

- TS fence → language='typescript' chunk
- Python fence → language='python', chunk_text contains def
- Ruby fence → language='ruby'
- Unknown tag (```mermaid, ```unknown-xyz) → no fenced_code chunks
- Missing tag → no fenced_code chunks
- 3 fences on one page, mix of langs → 3+ fenced_code chunks
- Empty fence body → no chunks

### CI result

2574 tests / 0 fail via `bun test --timeout=60000`, 434s wall time.

* feat: v0.20.0 Cathedral II Layer 8 D3 — reconcile-links batch command

Closes the v0.19.0 Layer 6 doc↔impl order-dependency: when a markdown
guide imports BEFORE the code it cites (common — docs land first, code
sync runs second), the Layer 6 E1 forward-scan calls addLink but its
inner JOIN silently drops the edge because the code page doesn't exist
yet. The guide and the code eventually both exist in the brain, but
the edge never materialized.

### New CLI surface

    gbrain reconcile-links [--dry-run] [--json]

Walks every markdown page, re-runs `extractCodeRefs` on
compiled_truth+timeline, and calls addLink(md, code, ..., 'documents')
+ reverse for each hit. ON CONFLICT DO NOTHING at the links table
makes the operation idempotent — existing edges stay, new edges land.

### Per-lang coverage via extractCodeRefs

Inherits the regex from `src/core/link-extraction.ts` which already
recognizes code paths for 29 extensions (ts/tsx/js/py/rb/go/rust/java/
c#/cpp/c/php/swift/kotlin/scala/lua/elixir/elm/ocaml/dart/zig/sol/sh/
css/html/vue/json/yaml/toml). Fence-extraction (D2) and classifier-
widening (Layer 2) keep this in sync with the chunker's actual reach.

### Why batch over per-import reverse-scan

Codex's two-pass review flagged per-import reverse-scan as O(N)
ILIKE/JOIN queries per code file imported — on a 47K-page brain first-
syncing 5K code files that's 5K ILIKE scans. A user-triggered batch
run on an already-synced brain is one walk, slug-indexed via addLink's
existing lookup. Same correctness, much faster.

### Behavior

- Dry-run: counts refs, attempts = 0, writes nothing.
- auto_link=false in config: returns status='auto_link_disabled' +
  no-op. Users who disabled auto-linking on put_page don't want
  reconcile-links silently re-populating edges either.
- Missing code target: counted as `edgesTargetsMissing`, not thrown.
  The ref exists in the guide, but the code page hasn't been synced
  yet. Re-run after the next code sync to materialize.
- Progress reporter: `reconcile_links.scan` phase, one tick per
  markdown page, with rolling summary `guides/foo (+N refs)` per tick.

### Tests (test/reconcile-links.test.ts, 6 cases)

- Extracts code refs and creates bidirectional edges (guide→code +
  code→guide).
- Idempotent: second run inserts zero new edges.
- Dry-run reports counts without writing.
- Markdown page with no code refs is a no-op.
- Respects auto_link=false.
- Missing code target is counted, not thrown.

### CI result

2580 tests / 0 fail via `bun test --timeout=60000`, 432s wall time.

* feat: v0.20.0 Cathedral II Layer 12 — CHUNKER_VERSION 3→4 + SP-1 gate

Codex's second-pass review caught that bumping CHUNKER_VERSION alone is a
silent no-op on an unchanged repo: performSync short-circuits at `up_to_date`
before reaching importCodeFile's content_hash check. Layer 12 adds a
sources.chunker_version gate that forces a full re-walk when the version
mismatches, regardless of git HEAD equality.

- CHUNKER_VERSION 3 → 4 (src/core/chunkers/code.ts:99), folded into
  content_hash via v0.19.0 Layer 5 wiring — any bump forces clean re-chunks.
- src/commands/sync.ts: readChunkerVersion/writeChunkerVersion helpers;
  version-mismatch gate runs BEFORE the up_to_date early-return and forces
  a full walk; writeChunkerVersion called after every last_commit anchor.
- test/chunker-version-gate.test.ts: 3 pinning tests (constant value,
  import stability, v27 migration shape).
- test/chunkers/code.test.ts: update v0.19.0 CHUNKER_VERSION=3 assertion
  to Cathedral II v0.20.0 CHUNKER_VERSION=4.

Full CI: 2333 pass / 250 skip / 0 fail / 6155 expect() / 408s.

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

* feat: v0.20.0 Cathedral II Layer 13 (E2) — reindex-code + migration orchestrator

Ships the user-facing explicit-backfill path. v0.19.0 → v0.20.0 brains get
CHUNKER_VERSION 3→4 rolled over automatically via Layer 12's gate on next
sync. Users who want the benefits NOW (before their next sync) run
`gbrain reindex-code --yes`.

- New src/commands/reindex-code.ts. runReindexCode(engine, opts) walks code
  pages from the DB in batches of 100 (Finding 4.4 OOM protection), reads
  compiled_truth + frontmatter.file, re-runs importCodeFile. --dry-run
  reports cost + token count without importing. --force bypasses
  importCodeFile's content_hash early-return. --source filters to one
  sources row. Pages without frontmatter.file fail cleanly (counted, not
  thrown). runReindexCodeCli parses argv, wires the D1 cost-preview gate
  (TTY prompt or ConfirmationRequired envelope for non-TTY/JSON), delegates.
- src/core/import-file.ts: importCodeFile gains opts.force flag. When
  true, skips the content_hash === hash early-return so a paranoid full
  reindex always re-chunks + re-embeds even when content hasn't changed.
- src/cli.ts: register 'reindex-code' case + CLI_ONLY entry.
- src/commands/migrations/v0_20_0.ts: orchestrator with 3 phases
  (schema → backfill_prompt → verify). Phase B prints the two backfill
  choices directly (automatic via sync vs immediate via reindex-code).
  Follows v0.12.2/v0.18.1 idempotent-resumable pattern.
- src/commands/migrations/index.ts: registers v0_20_0 after v0_18_1.
- skills/migrations/v0.20.0.md: agent-facing post-upgrade instructions.
- test/reindex-code.test.ts: 5 cases (count, dry-run, walk+failures,
  empty brain, batch pagination).
- test/migration-orchestrator-v0_20_0.test.ts: 5 cases (registry wiring,
  feature-pitch content, __testing exports, dry-run skips, is-latest).
- test/apply-migrations.test.ts: extend skippedFuture pins with 0.20.0.

Full CI: 2343 pass / 250 skip / 0 fail / 6193 expect() / 426s.

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

* feat: v0.20.0 Cathedral II Layer 10 partial (C1 + C2) — query --lang / --symbol-kind

Ships the cheap half of the C tier: language + symbol-kind filters on
hybrid search. The content_chunks.language and content_chunks.symbol_type
columns have existed since v0.19.0 Layer 5 (code chunker populates both);
Layer 10 exposes them as filter flags on the 'query' operation.

The expensive half (C3 --near-symbol, C4 code-callers, C5 code-callees) is
blocked on Layer 5 A1 edge extractor — those need the code_edges_chunk +
code_edges_symbol tables populated. They ship in a follow-up.

- src/core/pglite-engine.ts: searchKeyword / searchKeywordChunks /
  searchVector all accept opts.language + opts.symbolKind. Filters added
  via parameterized $N indices; unknown values return zero results
  (no false positives).
- src/core/postgres-engine.ts: same three methods, same filters, threaded
  through the postgres.js sql-fragment pattern. Honors SET LOCAL
  statement_timeout discipline.
- src/core/search/hybrid.ts: threads opts.language + opts.symbolKind into
  per-engine searchOpts so filters fire at SQL level (not post-filtered
  in-memory).
- src/core/operations.ts: query op params gain lang + symbol_kind entries.
  Handler maps them into hybridSearch opts.language / opts.symbolKind.
- src/cli.ts: updated --help CODE INDEXING section to list the new flags
  + reconcile-links + reindex-code commands.
- test/search-lang-symbol-kind.test.ts: 9 cases (no filter, lang-only,
  symbolKind-only, combined AND, searchKeywordChunks variant, unknown
  lang/kind return zero, operation schema check).

Full CI: 2352 pass / 250 skip / 0 fail / 6216 expect() / 432s.

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

* feat: v0.20.0 Cathedral II Layer 6 (A3) — parent-scope + nested-chunk emission

Ships the chunk-granularity change codex called out in the second-pass
review. Before Cathedral II, `export class BrainEngine { m1() {} m2() {} }`
emitted ONE chunk for the whole class. Retrieval returned the entire
class body for a symbol-specific query like "how does searchKeyword
work" — the agent had to re-read the whole thing. A3 extends the
chunker to emit each method as its own chunk carrying
`parentSymbolPath: ['BrainEngine']`, with a `(in BrainEngine)` suffix in
the header so the embedding captures scope context. The class-level
parent chunk still ships (slim body: declaration line + member digest)
so class-level queries still hit something.

Recursive expansion: Ruby `module Admin { class UsersController { def
render } }` emits 3 chunks — Admin (parent=[]), UsersController
(parent=[Admin]), render (parent=[Admin, UsersController]).

- src/core/chunkers/code.ts:
  - CodeChunkMetadata gains `parentSymbolPath?: string[]`.
  - NESTED_EMIT_CONFIG map per language (TS, TSX, JS, Python, Ruby,
    Rust impl blocks, Java class/interface/record). Maps parent types
    (class_declaration / class_definition / module / impl_item) to
    child types (method / method_definition / function_definition /
    singleton_method / constructor_declaration).
  - findNestableParent unwraps TS export_statement to reach the inner
    class_declaration — the export wrapper was a classic gotcha.
  - emitNestedScoped: recursive, builds full parent-chain path, pushes
    a slim scope-header chunk for each parent level + leaf chunks for
    methods. Handles module → class → method chains.
  - buildChunk emits "(in ClassName.method)" header suffix when
    parentSymbolPath is non-empty.
  - mergeSmallSiblings now bails on any file that has parent-scoped
    chunks. Methods emitted by A3 are intentionally small and
    individually addressable; merging them would erase the scope
    context Layer 6 just established.
- src/core/import-file.ts: importCodeFile passes parent_symbol_path
  from chunker metadata into ChunkInput so it lands in content_chunks.
- src/core/pglite-engine.ts + src/core/postgres-engine.ts: upsertChunks
  extends the column list to persist parent_symbol_path (TEXT[]),
  doc_comment (TEXT), symbol_name_qualified (TEXT). All three existed
  as schema columns from Layer 1 but the writers weren't plumbed yet.
  ON CONFLICT DO UPDATE includes all three so re-imports refresh
  metadata correctly.
- test/parent-scope.test.ts: 9 cases covering TypeScript class method
  expansion, Python class, Ruby module+class, top-level function
  passthrough, and round-trip through upsertChunks to verify text[]
  persistence.

Full CI: 2361 pass / 250 skip / 0 fail / 6270 expect() / 439s.

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

* feat: v0.20.0 Cathedral II Layer 5 (A1) — edge extractor + qualified names (8 langs)

The 10x leap. v0.19.0 shipped symbol-column filtering and could find "the
definition of X"; v0.20.0 Layer 5 captures who CALLS X. Walk the tree-sitter
tree during chunking, harvest call-site edges, persist to code_edges_symbol
with the callee's short-name as to_symbol_qualified. `getCallersOf("helper")`
now returns every call site, ready for Layer 7 two-pass retrieval to expand
into structural neighbors.

Scope: precision 80, recall 99. We don't try to resolve receiver types at
capture time (obj.method() stores "method", not "ObjClass.method"). That
receiver-type inference is a future optimization; the edges are captured,
which is the whole point. Cross-file resolution is also deferred — all
Layer 5 edges land unresolved in code_edges_symbol.

Per-language shipped: TypeScript, TSX, JavaScript, Python, Ruby, Go, Rust,
Java. ~85% of real brain code. Other languages chunk normally, edges just
empty.

- src/core/chunkers/qualified-names.ts (new): per-language delimiter
  conventions. Ruby `Admin::UsersController#render` (instance) vs Python
  `admin.users.UsersController.render` vs Rust `users::UsersController::render`.
  Unknown languages dot-join as fallback (never drop).
- src/core/chunkers/edge-extractor.ts (new): iterative AST walk (no
  recursion — tree-sitter trees can be deep, stack overflow risk on
  generated code). Per-language CALL_CONFIG maps node types to callee
  field names. extractCalleeName unwraps member_expression, scoped_identifier,
  field_expression to reach the innermost identifier. findChunkForOffset
  maps a byte offset to the innermost chunk for from_chunk_id resolution.
- src/core/chunkers/code.ts: CodeChunkMetadata gains
  symbolNameQualified. buildChunk folds in qualified-name from parents +
  name. New chunkCodeTextFull API returns (chunks, edges); chunkCodeText
  stays as back-compat wrapper.
- src/core/import-file.ts: call chunkCodeTextFull, build ChunkInput list
  with symbol_name_qualified, after upsertChunks run findChunkForOffset
  to map call-site byte offsets to resolved chunk IDs, call
  deleteCodeEdgesForChunks (codex SP-2 inbound invalidation) then
  addCodeEdges. Edge persistence is best-effort — failure logs a warn
  but does not fail the import.
- src/core/pglite-engine.ts + src/core/postgres-engine.ts: implement the
  5 stub methods. addCodeEdges splits resolved vs unresolved by
  to_chunk_id presence, inserts with ON CONFLICT DO NOTHING. getCallersOf
  / getCalleesOf UNION code_edges_chunk + code_edges_symbol (codex 1.3b:
  no promotion, UNION-on-read forever). getEdgesByChunk honors direction
  {in, out, both}. deleteCodeEdgesForChunks wipes both tables in both
  directions (codex SP-2).
- test/qualified-names.test.ts: 9 cases (TS/Ruby instance method/Python/
  Rust/Java/unknown-lang fallback).
- test/edge-extractor.test.ts: 11 cases (per-language call capture +
  findChunkForOffset mapping + unknown-language empty-list).
- test/code-edges.test.ts: 7 cases (addCodeEdges insert + idempotency,
  getCallersOf short-name match, resolved path, getEdgesByChunk
  direction filters, deleteCodeEdgesForChunks both-direction wipe).

Full CI: 2391 pass / 250 skip / 0 fail / 6308 expect() / 449s.

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

* feat: v0.20.0 Cathedral II Layer 10 rest (C4 + C5) — code-callers / code-callees CLI

Exposes Layer 5's call-graph edges as user-facing agent commands. The
existing code-def / code-refs pair answers "where is X defined?" and
"where is X referenced?"; Layer 10 rest adds "who CALLS X?" and "what
does X CALL?" — the structural questions v0.19.0 couldn't answer.

Conventions follow the code-def / code-refs precedent:
  - Auto-JSON on non-TTY (gh-CLI convention)
  - StructuredAgentError envelope on usage / runtime failure
  - Exit 2 on UsageError, exit 1 on runtime
  - --all-sources to widen beyond the anchor's source; default source-scoped

- src/commands/code-callers.ts (new) — wraps engine.getCallersOf.
- src/commands/code-callees.ts (new) — wraps engine.getCalleesOf.
- src/cli.ts — register both cases, update CLI_ONLY list, update --help
  CODE INDEXING section to list the two new commands.
- test/code-callers-cli.test.ts — 2 cases (module exports, callable).

The --near-symbol / --walk-depth flags on query ship with Layer 7
(A2 two-pass retrieval) in a follow-up layer commit.

Full CI: 2393 pass / 250 skip / 0 fail / 6310 expect() / 448s.

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

* feat: v0.20.0 Cathedral II Layer 7 (A2) — two-pass structural retrieval

The capstone of the retrieval-side upgrade. Layer 5 captured edges at
chunk time; Layer 7 uses them. Given a query like "how does
searchKeyword handle N+1", standard hybrid search returns the function
body; A2 expansion additionally surfaces:
  - the 3 functions that call it (1-hop)
  - the 2 functions it calls (1-hop)
  - the anchor set's neighbors' neighbors (2-hop, optional)

All ranked together with 1/(1+hop) score decay. One walk. Code-aware
brain, not RAG-over-code.

Default OFF per codex F5. Activation:
  - `--walk-depth N` (1 or 2) walks N hops from the anchor set.
  - `--near-symbol <qualified-name>` adds chunks matching the symbol's
    qualified name as extra anchors, enabling "expand around this
    specific symbol" without a keyword query.

Caps (codex F5):
  - depth capped at 2 (max blast radius).
  - neighbor cap 50 per hop (high-fan-out protection: console.log has
    100k callers and should not flood the result set).
  - per-page dedup cap lifts from 2 → min(10, walkDepth × 5) when
    walking — structural neighbors from the same class are the point.

- src/core/search/two-pass.ts (new): expandAnchors walks
  code_edges_chunk + code_edges_symbol, hydrating unresolved edges by
  matching symbol_name_qualified on lookup. hydrateChunks fetches
  SearchResult rows for expanded chunk IDs.
- src/core/search/hybrid.ts: gate the two-pass step on opts.walkDepth
  > 0 OR opts.nearSymbol set. Expansion runs before dedup so neighbors
  survive; dedup cap widens when walking. Best-effort — expansion
  failure falls back to base hybrid retrieval.
- src/core/operations.ts: query op params gain near_symbol (string) +
  walk_depth (number). Handler threads both into hybridSearch opts.
- test/two-pass.test.ts: 8 cases (walkDepth 0/1/2/5-clamp, nearSymbol
  anchoring, hydrateChunks round-trip, operation schema).

Full CI: 2401 pass / 250 skip / 0 fail / 6332 expect() / 449s.

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

* feat: v0.20.0 Cathedral II Layer 11 (E1) — BrainBench code sub-category tests

Pins the retrieval-quality behaviors Layer 5 and Layer 6 added, so any
accidental regression surfaces on CI rather than silently eroding search
quality.

Sub-categories:
  - call_graph_recall — importCodeFile captures calls edges
    end-to-end; getCallersOf + getCalleesOf round-trip through real
    edge extraction; re-import idempotency via codex SP-2 per-chunk
    invalidation.
  - parent_scope_coverage — nested methods persist parent_symbol_path
    through the upsertChunks path; qualified symbol names resolve
    correctly for nested declarations.

doc_comment_matching is deferred: the chunk-grain FTS trigger from
Layer 1b already weights doc_comment 'A', but chunker doc_comment
extraction (A4 full implementation) is a follow-up. The column exists,
the ranking is ready — waiting on extraction.

type_signature_retrieval deferred with C6 to v0.20.1 per plan.

- test/cathedral-ii-brainbench.test.ts (new): 6 cases covering the
  two sub-categories against real PGLite + importCodeFile.

Full CI: 2407 pass / 250 skip / 0 fail / 6345 expect() / 467s.

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

* feat: v0.20.0 Cathedral II Layer 14 — release (CHANGELOG + TODOS + version bump)

The capstone commit. Ships v0.20.0 — Code Cathedral II — with a full
release-summary in CHANGELOG.md covering the 13 layers that landed
(Layer 9 / Magika deferred to v0.20.1 per plan risk gate), migration
guidance under "To take advantage of v0.20.0", and itemized changes
grouped by layer with real numbers.

- VERSION: 0.19.0 → 0.20.0
- package.json: 0.19.0 → 0.20.0
- CHANGELOG.md: new [0.20.0] entry with release-summary (two-line
  bold headline, lead paragraph, numbers-that-matter table with
  before/after delta, per-language call-capture table, "what this
  means for builders" closer), "To take advantage of v0.20.0"
  section with verify commands + issue-reporting template, and the
  full itemized changes section grouped by layer (1 / 2 / 3 / 4 /
  5 / 6 / 7 / 8 / 10 / 11 / 12 / 13 / 9-deferred). Credits 2 codex
  passes + eng + ceo reviews — 16 cross-model findings absorbed.
- TODOS.md: retire the 4 v0.19.0 follow-ups (all landed in v0.20.0
  Layer 8 + Layer 10). Add 4 new Cathedral II follow-ups:
  - B2 Magika (Layer 9 deferred)
  - A4 full doc_comment extraction at chunk time
  - C6 code-signature
  - Cross-file edge resolution (Layer 5 precision upgrade)

Full CI: 2407 pass / 250 skip / 0 fail / 6345 expect() / 465s.

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

* fix(import-file): tolerate missing pages in doc↔impl linking

importCodeFile / importFromContent's E1 doc↔impl forward-link path was
calling tx.addLink() expecting the pre-v0.18 silent-no-op behavior on
missing pages. Master tightened addLink in postgres-engine.ts to throw
when either endpoint is missing — which is correct for explicit callers,
but the doc↔impl case is intentionally order-agnostic: a guide that
cites src/core/sync.ts can land before the code repo syncs (and vice
versa).

Result on CI: 21 E2E tests failed in test/e2e/mechanical.test.ts because
the fixture corpus has prose pages citing code paths the corpus doesn't
include, so each importFromContent threw "addLink failed: page X or Y
not found" and aborted before downstream assertions could run.

Fix: wrap each tx.addLink call (forward + reverse edge) in try/catch.
Match the existing pattern in src/commands/extract.ts:547 and
src/core/operations.ts:453,470 — both run try { addLink } catch { skip }
for exactly this reason. Missing edges land later via
`gbrain reconcile-links` (Layer 8 D3), which forward-scans every
markdown page and idempotently inserts the edges that resolve.

Comment refresh: the old comment ("addLink's inner SELECT naturally
drops edges to non-existent pages") was true pre-v0.18; updated to
reflect the current throwing behavior + the reconcile-links recovery
path.

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

* fix(test/migrate): bump v8/v9 dedup-regression budget 5s → 90s

The v8 (links_dedup) + v9 (timeline_dedup_index) regression tests time
the FULL `runMigrations` chain from version 7 → LATEST_VERSION. Their
5s budget was sized when the chain ended at v8/v9 themselves and v8 +
the helper-btree-index O(n log n) work were the dominant cost.

Cathedral II added v27 (TSVECTOR column + GIN index + plpgsql trigger
compile + 2 new tables w/ FK CASCADE) and v28 (UPDATE backfill of
search_vector). On PGLite WASM in CI, the full v7 → v28 chain now
takes ~30-40s — schema-creation overhead, not v8/v9 dedup itself.
Locally the chain ran in 2.75s; CI's container cold-start hit 33s.

The original O(n²) regression v8 had would have taken MINUTES on 1000
duplicate rows (the original incident was multi-minute, not multi-tens-
of-seconds). Bumping the budget to 90s preserves the regression gate
("if v8 reverts to O(n²), this test catches it because the run blows
past the budget by orders of magnitude") while accommodating Cathedral
II's longer schema chain.

CI: 33758ms (v8 test) + 33343ms (v9 test) → both under 90s. The 5s
assertion was failing them, not the test runner timeout.

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

* fix(migrate): v29 enables RLS on code_edges_chunk + code_edges_symbol

The two new tables added by v27 (Cathedral II foundation) shipped without
RLS enabled. The E2E test "RLS is enabled on every public table (no
hardcoded allowlist)" caught this — Supabase exposes the public schema
via PostgREST so any table without RLS is anon-readable. Same security
gap as the v0.18.1 RLS hardening pass that v24 closed for the original
10 gbrain-managed tables.

Three CI failures fixed by this migration:
  1. "RLS is enabled on every public table" — direct fail on the new
     tables.
  2. "GBRAIN:RLS_EXEMPT comment with valid reason exempts a non-RLS
     public table" — was failing because doctor saw the unrelated
     code_edges tables ALSO un-RLS'd, so the exempt-comment fixture
     wasn't the only no-RLS table and doctor stayed in fail status.
  3. "gbrain doctor exits 0 on healthy DB" — same cause, doctor was
     emitting a fail check for the missing-RLS tables on every healthy
     run.

Pattern: matches v24 exactly. DO $$ block with BYPASSRLS guard so a
non-bypass session can't accidentally lock itself out of its own data;
RAISE EXCEPTION on guard fail leaves schema_version at the prior value
so the next initSchema retries. Postgres-only via sqlFor — PGLite
doesn't enforce RLS the same way and the E2E gate runs only against
real Postgres.

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

* fix(test/e2e): v24 self-heals — assert version >= 24, not exactly 24

Pre-existing test bug surfaced when the E2E job ran on the Cathedral II
branch (and would have surfaced on master too once anyone ran the Tier 1
Mechanical job). The test rolls schema_version back to 23, runs init,
then asserts the version becomes exactly '24'. The intent was to prove
v24 didn't crash on missing budget_* tables — not to pin a specific
final version.

But initSchema runs every pending migration. With v25 + v26 (v0.19.0)
and now v27 + v28 + v29 (v0.21.0 Cathedral II) shipped, init advances
schema_version to LATEST_VERSION (currently 29) regardless of where it
started. The exact-match `'24'` assertion has been wrong since v25
landed; only the lack of an E2E run on master CI hid it.

Fix: parse the final version as int and assert `>= 24`. Same intent
(prove v24 ran cleanly + didn't roll back), forward-compatible with
future schema growth.

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

* docs(README): add "Using gbrain with GStack" — 5 code-search magical moments

Discoverability hint for engineering agents running on GStack. Cathedral
II (v0.21.0) shipped call-graph edges + two-pass retrieval, but a
GStack agent running /investigate or /review won't reach for them
unless someone tells it gbrain has these surfaces. The new subsection
slots between Remote MCP and the Skills index, lists the 5 commands
verbatim (code-callers, code-callees, code-def, code-refs, query
--near-symbol --walk-depth), and links to the v0.21.0 CHANGELOG entry
for context.

Tradeoff acknowledged: gbrain README serves both standalone and
agent-platform users, so the GStack section is kept tight (16 lines)
and slotted with the other agent-integration paths rather than at the
top.

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

* docs: regenerate llms.txt + llms-full.txt for v0.21.0

The build-llms regen-drift guard caught that the committed llms files
were stale after the README "Using gbrain with GStack" addition + the
v0.21.0 CHANGELOG promotion. Running `bun run build:llms` rebuilds both
deterministically from llms-config.ts so the test passes.

No source content changed in this commit — just the generator output.

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

---------

Co-authored-by: Garry Tan <garry@ycombinator.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 12:25:34 -07:00
11abb24ddd v0.20.4 feat: merge gbrain-jobs into minion-orchestrator — single unified minions skill (#381)
* feat: merge gbrain-jobs into minion-orchestrator — single unified minions skill

* fix(skill/minion-orchestrator): correct MCP boundary, real handler names, PGLite path

The initial merge commit a51c737 documented `submit_job name="shell"` as
agent-callable, but src/core/operations.ts:1106 rejects protected names
from MCP callers (shell is in src/core/minions/protected-names.ts:16) —
shell-job submission is CLI-only. Subagent examples referenced non-existent
handler names (`research`, `orchestrate`) instead of the real `subagent` /
`subagent_aggregator` handlers. PGLite section wrongly told users to
migrate to Supabase when `gbrain jobs submit ... --follow` inline mode
works per docs/guides/minions-shell-jobs.md:15. Contract section canonized
"every task through Minions" against the `pain_triggered` default in
skills/conventions/subagent-routing.md:16,27.

Rewrite addresses all four:
- Shell Jobs section is explicit about CLI-only submission; agents observe
  via get_job / list_jobs / get_job_progress (non-protected).
- Subagent examples route through `gbrain agent run` (user-facing CLI)
  with raw handler names documented as the power-user path.
- PGLite gets --follow inline execution, not migration friction.
- Contract softened to point at subagent-routing.md convention.

Also adds a Preconditions block for Shell Jobs (env gate, RCE warning,
execution-mode choice, verification command), narrows the frontmatter
"gbrain jobs" trigger to "gbrain jobs submit" + "submit a gbrain job"
(bare was too broad — CLI namespace covers 9 subcommands), inlines a
"replaces older gbrain-jobs routing intent" note in the description, and
removes non-existent `get_job_stats` from the tools list (CLI is
`gbrain jobs stats`; no MCP equivalent).

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

* fix(resolver): narrow "gbrain jobs" trigger to specific intents

Replace bare "gbrain jobs" in the routing table with "gbrain jobs submit"
+ "submit a gbrain job". The bare phrase was too broad — the CLI namespace
covers 9 subcommands (submit, list, get, retry, delete, prune, stats,
smoke, work). Users asking about stats/prune/retry now fall through to
`gbrain --help` instead of getting misrouted to minion-orchestrator, which
only documents shell execution and subagent orchestration.

Matches the frontmatter trigger narrow in minion-orchestrator/SKILL.md.

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

* test(resolver): add round-trip + skill-example-name validator

Two new assertion blocks in test/resolver.test.ts:

1. RESOLVER.md trigger round-trip: every quoted phrase in a routing-table
   row has a fuzzy match in the target skill's frontmatter `triggers:` list.
   Catches RESOLVER ↔ frontmatter drift that checkResolvable's reachability
   check doesn't. Fuzzy match is case-insensitive, trailing-punctuation-
   insensitive, and splits on "/" for compound phrases like
   "pause/resume agent" — accommodates RESOLVER.md's natural-language
   summary style without allowing real drift through.

2. Skill example-name validator: every `name="<word>"` reference in any
   SKILL.md body must resolve to either a declared operation in
   src/core/operations.ts or a known Minions handler in
   PROTECTED_JOB_NAMES. Would have caught the `name="research"` /
   `name="orchestrate"` drift that slipped through the first review
   — nothing in CI caught those handler names referencing non-existent
   handlers until a Codex cold-read found them. This test closes that
   class of regression gap.

51 / 51 tests pass locally. Full E2E suite (bun run test:e2e) still
passes 197 / 197 across 19 files.

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

* test(e2e): PGLite shell-job --follow inline path

Closes the T4 coverage gap surfaced during PR #381 eng review. The sibling
test/e2e/minions-shell.test.ts covers Postgres + persistent-daemon; this
file covers the PGLite + --follow path the minion-orchestrator skill now
documents.

Two assertions:

1. submit → registerBuiltinHandlers → worker.start → shell runs → completes
   with exit_code 0 and stdout_tail "hello\n". Exercises the exact dispatch
   path src/commands/jobs.ts:207 takes when --follow is set, including the
   GBRAIN_ALLOW_SHELL_JOBS=1 gate.

2. With GBRAIN_ALLOW_SHELL_JOBS unset, registerBuiltinHandlers leaves the
   shell handler unregistered. Confirms the env gate from
   src/commands/jobs.ts:611 works.

Runs in-memory against PGLiteEngine — no DATABASE_URL, no Docker, runs in
CI unconditionally. Completes in ~1.2s.

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

* fix: pre-landing review fixes

Pre-landing review caught 4 doc bugs + 2 test fragilities + 2 pre-existing
drift cases. All auto-fix category (clear correct answer, single obvious fix).

minion-orchestrator/SKILL.md:
- Shell submit examples used nonexistent `--cmd`/`--argv`/`--cwd` flags. Real
  CLI takes `--params '{"cmd":"...","cwd":"..."}'` (src/commands/jobs.ts:55-85).
  Examples now match `gbrain jobs submit --help` output.
- `--tools "search,web_search"` referenced `web_search` which isn't in
  BRAIN_TOOL_ALLOWLIST (src/core/minions/tools/brain-allowlist.ts:47-59).
  Swapped to `search,query`. Added a full allowlist enumeration so
  readers don't have to grep.
- `gbrain agent run` flags section listed `--queue`, `--priority`,
  `--max-attempts`, `--delay` — none of these exist on that command
  (src/commands/agent.ts:105-129). Replaced with the real flag set
  (`--subagent-def`, `--model`, `--max-turns`, `--tools`, `--timeout-ms`,
  `--fanout-manifest`, `--follow`, `--no-follow`, `--detach`) and a note
  about using `gbrain jobs submit` for queue tuning.
- MCP boundary claim "returns permission_denied" was imprecise. Reworded:
  throws an OperationError with code permission_denied.

test/resolver.test.ts:
- D5/C row regex required the backtick-quoted skill path to be followed
  immediately by `|`, silently skipping rows with trailing parentheticals
  (e.g., `` `skills/maintain/SKILL.md` (extraction sections) |``). Broadened
  to `[^|]*\|` so every row gets audited.

test/e2e/minions-shell-pglite.test.ts:
- Shared engine across both tests with no per-test reset. Future test
  additions would hit order-dependency. Added beforeEach TRUNCATE on
  minion_jobs / minion_inbox / minion_attachments, matching the Postgres
  sibling at test/e2e/minions-shell.test.ts:55-58.

skills/query/SKILL.md:
- Added 4 triggers RESOLVER.md routes to this skill but the frontmatter
  never declared: "who knows who", "relationship between", "connections",
  "graph query". Pre-existing drift — the broadened D5/C regex surfaced it.

skills/maintain/SKILL.md:
- Added 6 triggers with the same pre-existing drift: "extract links",
  "build link graph", "populate timeline", "populate links", "backfill graph",
  "extract timeline entries".

57/57 tests pass on the fixed tree.

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

* fix: second-pass review fixes — stale CLI flag + handler name

Two more stale references caught by specialist re-dispatch on the fixed tree:

skills/minion-orchestrator/SKILL.md:72 — Routing table row described shell
  jobs as taking `--cmd` or `--argv` as CLI flags. Same class of bug as M1
  from the prior fix commit but in a different location. Now says `--params`
  with `cmd` or `argv`, matching the corrected submit examples (lines 112-120).

skills/conventions/subagent-routing.md:82 — "Check `get_job_stats`
  queue_health.active" referenced an MCP operation that doesn't exist in
  src/core/operations.ts. The new minion-orchestrator skill cross-references
  this convention file, so agents following the routing pointer would hit a
  non-existent op. Replaced with the real ops: `list_jobs --status active`
  (MCP) or `gbrain jobs stats` (CLI).

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

* fix: adversarial pass cleanups — manifest.json + anti-pattern scope

Claude adversarial subagent caught two last consistency gaps:

skills/manifest.json:135 — Skill description still read "Manage background
  agents via Minions job queue" (subagent-only framing), out of sync with
  the reframed SKILL.md frontmatter. Manifest is what the skill registry
  indexes; leaving this stale meant shell-job-intent routers would miss it.
  Updated to match the unified wording.

skills/minion-orchestrator/SKILL.md:288 — Anti-pattern line "Don't use
  sessions_spawn with runtime: subagent when Minions is available" was
  subagent-lane-specific inside the now-consolidated skill, reading like
  the one rule in the skill but only addressing one lane. Scoped to
  "For subagent work" and pointed at `gbrain agent run` so the rule
  doesn't confuse shell-job readers.

Two investigate-class items deferred to follow-up:
- D13 regex could false-positive on future skills with unrelated `name="..."`
  usage. Today clean; scope to backtick-fenced snippets if it bites.
- PGLite E2E env-var race if bun:test ever goes file-parallel. Today isolated
  per file; add helper + comment when needed.

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

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

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

* docs: update README + CLAUDE.md for v0.19.2 Minions consolidation

- Skill count 28 -> 29 across README and CLAUDE.md (adds smoke-test from
  v0.19.1 to the Skills section, closes a prior drift).
- README minion-orchestrator row rewritten to name both lanes (shell jobs
  via `gbrain jobs submit shell`, LLM subagents via `gbrain agent run`)
  so the surface matches the consolidated skill file.
- README Operational table gains a smoke-test row.
- CLAUDE.md key-files entry for minion-orchestrator now describes the
  v0.19.2 consolidation, trust boundary (MCP permission_denied on
  protected names), and the narrowed trigger set.
- CLAUDE.md Skills section notes the consolidation and the new v0.19.1
  smoke-test skill.
- CLAUDE.md test inventory picks up `test/e2e/minions-shell-pglite.test.ts`
  and the v0.19.2 round-trip + name-validator additions in
  `test/resolver.test.ts`.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(ci): update PGLite test for new env-gate behavior + regenerate llms-full.txt

CI caught two issues:

1. `test/e2e/minions-shell-pglite.test.ts` — the "GBRAIN_ALLOW_SHELL_JOBS
   unset → shell handler not registered" test was written against pre-v0.20.3
   `registerBuiltinHandlers` behavior (env gate at registration time). Master's
   queue-resilience merge moved the gate from registration to execution:
   shell handler is now always registered so claimed jobs emit a clear rejection
   log, and `shellHandler` itself throws UnrecoverableError when
   GBRAIN_ALLOW_SHELL_JOBS != '1' (see src/core/minions/handlers/shell.ts:210).
   Updated the test to invoke shellHandler directly with a minimal ctx and
   assert the throw. Preserves the test's intent (prove the guard works) under
   the new control flow.

2. `llms-full.txt` drift — README.md + CLAUDE.md updates in v0.19.2 and v0.20.4
   updated the skill count to 29 and rewrote the minion-orchestrator
   description, but the committed `llms-full.txt` bundle still reflected the
   pre-consolidation content. Regenerated via `bun run build:llms`.

The third CI failure (`planInstall + applyInstall D-CX-11`) passes cleanly
locally (26/26 in test/skillpack-install.test.ts). The 1ms runtime in CI
suggests a filesystem-mtime flake, not a real regression from this branch.

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

* fix(skillpack): treat future-mtime lock as stale (CI race fix)

D-CX-11 ("--force-unlock overrides a stale lock") flaked in CI with a 1ms
runtime. Root cause: on fast CI filesystems (ext4 with high-resolution
mtimes on GitHub runners), `writeFileSync` can set a lock's mtime a few
microseconds ahead of the subsequent `Date.now()`, making `age` negative.

Old logic:
  const stale = age >= staleMs;

With `staleMs: 0` and `age = -0.3ms`: `-0.3 >= 0` is false → NOT stale →
the `!stale` branch throws `lock_held` before reaching the force-unlock
path. Test failed at the first ms, never exercised the actual unlock logic.

Fix (src/core/skillpack/installer.ts:189):
  const stale = age < 0 || age >= staleMs;

Treats negative age (future mtime) as stale. Safe: if the lock's mtime is
in the future, either the filesystem clock just jumped forward or the
lock was written by a racing process; either way it's not a live,
healthy lock and the stale path is the correct branch.

Passes locally (26/26 in test/skillpack-install.test.ts).

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

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 01:39:58 -07:00
d838d4792b feat: queue resilience — wall-clock timeouts, backpressure, --no-worker, env concurrency (#379)
* feat: queue resilience — wall-clock timeouts, backpressure, --no-worker, env concurrency, shell guard

Prevents stall-induced queue blockage discovered in production (OpenClaw):

1. Wall-clock timeout sweep: dead-letters active jobs exceeding 2× timeout_ms
   (or 2 × lockDuration × max_stalled). Catches jobs stuck while holding DB
   connections where FOR UPDATE SKIP LOCKED stall detection skips them.

2. Submission backpressure (maxWaiting): caps waiting jobs per name at
   submission time. Prevents autopilot-cycle flood when the queue is blocked.

3. --no-worker flag for autopilot: skips spawning the built-in worker child.
   For environments where the worker lifecycle is managed externally (systemd,
   Docker, OpenClaw service-manager).

4. GBRAIN_WORKER_CONCURRENCY env var: fallback for --concurrency when the
   worker is spawned by autopilot (which can't pass CLI flags to the child).

5. Shell job env guard with clear logging: shell handler is always registered
   but throws UnrecoverableError with a clear message when
   GBRAIN_ALLOW_SHELL_JOBS=1 is not set, instead of silently not registering.

* feat: v0.19.1 Lane A — maxWaiting atomic guard, concurrency clamp, --max-waiting CLI

Addresses three production-hardening findings from the CEO + Eng + Codex
adversarial review of PR #379:

D2/H2: maxWaiting was TOCTOU-racy — two concurrent submitters could both
see waitingCount < max and both insert. Wrap the count+select+insert in
pg_advisory_xact_lock keyed on (name, queue). Serializes concurrent
decisions for the SAME key while leaving different keys fully parallel.
Lock auto-releases on txn commit/rollback — no cleanup path to leak.
Also fix the missing queue-scope bug: count and select now filter on
(name, queue) not name alone, so cross-queue same-name jobs don't
suppress each other.

D3/H3: resolveWorkerConcurrency silently accepted NaN / 0 / negative from
parseInt. `inFlight.size < NaN` is always false → worker claims nothing →
silent wedge from a single-typo env var. Clamp to ≥1 with a loud stderr
warning naming the bad value.

D5/H5: `gbrain jobs submit` never parsed `--max-waiting N` despite the
MinionJobInput field. Wire the flag with clamp [1, 100], mirror
`--max-stalled`. Extract `parseMaxWaitingFlag` for unit testing.

Q1: Silent coalesce was invisible by design. New
src/core/minions/backpressure-audit.ts mirrors shell-audit.ts's ISO-week
JSONL pattern: `~/.gbrain/audit/backpressure-YYYY-Www.jsonl`. Coalesce
events write one JSONL line with (queue, name, waiting_count, max_waiting,
returned_job_id, ts). Best-effort — disk-full never blocks submission.

A2: `gbrain jobs smoke --wedge-rescue` new opt-in regression case.
Forges a wedged-worker row state, invokes handleStalled + handleTimeouts
+ handleWallClockTimeouts in order, asserts only wall-clock evicts.
Mirrors the v0.14.3 `--sigkill-rescue` shape.

Tests: 23 new unit cases in test/minions.test.ts covering wall-clock
timeout (3 cases + non-interference with handleTimeouts), maxWaiting
(coalesce, clamp 0, floor, concurrent-submitter race via Promise.all,
cross-queue isolation, unset fallthrough), concurrency clamp (7 cases
incl. NaN/0/negative), parseMaxWaitingFlag (5 cases), backpressure
audit file write.

Part of v0.19.1 plan at ~/.claude/plans/ok-wintermute-wrote-this-polished-matsumoto.md

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

* feat: v0.19.1 Lane B — doctor queue_health, autopilot peer probe, runbook

A5 / D4: New `queue_health` check in `gbrain doctor`. Postgres-only (PGLite
has no multi-process worker surface). Two subchecks, both cheap (single
SELECT each, status-index-covered):

- stalled-forever: any active job with started_at > 1h. Surfaces the
  worst offenders (top 5 by started_at ASC) with `gbrain jobs get/cancel`
  fix hints. The incident that motivated v0.19.1 ran 90+ min before the
  operator noticed.
- waiting-depth: per-name waiting count exceeds threshold. Default 10,
  overridable via GBRAIN_QUEUE_WAITING_THRESHOLD env (D9). Signals a
  submitter probably needs maxWaiting set.

Worker-heartbeat subcheck from the original plan dropped (D4/H4): no
minion_workers table exists, and lock_until-on-active-jobs is a lossy
proxy that can't distinguish idle-worker from dead-worker. Tracked as
follow-up B7.

A4: --no-worker peer-liveness probe in autopilot. When --no-worker is
set, every cycle runs a cheap SELECT checking for any active job whose
lock_until was refreshed in the last 2 minutes. After 3 consecutive
idle ticks, logs a loud WARNING naming the silent-wedge vector and
referencing B7 as the ground-truth follow-up. Re-arms on next live
signal so the warning doesn't spam every cycle.

A6: New docs/guides/queue-operations-runbook.md (one viewport, ~60
lines). "My queue looks wedged — what do I run?" in order of
escalation. What each doctor subcheck means. Self-check for the
--no-worker / no-worker-running footgun.

CLAUDE.md: key-files updates for handleWallClockTimeouts (v0.19.0 Layer
3 kill shot), maxWaiting advisory-lock rewrite (v0.19.1 D2), queue_health
doctor check (v0.19.1 D4), and backpressure-audit.ts.

Tests: all 143 minions + 13 doctor unit tests pass. No new test cases
required in Lane B; the doctor queue_health exercise is in the E2E
verification step (needs real PG to produce meaningful stalled-forever
rows). The --no-worker probe is exercised by the smoke case's wedge
setup in Lane A.

README: unchanged. Existing `gbrain jobs submit` examples don't show
--max-stalled, so no --max-waiting precedent to extend per A6 conditional.

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

* chore: v0.19.1 Lane C — CHANGELOG entry, VERSION bump, remove SPEC.md

VERSION: 0.19.0 → 0.19.1 (patch; bug-fix-dominant, no schema change,
no new user-facing vocabulary).

CHANGELOG: new v0.19.1 entry at the top with the full release-summary
template per CLAUDE.md — bold two-line headline, lead paragraph, "numbers
that matter" before/after table measured against the real incident,
"what this means for OpenClaw users" closer, required "To take
advantage of v0.19.1" block naming the worker-restart requirement,
itemized changes by area, and "For contributors" section closing the
loop on the stale autopilot-idempotency narrative the CEO review was
based on.

Mechanism reframing per D1/H1: the 18-job pile-up was NOT caused by
missing idempotency (autopilot already passes
`idempotency_key: autopilot-cycle:${slot}` at autopilot.ts:241). The
18 jobs were 18 DIFFERENT slots stacking up behind the wedged one.
`maxWaiting` still caps the pile; the incident just wasn't about
idempotency. Adversarial review caught this before ship.

SPEC.md: deleted from repo root. It was Wintermute's planning artifact
for the original PR, not a shipped spec. Design docs belong under
docs/designs/ per repo convention; leaving one at repo root set a
precedent this repo doesn't want (A7/D11). CHANGELOG + the plan file
at ~/.claude/plans/ok-wintermute-wrote-this-polished-matsumoto.md are
the durable artifacts.

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

* fix: --wedge-rescue smoke state — both stall+timeout sweeps must skip

Smoke case was setting lock_until in the past, so handleStalled's
requeue path fired before handleWallClockTimeouts had a chance to
evict. Production scenario is "lock_until still live (worker
renewing) + timeout_at disqualified" — only wall-clock matches.

Single-connection smoke can't simulate a row lock held by another
txn, so we force the equivalent outcome:
- lock_until = now() + 30s → handleStalled skips (not a stall)
- timeout_at = NULL → handleTimeouts skips (needs NOT NULL)
- started_at = now() - 10s, timeout_ms=1000 → wall-clock matches
  (2 × timeout_ms = 2000ms threshold exceeded)

Verified: SMOKE PASS — Minions healthy + wedge rescue in 0.14s.

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

* fix: CI failures — shell-handler tests + llms-full.txt drift

Two CI failure clusters, both pre-existing but surfaced by the v0.20.3
merge:

1) test/minions-shell.test.ts — 12 failing cases. The shell handler
   throws UnrecoverableError when GBRAIN_ALLOW_SHELL_JOBS !== '1' (the
   production RCE guard at shell.ts:210). The unit tests exercise
   handler mechanics, not the guard, but never set the env var — so
   every invocation exits through the guard path instead of the code
   being tested. Fix: set GBRAIN_ALLOW_SHELL_JOBS=1 in beforeAll,
   restore in afterAll. The env-guard IS still tested separately via
   the test/minions.test.ts case added in v0.20.3 Lane A which toggles
   the var itself.

2) llms-full.txt — stale against CLAUDE.md. Key-files entries for
   queue.ts, doctor.ts, and the new backpressure-audit.ts updated in
   v0.20.3 Lane B triggered the build-llms drift guard. Regenerated
   via `bun run build:llms`; no behavior change, just the inlined-docs
   bundle catching up to source.

Full test run: 2367 pass, 0 fail across 137 files.

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

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 01:09:28 -07:00
e3f704229b v0.20.2 feat: gbrain jobs supervisor — self-healing worker process manager (#364)
* feat: add `gbrain jobs supervisor` — self-healing worker process manager

Adds a first-class supervisor command that:
- Spawns `gbrain jobs work` as a child process
- Restarts on crash with exponential backoff (1s→60s cap)
- Resets crash counter after 5min of stable operation
- PID file locking prevents duplicate supervisors
- Periodic health checks (stalled jobs, completion gaps)
- Graceful shutdown (SIGTERM→35s→SIGKILL)

Usage:
  gbrain jobs supervisor --concurrency 4

Replaces ad-hoc nohup patterns in bootstrap scripts.
The autopilot command's internal supervisor can be migrated
to use this in a follow-up.

Tests: 7 pass (backoff calc, PID management, crash tracking)

* supervisor: atomic PID lock, queue-scoped health, env safety, unified exit

Lane A of PR #364 review fixes (20-item multi-lane plan). Addresses the
codex-tier + CEO + Eng findings on src/core/minions/supervisor.ts:

Safety + correctness:
- Atomic O_CREAT|O_EXCL PID lock via openSync('wx') with stale-file
  liveness check. Prevents two supervisors racing on the same PID file.
  (codex #1)
- Health check now queries status='active' AND lock_until < now()
  matching queue.ts:848's authoritative stalled definition. The prior
  `status = 'stalled'` predicate returned zero rows forever because
  'stalled' is not a persisted value in the schema. (codex #2)
- All health queries scoped to WHERE queue = $1 via opts.queue binding.
  Multi-queue installs no longer see cross-queue false positives.
  (codex #3)
- Class default allowShellJobs flipped true→false AND explicit
  `delete env.GBRAIN_ALLOW_SHELL_JOBS` when false, so child workers
  don't silently inherit the var from the parent shell. (eng #8, codex #9)
- Unified shutdown(reason, exitCode) — max-crashes now routes through
  the same drain path as SIGTERM. Single source of truth for lifecycle
  cleanup; prerequisite for trustworthy audit events (Lane C). (eng #1)
- Default PID path moves from /tmp to ~/.gbrain/supervisor.pid with
  mkdirSync recursive + GBRAIN_SUPERVISOR_PID_FILE env override.
  Matches the rest of the product's ~/.gbrain/ convention; fresh
  installs no longer hit ENOENT. (CEO #2 + codex #6)

Refinements:
- crashCount = 1 after 5-min stable-run reset (was 0, produced
  calculateBackoffMs(-1) = 500ms by accident). Now reads as 'first
  crash of a new cycle' with a clean 1s backoff. (Nit 1)
- Top-of-file POSTGRES-ONLY docstring documenting why the supervisor
  can't run against PGLite. (Nit 2)
- inBackoff flag suppresses 'worker not alive' warn during the
  expected null-child window (crash → sleep → next spawn). (eng #2)
- Tracked listener refs for SIGTERM/SIGINT removed in shutdown() so
  integration tests spinning up/tearing down multiple supervisors on
  one process don't leak handlers. (eng #3)
- Single FILTER query replaces two SELECT counts — one round-trip
  instead of two, three metrics in one pass. (eng #10)
- child.on('error') listener emits worker_spawn_failed event for
  ENOENT/EACCES; exit handler still increments crashCount as usual
  so max-crashes bounds permanent misconfigurations. (codex #7)
- healthInFlight boolean guard with try/finally prevents overlapping
  health checks from stacking on a hung DB. (codex #8)

Documented exit codes (ExitCodes const):
  0 CLEAN, 1 MAX_CRASHES, 2 LOCK_HELD, 3 PID_UNWRITABLE
  Agent can branch on exit=2 ('another supervisor, I'm fine') vs
  exit=1 ('escalate to human').

Event emitter surface:
  - started / worker_spawned / worker_exited / worker_spawn_failed
  - backoff / health_warn / health_error / max_crashes_exceeded
  - shutting_down / stopped
  Plumbed through emit() with an onEvent callback hook for Lane C's
  audit writer. json:false is the default; Lane C's --json mode
  flips it and writes JSONL to stderr.

CLI changes (src/commands/jobs.ts):
- `gbrain jobs supervisor` gains --allow-shell-jobs (explicit opt-in
  mirroring the env-var gate), --cli-path (override auto-resolution
  for exotic setups), and --json (JSONL lifecycle events on stderr).
- Expanded --help body with description, 3 examples, and exit-code
  table. (DX Fix A per review)
- Three-tier PID path resolution: --pid-file > GBRAIN_SUPERVISOR_PID_FILE
  > ~/.gbrain/supervisor.pid (via exported DEFAULT_PID_FILE).
- Removed the catch-fallback to process.argv[1] — resolveGbrainCliPath()
  throws its own actionable install-hint error, which is what dev users
  need instead of a cryptic spawn failure on a .ts path. (codex #5)

Tests: existing 7 supervisor.test.ts cases continue to pass.
Integration tests (crash-restart, max-crashes, SIGTERM-during-backoff,
env-inheritance regression) land in Lane E.

Out of scope for this lane (tracked in follow-up lanes):
- Audit file writer at ~/.gbrain/audit/supervisor-YYYY-Www.jsonl (Lane C)
- Documentation pass (Lane B)
- supervisor start/status/stop subcommands (Lane C)
- gbrain doctor supervisor check (Lane D)
- /ship release hygiene (Lane F)
- autopilot.ts migration to MinionSupervisor (deferred to follow-up PR
  per codex — requires non-blocking start() API redesign, not ~30 lines)

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

* docs: supervisor as canonical worker deployment pattern

Lane B of PR #364 review fixes. Reframes docs/guides/minions-deployment.md
around `gbrain jobs supervisor` as the default answer (blocker 7), deletes
the 68-line legacy bash watchdog (F10), and updates README + deployment
snippets to match.

docs/guides/minions-deployment.md:
- New 'Worker supervision' section at the top with the canonical 3-command
  agent pattern (start --detach / status --json / stop) and a documented
  exit-code table (0 clean, 1 max-crashes, 2 lock-held, 3 PID-unwritable).
- 'Which supervisor when?' decision table: container = supervisor as
  PID 1, Linux VM = systemd-over-supervisor, dev laptop = bare terminal.
- New 'Agent usage' section for OpenClaw / Hermes / Cursor / Codex — the
  3-turn discover-start-maintain workflow that replaces shell archaeology
  with machine-parseable JSON events + an audit file at
  ~/.gbrain/audit/supervisor-YYYY-Www.jsonl.
- Demoted the 'Option 1: watchdog cron' path entirely; replaced with a
  straightforward upgrade migration block (stop script, remove cron line,
  start supervisor, verify via doctor).
- Preconditions now check Postgres connectivity directly (supervisor is
  Postgres-only; the CLI rejects PGLite with a clear error).

Snippets:
- systemd.service: ExecStart now invokes `gbrain jobs supervisor` instead
  of raw `gbrain jobs work`. Two-layer supervision (systemd → supervisor
  → worker) buys automatic restart on reboot plus fast crash recovery.
  ReadWritePaths expanded to cover $HOME/.gbrain (supervisor PID + audit).
- Procfile + fly.toml.partial: same change — platform restarts the
  container on host events, supervisor restarts the worker on crashes.
- minion-watchdog.sh: deleted (git history retains it for anyone in an
  exotic deployment). Supervisor subsumes every capability it had plus
  atomic PID locking, structured audit events, queue-scoped health
  checks, and graceful drain on SIGTERM.

README.md:
- Added a paragraph under the Minions section pointing `gbrain jobs
  supervisor` as canonical, noting the --detach / status / stop surface
  and the audit file path, with a link to the full deployment guide.
  Kept `gbrain jobs work` documented for direct raw invocation but
  flagged 'prefer supervisor' for any long-running use.

The supervisor `--help` body itself (3 examples + exit-code table in
src/commands/jobs.ts) landed with Lane A — this lane finishes the
discoverability story by making the supervisor findable via doc grep,
README landing, and deployment-guide landing paths.

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

* supervisor: daemon-manager subcommands + JSONL audit writer

Lane C of PR #364 review fixes. Adds the daemon-manager CLI surface so
agents can drive `gbrain jobs supervisor` in 3 turns instead of 10, and
the audit writer that makes lifecycle events inspectable across process
restarts. (Blocker 8, closes DX Fix A/B/C.)

New: src/core/minions/handlers/supervisor-audit.ts
  - writeSupervisorEvent(emission, supervisorPid) appends JSONL to
    `${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-YYYY-Www.jsonl`.
    ISO-week rotation via a `computeSupervisorAuditFilename()` helper
    that mirrors `shell-audit.ts` exactly (year-boundary ISO week math,
    Thursday anchor, etc).
  - readSupervisorEvents({sinceMs}) returns parsed events from the
    current week's file, oldest-first, for Lane D's doctor check.
    Malformed lines are skipped silently (disk-full truncation is
    already best-effort at write time).
  - Reuses `resolveAuditDir()` from shell-audit.ts so the
    `GBRAIN_AUDIT_DIR` env var override works identically across all
    gbrain audit trails.

src/commands/jobs.ts: supervisor subcommand dispatcher
  - `gbrain jobs supervisor [start] [--detach] [--json] ...` — default
    subcommand. Without --detach, runs foreground as before. With
    --detach, forks a background child (inheriting stderr so the caller
    can still tail JSONL events), writes a stdout payload:
      {"event":"started","supervisor_pid":N,"pid_file":"...","detached":true}
    and exits 0. Stdin/stdout on the detached child are /dev/null so
    the parent shell isn't held open.
  - `gbrain jobs supervisor status [--json]` — reads the PID file,
    checks liveness via `kill -0`, then reads the last 24h from the
    supervisor audit file to compute crashes_24h / last_start /
    max_crashes_exceeded. Exits 0 if running, 1 if not. JSON output
    is machine-parseable; human output is a 5-line ASCII report.
  - `gbrain jobs supervisor stop [--json]` — reads PID, sends SIGTERM,
    polls `kill -0` every 250ms for up to 40s (supervisor's own 35s
    worker-drain + 5s slack). Reports outcome: drained / timeout_40s
    / pid_file_missing / pid_file_corrupt / process_gone. Exit 0 on
    clean stop.
  - `--json` flag is already plumbed through to the supervisor opts
    from Lane A — this lane adds the onEvent audit-writer callback
    so every supervisor emission (started, worker_spawned,
    worker_exited, worker_spawn_failed, backoff, health_warn,
    health_error, max_crashes_exceeded, shutting_down, stopped) lands
    in the JSONL file with the supervisor's PID attached.

--help body updated:
  - Three separate usage lines (start / status / stop).
  - SUBCOMMANDS block with one-line summaries each.
  - EXIT CODES block (unchanged from Lane A, moved under SUBCOMMANDS).
  - EXAMPLES block updated with status --json + stop + --detach forms.

Tests: existing 127 supervisor + minions tests continue to pass.
Integration tests for the new subcommands + audit writer land with
Lane E.

Follow-up (Lane D): `gbrain doctor` will read readSupervisorEvents()
from this module to surface a `supervisor` health check alongside its
existing checks (DB connectivity, schema version, queue health).

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

* doctor: add supervisor health check

Lane D of PR #364 review fixes. Closes the observability loop: now that
Lane C writes supervisor lifecycle events to
`${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-YYYY-Www.jsonl`,
`gbrain doctor` surfaces a `supervisor` check alongside its existing
health indicators.

Implementation (src/commands/doctor.ts, filesystem-only block 3b-bis):
- Resolves DEFAULT_PID_FILE via the same three-tier logic as the start
  path (--pid-file > GBRAIN_SUPERVISOR_PID_FILE > ~/.gbrain/supervisor.pid).
- Reads the PID file + `kill -0 <pid>` for liveness.
- Calls readSupervisorEvents({sinceMs: 24h}) from the audit module to
  derive last_start / crashes_24h / max_crashes_exceeded.
- Suppresses the check entirely when the user has never invoked the
  supervisor (no PID file AND no audit events) — avoids noise on
  installs that don't use the feature.

Status thresholds:
  fail   max_crashes_exceeded event seen in last 24h
         (supervisor gave up; operator needs to restart or triage)
  warn   supervisor not running but audit shows prior use
         (unexpected stop — likely crash or manual kill)
  warn   running but > 3 crashes in last 24h
         (supervisor recovering but worker is unstable)
  ok     running + ≤ 3 crashes + no max_crashes event

All failure paths emit a paste-ready recovery command. Read/import
errors are swallowed (best-effort like the other doctor checks).

Tests: all 127 supervisor + minions tests still green; 13 existing
doctor tests unaffected.

F3 done. All four lanes A/B/C/D are now committed; Lane E (integration
tests) and Lane F (/ship v0.20.2) remain.

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

* test: 4 critical integration tests for supervisor lifecycle

Lane E of PR #364 review fixes (blocker 10). Fills the ~15% coverage
gap flagged in the eng review by actually exercising the code paths
that will break in production — crash-restart loop, max-crashes exit,
SIGTERM-during-backoff, env-var inheritance — via real spawn() calls
against fake shell-script workers. No mocks: real fork, real signals,
real env propagation, real audit file writes.

test/fixtures/supervisor-runner.ts (new, 55 lines):
  A standalone bun script that constructs a MinionSupervisor from env
  vars (SUP_PID_FILE / SUP_CLI_PATH / SUP_MAX_CRASHES / SUP_BACKOFF_FLOOR_MS
  / SUP_HEALTH_INTERVAL_MS / SUP_ALLOW_SHELL_JOBS / SUP_AUDIT_DIR) and
  calls start(). Mock engine returns empty rows for executeRaw (health
  check path still exercised without Postgres). Tests spawn this as a
  subprocess because MinionSupervisor.start() calls process.exit() on
  shutdown — can't run it in the test runner's own process.

test/supervisor.test.ts (existing; 91 → 300 lines):
  - Added IntegrationHarness helper: creates a unique tmpdir per test,
    a fake worker shell script, a PID-file path, and an audit-dir path;
    cleanup runs in finally.
  - spawnSupervisor() forks bun on the runner with env vars set.
  - readAudit() reads the supervisor-YYYY-Www.jsonl file via the
    existing readSupervisorEvents() helper (Lane C), threading
    GBRAIN_AUDIT_DIR through so tests don't collide on ~/.gbrain.
  - waitFor(pred, timeoutMs) polls helper for event-driven tests.

Four integration tests (with _backoffFloorMs=5 for <1s suite runs):

  1. "respawns the worker after a crash and eventually exits with
     max-crashes code=1"
     Worker always `exit 1`. maxCrashes=3. Asserts: exit code 1, PID
     file cleaned up, audit contains started + 3x worker_spawned +
     3x worker_exited + max_crashes_exceeded + shutting_down + stopped,
     and the stopped event carries {reason:'max_crashes', exit_code:1}.
     Locks in blockers 1 (PID lock), 2+3+6 (health SQL doesn't 500),
     5 (unified shutdown emits right events), F8 (spawn errors counted).

  2. "receives SIGTERM while sleeping between crashes and exits 0 cleanly"
     Worker always `exit 1`, backoff floor 800ms to catch the sleep.
     Asserts: SIGTERM during backoff → exit code 0 (not 1) in <5s,
     no signal kill (process.exit via shutdown), audit contains
     shutting_down {reason:'SIGTERM'} + stopped, PID file cleaned up.
     Locks in eng Issue 1 (unified exit path), eng Issue 3 (signal
     handlers don't accumulate across shutdowns).

  3. "strips inherited GBRAIN_ALLOW_SHELL_JOBS when allowShellJobs=false,
     even if parent has it set"  ⚠ CRITICAL regression test
     Parent env has GBRAIN_ALLOW_SHELL_JOBS=1. SUP_ALLOW_SHELL_JOBS=0.
     Worker writes $GBRAIN_ALLOW_SHELL_JOBS (or 'UNSET' if absent) to
     an OUT_FILE. Asserts child sees 'UNSET'. Locks in codex #9 + eng
     #8: the `else delete env.GBRAIN_ALLOW_SHELL_JOBS` branch from
     Lane A is load-bearing for the supervisor's security posture;
     this test prevents a future refactor silently re-opening the
     inheritance hole.

  4. "DOES pass GBRAIN_ALLOW_SHELL_JOBS to child when allowShellJobs=true"
     Positive-path companion to #3. SUP_ALLOW_SHELL_JOBS=1 → worker
     sees '1'. Confirms the else-branch doesn't over-strip and that
     operators who explicitly opt in still get shell-exec enabled.

Plus two audit-format unit tests:
  - computeSupervisorAuditFilename format (regex match)
  - Year-boundary ISO week: 2027-01-01 → supervisor-2026-W53.jsonl
    (matches the shell-audit.ts pattern exactly)

Before: 7 tests covering backoff math + PID helpers (~15% behavioral
coverage per eng review).
After: 13 tests across all critical lifecycle paths (crash-restart,
max-crashes, SIGTERM, env-inheritance, audit rotation).

All 146 tests in supervisor + minions + doctor suites green in ~8s.

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

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

Lane F of PR #364 review fixes. Closes the multi-lane plan with release
hygiene: VERSION bump 0.19.0 → 0.20.2, package.json sync, CHANGELOG entry
in GStack voice with release summary + "numbers that matter" table +
"To take advantage of v0.20.2" migration block + itemized changes.

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

* fix: escape template-literal interpolation in supervisor --help

The --help body in src/commands/jobs.ts is one big backtick template
literal. The supervisor subcommand description I added in Lane B used
both `${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}` (parsed as a template
interpolation into an undefined variable) and inline `code` backticks
(parsed as nested template literals). CI caught it with ~200 tsc parse
errors across the file.

Fix:
- Escape `${...}` → `\${...}` so the audit-file path renders literally.
- Replace prose inline-code backticks with plain single-quote fences
  (`gbrain jobs work` → 'gbrain jobs work', `~/.gbrain/supervisor.pid`
  → ~/.gbrain/supervisor.pid). `--help` output is human prose; the
  single-quote form reads cleanly in a terminal without needing to
  smuggle nested backticks through a template literal.

`bunx tsc --noEmit` is clean. 146 tests still pass.

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

* chore: regenerate llms-full.txt after Lane B doc rewrite

CI drift guard caught that `llms-full.txt` didn't match the current
generator output. Root cause: the Lane B rewrite of
`docs/guides/minions-deployment.md` (supervisor as canonical, watchdog
deleted) changed content that gets inlined into `llms-full.txt`, but I
didn't run `bun run build:llms` to regenerate.

`bun test test/build-llms.test.ts` now clean (7/7 pass).

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

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 00:24:10 -07:00
Garry TanandClaude Opus 4.7 8b3c24c891 v0.20.0 feat: extract BrainBench to sibling gbrain-evals repo (#195)
* fix(link-extraction): v0.10.5 drive works_at + advises accuracy on rich prose

Extends inferLinkType patterns to cover rich-prose phrasings that miss with
v0.10.4 regexes. Targets the residuals called out in TODOS.md: works_at at
58% type accuracy, advises at 41%.

WORKS_AT_RE additions:
- Rank-prefixed: "senior engineer at", "staff engineer at", "principal/lead"
- Discipline-prefixed: "backend/frontend/full-stack/ML/data/security engineer at"
- Possessive time: "his/her/their/my time at"
- Leadership beyond "leads engineering": "heads up X at", "manages engineering at",
  "runs product at", "leads the [team] at"
- Role nouns: "role at", "position at", "tenure as", "stint as"
- Promotion patterns: "promoted to staff/senior/principal at"

ADVISES_RE additions:
- Advisory capacity: "in an advisory capacity", "advisory engagement/partnership/contract"
- "as an advisor": "joined as an advisor", "serves as technical advisor"
- Prefixed advisor nouns: "strategic/technical/security/product/industry advisor to|at"
- Consulting: "consults for", "consulting role at|with"

New EMPLOYEE_ROLE_RE page-level prior: fires when the page describes the subject
as an employee (senior/staff/principal engineer, director, VP, CTO/CEO/CFO) at
some company. Biases outbound company refs toward works_at when per-edge context
is possessive or narrative without an explicit work verb. Scoped to person -> company
links only. Precedence: investor > advisor > employee (investors often hold board
seats which would otherwise mis-classify as advise/works_at).

ADVISOR_ROLE_RE broadened from "full-time/professional/advises multiple" to catch
any page that self-identifies the subject as an advisor ("is an advisor",
"serves as advisor", possessive "her advisory work/role/engagement").

Tests: 65 pass (16 new v0.10.5 coverage tests + 4 regression guards against
v0.10.4 tightenings). Templated benchmark still 88.9% type_accuracy (10/10 on
works_at and advises). Rich-prose measurement requires the multi-axis report
upgrade (next commit) to validate retroactively.

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

* feat(eval): type-accuracy runner on rich-prose corpus + wire into all.ts

New Category 2 in BrainBench: per-link-type accuracy measured directly on the
240-page rich-prose world-v1 corpus. Distinct from Cat 1's retrieval metrics,
this measures whether inferLinkType() correctly classifies extracted edges
when the prose varies (the 58% works_at and 41% advises residuals that v0.10.5
regexes targeted).

How it works:
  1. Loads all pages from eval/data/world-v1/
  2. Derives GOLD expected edges from each page's _facts metadata
     (founders → founded, investors → invested_in, advisors → advises,
      employees → works_at, attendees → attended, primary_affiliation +
      role drives person-page outbound type)
  3. Runs extractPageLinks() on each page → INFERRED edges
  4. Per (from, to) pair, compares inferred type vs gold type
  5. Emits per-link-type table: correct / mistyped / missed / spurious +
     type accuracy + recall + precision + strict F1 (triple match)
  6. Full confusion matrix rows=gold, cols=inferred

v0.10.5 validation on 240-page corpus (up from pre-v0.10.5 baselines):
  - works_at:    58%  → 100.0%   (+42 pts) — 10/10 correct, 0 mistyped
  - advises:     41%  → 88.2%    (+47 pts) — 15/17 correct
  - attended:    —    → 100.0%   131/134 recall
  - founded:    100%  → 100.0%   40/40
  - invested_in: 89%  → 92.0%    69/75
  - Overall:    88.5% → 95.7%    type accuracy (conditional on edge found)

Strict F1 overall: 53.7%. Lower because the _facts-based gold set only
captures core relationships; rich prose extracts many peripheral mentions
(190 spurious "mentions" edges) that aren't bugs but are correctly-typed
prose references without a _facts counterpart. Spurious counts are signal
for future type-precision tuning, not failure.

Wired into eval/runner/all.ts as Cat 2 so every full benchmark run includes
the rich-prose type accuracy table alongside retrieval metrics.

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

* feat(eval): Phase 2 adapter interface + EXT-1 ripgrep+BM25 baseline

Phase 2 credibility unlock: BrainBench now compares gbrain to external
baselines on the same corpus and queries. Transforms the benchmark from
internal ablation ("gbrain-graph beats gbrain-grep") to category comparison
("gbrain-graph beats classic BM25 by 32 pts P@5"). This is the #1 fix
from the 4-review arc — addresses Codex's core critique that v1's
before/after was self-referential.

Added:
  eval/runner/types.ts                      — Adapter interface (v1.1 spec)
  eval/runner/adapters/ripgrep-bm25.ts      — EXT-1 classic IR baseline
  eval/runner/adapters/ripgrep-bm25.test.ts — 11 unit tests, all pass
  eval/runner/multi-adapter.ts              — side-by-side scorer

Adapter interface (eng pass 2 spec):
  - Thin 3-method Strategy: init(rawPages, config), query(q, state), snapshot(state)
  - BrainState is opaque to runner (never inspected)
  - Raw pages passed in-memory; gold/ never crosses adapter boundary
    (structural ingestion-boundary enforcement)
  - PoisonDisposition enum reserved for future poison-resistance scoring

EXT-1 ripgrep+BM25:
  - Classic Lucene-variant IDF + k1/b tuned at standard 1.5/0.75
  - Title tokens double-weighted for entity-page slug-match bias
  - Stopword filter, alphanumeric tokenization, stable lexicographic tie-break
  - Pure in-memory inverted index — no external deps, ~100 LOC core

First side-by-side results on 240-page rich-prose corpus, 145 relational queries:

| Adapter       | P@5    | R@5    | Correct top-5 |
|---------------|--------|--------|---------------|
| gbrain-after  | 49.1%  | 97.9%  | 248/261       |
| ripgrep-bm25  | 17.1%  | 62.4%  | 124/261       |
| Delta         | +32.0  | +35.5  | +124          |

gbrain-after is the hybrid graph+grep config from PR #188. Ripgrep+BM25 is
a genuinely strong classic-IR baseline (BM25 is what Lucene/Elasticsearch
ship). gbrain's ~+32-point lead on relational queries reflects real work
by the knowledge graph layer: typed links + traversePaths surface the
correct answers in top-K that BM25 only pulls in via partial-text overlap.

Next in Phase 2: EXT-2 vector-only RAG + EXT-3 hybrid-without-graph
adapters. Both plug into the same Adapter interface.

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

* feat(eval): Phase 2 EXT-2 vector-only RAG adapter

Second external baseline for BrainBench. Pure cosine-similarity ranking
using the SAME text-embedding-3-large model gbrain uses internally —
apples-to-apples on the embedding layer so any gbrain lead reflects the
graph + hybrid fusion, not a better embedder.

Files:
  eval/runner/adapters/vector-only.ts      ~130 LOC
  eval/runner/adapters/vector-only.test.ts 6 unit tests (cosine math)

Design:
  - One vector per page (title + compiled_truth + timeline, capped 8K chars).
  - No chunking (intentional; chunked vector RAG would be EXT-2b later).
  - No keyword fallback (that's EXT-3 hybrid-without-graph).
  - Embeddings in batches of 50 via existing src/core/embedding.ts (retry+backoff).
  - Cost on 240 pages: ~$0.02/run.

Three-adapter side-by-side on 240-page rich-prose corpus, 145 relational queries:

| Adapter       | P@5    | R@5    | Correct top-5 |
|---------------|--------|--------|---------------|
| gbrain-after  | 49.1%  | 97.9%  | 248/261       |
| ripgrep-bm25  | 17.1%  | 62.4%  | 124/261       |
| vector-only   | 10.8%  | 40.7%  |  78/261       |

Interesting finding: vector-only scores WORSE than BM25 on relational queries
like "Who invested in X?" — exact entity match matters more than semantic
similarity for these templates. BM25 nails the entity-name term; vector-only
returns topically-similar-but-not-mentioning pages. This is the known failure
mode of pure-vector RAG on precise relational/identity queries. Real-world
vector RAG systems always add keyword fallback; EXT-3 (hybrid-without-graph)
will be that fairer comparator.

gbrain's lead widens in vector-only comparison: +38.4 pts P@5, +57.2 pts R@5.
The graph layer is doing the heavy lifting for relational traversal; pure
vector RAG can't express "traverse 'attended' edges from this meeting page."

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

* feat(eval): Phase 2 EXT-3 hybrid-without-graph adapter — graph isolated

Third and closest-to-gbrain external baseline. Runs gbrain's full hybrid
search (vector + keyword + RRF fusion + dedup) WITHOUT the knowledge-graph
layer. Same engine, same embedder, same chunking, same hybrid fusion —
only traversePaths + typed-link extraction turned off.

This is the decisive comparator for "does the knowledge graph do useful
work?" Same everything-else, only graph differs. Any lead gbrain-after has
over EXT-3 is 100% attributable to the graph layer.

Files:
  eval/runner/adapters/hybrid-nograph.ts   — ~110 LOC

Implementation:
  - New PGLiteEngine per run; auto_link set to 'false' (belt).
  - importFromContent() used instead of bare putPage() so chunks +
    embeddings get populated (hybridSearch needs them).
  - NO runExtract() call — typed links/timeline stay empty (suspenders).
  - hybridSearch(engine, q.text) answers every query. Aggregate chunks
    to page-level by best chunk score.

FOUR-adapter side-by-side on 240-page rich-prose corpus, 145 relational queries:

| Adapter         | P@5    | R@5    | Correct/Gold |
|-----------------|--------|--------|--------------|
| gbrain-after    | 49.1%  | 97.9%  | 248/261      |
| hybrid-nograph  | 17.8%  | 65.1%  | 129/261      |
| ripgrep-bm25    | 17.1%  | 62.4%  | 124/261      |
| vector-only     | 10.8%  | 40.7%  |  78/261      |

The headline delta nobody can hand-wave away:
  gbrain-after → hybrid-nograph  = +31.4 P@5, +32.9 R@5
  hybrid-nograph → ripgrep-bm25  = +0.7 P@5,  +2.7 R@5

Hybrid search (vector+keyword+RRF) over pure BM25 gains ~1 point. The
knowledge graph layer over hybrid gains ~31 points. The graph is doing
the work; adding it to a retrieval stack is what actually moves the needle
on relational queries. The vector/keyword/BM25 debate is a footnote.

Timing: hybrid-nograph init is ~2 min (embeds 240 pages once); query loop
is fast. gbrain-after is ~1.5s total because traversePaths doesn't need
embeddings. Runs at ~$0.02 Opus-equivalent in embedding cost.

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

* feat(eval): Phase 2 query validator + Tier 5 Fuzzy + Tier 5.5 synthetic + N=5 tolerance bands

Closes multiple Phase 2 items in one commit since they form a cohesive
package: query schema enforcement + new query tiers + per-query-set
statistical rigor.

Added:
  eval/runner/queries/validator.ts               — hand-rolled Query schema validator
  eval/runner/queries/validator.test.ts          — 24 unit tests, all pass
  eval/runner/queries/tier5-fuzzy.ts             — 30 hand-authored Tier 5 Fuzzy/Vibe queries
  eval/runner/queries/tier5_5-synthetic.ts       — 50 SYNTHETIC-labeled outsider-style queries (author: "synthetic-outsider-v1")
  eval/runner/queries/index.ts                   — aggregator + validateAll()

Modified:
  eval/runner/multi-adapter.ts                   — N=5 runs per adapter (BRAINBENCH_N override), page-order shuffle, mean±stddev reporting

Query validator (hand-rolled, no zod dep to match gbrain codebase style):
  - Temporal verb regex enforces as_of_date (per eng pass 2 spec):
    /\\b(is|was|were|current|now|at the time|during|as of|when did)\\b/i
  - Validates tier enum, expected_output_type enum, gold shape per type
  - gold.relevant must be non-empty slug[] for cited-source-pages queries
  - abstention requires gold.expected_abstention === true
  - externally-authored tier requires author field
  - batch validation catches duplicate IDs

Tier 5 Fuzzy/Vibe (30 queries, hand-authored):
  - Vague recall: "Someone who was a senior engineer at a biotech company..."
  - Trait-based: "The engineer who pushed back on microservices"
  - Cultural/epithet: "Who is known as a 'systems builder' in security?"
  - Abstention bait: "Which Layer 1 project did the crypto guy leave?" (prose
    mentions but never names; good systems abstain)
  - Addresses Codex's circularity critique — vague queries where graph-heavy
    systems shouldn't inherently win.

Tier 5.5 Synthetic Outsider (50 queries, AI-authored placeholder):
  - Clearly labeled author: "synthetic-outsider-v1"
  - Phrasing variety not in the 4 template families:
    * fragment style ("crypto founder Goldman Sachs background")
    * polite/natural ("Can you pull up what we have on...")
    * comparison ("What is the difference between X and Y?")
    * follow-up ("And who else advises Orbit Labs?")
    * typos/misspellings ("adam lopez bioinformatcis")
    * similarity ("Find me someone like Alice Davis...")
    * imperative ("Pull up Alice Davis")
  - Real Tier 5.5 from outside researchers supersedes synthetic via
    PRs to eval/external-authors/ (docs ship in follow-up commit).

N=5 tolerance bands:
  - Default N=5, override via BRAINBENCH_N env var (e.g. BRAINBENCH_N=1 for dev loops)
  - Per-run seeded Fisher-Yates shuffle of page ingest order (LCG seed = run_idx+1)
  - Surfaces order-dependent adapter bugs (tie-break-by-first-seen etc.)
  - Reports mean ± sample-stddev per metric
  - "stddev = 0" is honest signal that the adapter is deterministic, not a bug.
    LLM-judge metrics (future) will naturally produce non-zero stddev.

Validation: all 80 Tier 5 + 5.5 queries pass validateAll(). 24 validator
unit tests pass.

Next commit: world.html contributor explorer (Phase 3).

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

* feat(eval): Phase 3 world.html explorer + eval:* CLI surface

Contributor DX magical moment. Static HTML explorer renders the full
canonical world (240 entities) as an explorable tree, opens in any browser,
zero install. Every string HTML-entity-encoded (XSS-safe — direct vuln
class per eng pass 2, confidence 9/10).

Added:
  eval/generators/world-html.ts         — renderer (~240 LOC; single-file
                                          HTML with inline CSS + minimal JS)
  eval/generators/world-html.test.ts    — 16 tests (XSS + rendering correctness)
  eval/cli/world-view.ts                — render + open in default browser
  eval/cli/query-validate.ts            — CLI wrapper for queries/validator
  eval/cli/query-new.ts                 — scaffold a query template

Modified:
  package.json                          — 7 new eval:* scripts
  .gitignore                            — ignore generated world.html

package.json scripts shipped:
  bun run test:eval                 all eval unit tests (57 pass)
  bun run eval:run                  full 4-adapter N=5 side-by-side
  bun run eval:run:dev              N=1 fast dev iteration
  bun run eval:world:view           render world.html + open in browser
  bun run eval:world:render         render only (CI-friendly, --no-open)
  bun run eval:query:validate       validate built-in T5+T5.5 (or a file path)
  bun run eval:query:new            scaffold a new Query JSON template
  bun run eval:type-accuracy        per-link-type accuracy report

XSS safety:
  escapeHtml() encodes the 5 critical chars (& < > " '). Tested directly
  with representative Opus-generated attacks:
    <img src=x onerror=alert('xss')>  → &lt;img src=x onerror=alert(&#39;xss&#39;)&gt;
    <script>fetch('/steal')</script>  → &lt;script&gt;fetch(&#39;/steal&#39;)&lt;/script&gt;
  Ledger metadata (generated_at, model) also escaped — covers the less
  obvious attack surface where Opus could emit tag-like content into the
  metadata file.

world.html structure:
  - Left rail: entities grouped by type with counts (companies, people,
    meetings, concepts), alphabetical within type
  - Right pane: per-entity cards with title + slug + compiled_truth +
    timeline + canonical _facts as collapsed JSON
  - URL fragment deep-links (#people/alice-chen)
  - Sticky rail on desktop; responsive stack on mobile
  - Vanilla JS for active-link highlighting on scroll (no framework)

Generated file: ~1MB for 240 entities (full prose). Gitignored; rebuild
with `bun run eval:world:view`. Regeneration is ~50ms.

Contributor TTHW (Tier 5.5 query authoring):
  1. bun run eval:world:view                         # see entities
  2. bun run eval:query:new --tier externally-authored --author "@me"
  3. edit template with real slug + query text
  4. bun run eval:query:validate path/to/file.json
  5. submit PR

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

* docs(eval): Phase 3 contributor docs + CI workflow for eval/ tests

Ships the contributor-onboarding surface promised in the plan. With this
commit, external researchers have a self-serve path from clone to PR in
under 5 minutes.

Added:
  eval/README.md                                — 5-minute quickstart,
                                                  directory map, methodology
                                                  one-pager, adapter scorecard
  eval/CONTRIBUTING.md                          — three contributor paths:
                                                    1. Write Tier 5.5 queries
                                                    2. Submit an external adapter
                                                    3. Reproduce a scorecard
  eval/RUNBOOK.md                               — operational troubleshooting:
                                                  generation failures, runner
                                                  failures, query validation,
                                                  world.html rendering, CI
  eval/CREDITS.md                               — contributor attribution
                                                  (synthetic-outsider-v1 labeled
                                                  as placeholder; real submissions
                                                  land here)
  .github/PULL_REQUEST_TEMPLATE/tier5-queries.md — structured PR template
                                                  for Tier 5.5 submissions
  .github/workflows/eval-tests.yml              — CI: validates queries,
                                                  runs all eval unit tests,
                                                  renders world.html on every PR
                                                  touching eval/** or
                                                  src/core/link-extraction.ts

CI scope (intentionally narrow):
  - Triggers on paths: eval/**, src/core/link-extraction.ts, src/core/search/**
  - Runs: bun run eval:query:validate (80 queries), test:eval (57 tests),
          eval:world:render (smoke-test the HTML renderer)
  - Pinned actions by commit SHA (matches existing .github/workflows/test.yml)
  - Zero API calls — all Opus/OpenAI paths stubbed or skipped in unit tests
  - Fast: ~30s total wall clock

Contributor TTHW (clone → first merged PR):
  - Path 1 (Tier 5.5 queries): ~5 min
  - Path 2 (external adapter): ~30 min for a simple adapter
  - Path 3 (reproduce scorecard): ~15 min wall clock (N=5 run)

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

* fix(eval): teardown PGLite engines so bun run eval:run exits 0

The multi-adapter runner left PGLite engines alive after each run.
GbrainAfterAdapter and HybridNoGraphAdapter both instantiate a
PGLiteEngine in init() but never disconnect it; Bun's shutdown path
exits with code 99 when embedded-Postgres workers outlive main().

Added optional `teardown?(state)` to the Adapter interface, implemented
it on both engine-backed adapters, and call it from scoreOneRun after
the N=5 loop. ripgrep-bm25 and vector-only hold no DB resources and
don't need a teardown.

Verified: gbrain-after, hybrid-nograph, ripgrep-bm25, vector-only all
exit 0 at N=1. Full test:eval passes (57 tests). No metric change.

* docs(bench): 2026-04-19 multi-adapter scorecard

Reproducibility run of the 4-adapter side-by-side at commit b81373d
(branch garrytan/gbrain-evals). N=5, 240-page corpus, 145 relational
queries from world-v1.

Headline: gbrain-after 49.1% P@5 / 97.9% R@5. hybrid-nograph 17.8% /
65.1%. ripgrep-bm25 17.1% / 62.4%. vector-only 10.8% / 40.7%. All
adapters deterministic (stddev = 0 across the 5 runs per adapter).

Matches the scorecard in eval/README.md byte-for-byte for the three
deterministic adapters; hybrid-nograph matches within tolerance bands.

* docs(bench): 2026-04-19 gbrain v0.11.1 vs v0.12.1 regression comparison

Runs the same eval harness against two gbrain src/ trees on the same
240-page corpus and 145 queries. Patches the v0.11 copy's gbrain-after
adapter to use getLinks/getBacklinks (v0.11 has no traversePaths)
with identical direction+linkType semantics.

gbrain-after P@5 22.1% -> 49.1% (+27 pts); R@5 54.6% -> 97.9% (+43
pts); correct-in-top-5 99 -> 248 (+149). hybrid-nograph flat at 17.8%
/ 65.1% on both (v0.12 didn't touch hybridSearch / chunking).

Driver is extraction quality, not graph presence: v0.12 emits 499
typed links (v0.11: 136, x3.7) and 2,208 timeline entries (v0.11: 27,
x82) on the same 240 pages. Sharpens the April-18 "graph layer does
the work" claim -- on v0.11 that architecture only beat hybrid-nograph
by 4.3 points; the 31-point lead in the multi-adapter scorecard comes
from graph + high-quality extract in combination.

* feat(eval): BrainBench v1 portable JSON schemas + gold templates

Adds the v1→v2 contract boundary for BrainBench. 6 JSON schemas at
eval/schemas/ pin the shape of every artifact a stack must emit to be
scorable: corpus-manifest, public-probe (PublicQuery with gold stripped),
tool-schema (12 read + 3 dry_run tools, 32K tool-output cap), transcript,
scorecard (N ∈ {1, 5, 10}), evidence-contract (structured judge input).

8 gold file templates at eval/data/gold/ scaffold the sealed qrels,
contradictions, poison items, and citation labels. Empty-but-valid
skeletons; Day 3b fills them with real content once the amara-life-v1
corpus generates.

48 tests validate schema syntax, $schema/$id/title/type headers,
round-trip stability, and cross-schema coherence (new Page types in
manifest enum, tool counts, token cap, N enum).

When v2 ports to Python + Inspect AI + Docker, these schemas are the
boundary. Same fixtures, same tool contracts, zero rework.

* feat(eval): amara-life-v1 skeleton + Page.type enum for email/slack/cal/note

Deterministic procedural generator for the twin-amara-lite fictional-life
corpus (BrainBench v1 Cat 5/8/9/11 target). 15 contacts picked from
world-v1, 50 emails + 300 Slack messages across 4 channels + 20 calendar
events + 8 meeting transcripts + 40 first-person notes. Mulberry32 PRNG
gives byte-identical output under reseed.

Plants 10 contradictions + 5 stale facts + 5 poison items + 3 implicit
preferences at deterministic positions. Fixture_ids are unique across the
corpus so gold/contradictions.json + gold/poison.json + gold/implicit-
preferences.json can cross-reference by stable ID.

PageType extended in both src/core/types.ts and eval/runner/types.ts to
include email | slack | calendar-event | note (+ meeting on the production
side). src/core/markdown.ts inferType() heuristics updated for the new
one-slash slug prefixes (emails/em-NNNN, slack/sl-NNNN, cal/evt-NNNN,
notes/YYYY-MM-DD-topic, meeting/mtg-NNNN).

17 tests cover counts (50/300/20/8/40), perturbation counts (exact
10/5/5/3), seed determinism + divergence, slug regex conformance (matches
eval/runner/queries/validator.ts:131 one-slash rule), unique fixture_ids,
amara-in-every-email invariant, calendar dtstart < dtend, and Amara-is-
attendee on every meeting.

* feat(eval): amara-life-gen.ts with structured cache key + $20 cost gate

Opus prose expansion of the amara-life-v1 skeleton. Per-item structured
cache key = sha256({schema_version, template_id, template_hash, model_id,
model_params, seed, item_spec_hash}). Prompt-template tweak changes
template_hash; only those items regenerate. Schema bump changes
schema_version; everything invalidates cleanly. Interrupted runs resume
from the last cached item; zero re-spend.

Cost-gated at $20 hard-stop with Anthropic input/output pricing tracking.
Dry-run mode (--dry-run) executes the full pipeline with stub bodies for
smoke-testing the I/O layout without LLM spend. --max N caps items per
type for debugging. --force ignores cache.

Writes per-format outputs under eval/data/amara-life-v1/:
  inbox/emails.jsonl (one email per line with body_text appended)
  slack/messages.jsonl (one message per line with text appended)
  calendar.ics (RFC-5545 VEVENT format, templated — no LLM)
  meetings/<id>.md (transcript with YAML frontmatter)
  notes/<YYYY-MM-DD-topic>.md (first-person journal)
  docs/*.md (6 reference docs, templated — no LLM)
  corpus-manifest.json (per eval/schemas/corpus-manifest.schema.json,
    including per-item content_sha256 and generator_cache_key)

Perturbation hints (contradiction, stale-fact, poison, implicit-
preference) flow through the prompt so Opus weaves the specific claim
into each item's body. Poison items are hand-crafted to include
paraphrased prompt-injection attempts (not literal 'IGNORE ALL
PREVIOUS' — defense is the structured-evidence judge contract at
Day 5, not regex redaction).

New package.json scripts:
  eval:generate-amara-life       # real run (~$12 Opus estimated)
  eval:generate-amara-life:dry   # smoke test, zero spend

test:eval extended to include test/eval/. 10 cache-key tests cover
determinism, invalidation across every field of the key, canonical JSON
stability under object-key reorder, and per-skeleton-item spec-hash
uniqueness (50 distinct hashes for 50 distinct emails).

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

Resets package.json from stale 0.13.1 to 0.15.0 (matches VERSION).
v0.14.0 shipped with the stale package.json version; this sync catches
that up and moves to v0.15.0 in one step.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* docs: update CLAUDE.md + README + eval/README for v0.15.0 BrainBench

CLAUDE.md: adds a full BrainBench section to the Key Files list — 14 new
entries covering eval/README.md, multi-adapter.ts, types.ts (with new
PublicPage/PublicQuery), adapters/, queries/, type-accuracy.ts,
adversarial.ts, all.ts, world.ts/gen.ts, world-html.ts, amara-life.ts,
amara-life-gen.ts, schemas/, data/world-v1/, data/gold/,
data/amara-life-v1/, docs/benchmarks/, and test/eval/. Adds 3 new
test/eval/ lines to the unit-tests catalog.

eval/README.md: file tree updated to reflect v0.15 additions —
data/amara-life-v1/, data/gold/, schemas/, generators/amara-life.ts +
amara-life-gen.ts, runner/all.ts + adversarial.ts.

README.md: updates hero benchmark numbers (L7 intro + L353 mid-page)
from v0.10.5 PR #188 numbers (R@5 83→95, P@5 39→45) to current v0.12.1
4-adapter numbers (P@5 49.1% · R@5 97.9% · +31.4 pts vs hybrid-nograph).
Adds the v0.11→v0.12 regression comparison as the secondary reference.
Deeper-section tables (L422+) labeled "BrainBench v1 (PR #188)" are
preserved as historical data.

CHANGELOG is untouched — /ship already wrote the v0.15.0 entry.
TODOS.md is untouched — Cat 5/6/8/9/11 remain open (only foundations
shipped in v0.15.0; Cat runners ship in v1 Complete follow-ups).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(eval): Day 4 — pdf-parse + flight-recorder + tool-bridge (dry_run + expand:false)

Three infrastructure modules for BrainBench v1 Complete Cats 5/8/9/11.

**eval/runner/loaders/pdf.ts** — Thin pdf-parse wrapper. Lazy import keeps
pdf-parse out of the module-load path (avoids library debug-mode side
effects). Size cap (50MB default), encryption detection, structured error
classes (PdfEncryptedError, PdfTooLargeError, PdfParseError). Only Cat 11
multimodal will import this; production bundle never sees pdf-parse.

**eval/runner/tool-bridge.ts** — Maps 12 read-only operations from
src/core/operations.ts to Anthropic tool definitions + adds 3 dry_run write
tools. Three structural invariants enforced:

  1. No hidden LLM calls. `operations.query` defaults expand=true which
     routes through expansion.ts → Haiku. Bridge strips `expand` from the
     query tool's input schema AND executor hard-sets expand:false. Zero
     nested Haiku calls in any agent trace.

  2. Mutating ops throw ForbiddenOpError. put_page, add_link, delete_page,
     etc. are rejected by name. Agents record intent via dry_run_put_page /
     dry_run_add_link / dry_run_add_timeline_entry which persist to the
     flight-recorder without mutating the engine. This is how Cat 8's
     back_link_compliance + citation_format metrics measure anything with
     a read-only tool surface.

  3. Poison tagged by the bridge, not the judge. Every tool result is
     scanned for slugs matching gold/poison.json fixtures. Matched
     fixture_ids flow into tool_call_summary.saw_poison_items for the
     structured-evidence judge contract. Judge never reads raw tool
     output — Section-3 defense against paraphrased prompt injections
     (poison payloads never reach the judge model at all).

32K-token cap (~128K chars) with "…[truncated]" suffix.

**eval/runner/recorder.ts** — Per-run flight-recorder bundle emitter. Full
6-artifact bundle (transcript.md, brain-export.json, entity-graph.json,
citations.json, scorecard.json, judge-notes.md) when the adapter provides
an AdapterExport; 3-artifact fallback (transcript + scorecard +
judge-notes) otherwise. Atomic writes via tmp+rename. Collision-safe:
duplicate directory names get incremental -2, -3 suffix. `safeStringify`
handles circular references without throwing and JSON-serializes
Float32Array embeddings.

**package.json:** adds pdf-parse@2.4.5 as a devDependency. Scoped to eval/
use only; production gbrain binary unaffected.

**Tests:** 63 new — 30 tool-bridge, 21 recorder, 12 pdf-loader. All pass.
Fake engine uses a Proxy with `__default__` fallback so poison-matching
tests don't have to mock the exact engine method name that each operation
calls (some route via searchKeyword, others via getPage — proxy handles
both uniformly).

Total eval suite now: 132 pass, 0 fail, 923 expect() calls.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(eval): Day 5 — agent adapter + judge with structured evidence contract

Two modules that together wire Cat 8 / Cat 9 / Cat 5 end-to-end scoring.

**eval/runner/judge.ts** — Haiku 4.5 via tool-use `score_answer`. Input is
the structured JudgeEvidence contract (fix #16 from the plan's codex
review): probe + final_answer_text + evidence_refs + tool_call_summary +
ground_truth_pages + rubric. Raw tool output NEVER reaches the judge —
that's the Section-3 defense against paraphrased prompt-injection payloads
in gold/poison.json.

Retry policy: one retry on malformed tool_use response. If the second
attempt is still malformed, score the probe as `judge_failed` (all scores
0, verdict=fail) so the run still completes.

Aggregation: weighted mean across rubric criteria. Canonical thresholds
(pass ≥3.5, partial 2.5-3.5, fail <2.5) — judge can propose a verdict but
the computed verdict from the weighted mean is what the scorecard records.
This prevents the model from inflating or deflating its own verdict.

Score values are clamped to 0-5 on parse even if the model returns out of
range. `assertNoRawToolOutput(evidence)` is a regression guard that
returns the list of forbidden fields (tool_result, raw_transcript, etc.)
if any leak into the evidence contract.

**eval/runner/adapters/claude-sonnet-with-tools.ts** — The agent adapter.
Implements `Adapter` interface minimally: `init()` spins up PGLite and
seeds it, `query()` throws because the adapter is Cat 8/9-only and emits
a final-answer text, not a RankedDoc[]. Retrieval scorecard stays at 4
adapters.

`runAgentLoop(probeId, text, state, config)` drives the multi-turn loop:
Sonnet → tool_use → tool-bridge.executeTool → tool_result → back to
Sonnet. Turn cap 10. max_tokens 1024. System prompt (brain-first iron
law, citation format, amara context) is cached via cache_control.
Exponential backoff on rate-limit errors (1s, 2s, 4s).

Emits a `Transcript` per eval/schemas/transcript.schema.json — consumed
directly by recorder.ts for the flight-recorder bundle.

`brain_first_ordering` classifies Cat 8's flagship metric: did the agent
call search/get_page BEFORE producing the final answer? The `no_brain_calls`
case (agent answers from general knowledge without ever hitting the brain)
is the compliance failure to surface.

ForbiddenOpError + UnknownToolError from the bridge are caught in the
agent loop and surfaced as tool_result with is_error=true — keeps the
loop going and preserves full audit trail for the judge.

**Tests (35 new):** judge (23) — happy path, retry, fallback, evidence
contract sanitization, rendered prompt does not contain raw tool_result
text, verdict thresholds, score clamping, weighted mean with mixed
weights, parseToolUse rejects malformed input. agent-adapter (12) —
Adapter.query() throws, init() seeds PGLite, end-to-end tool loop with
stubbed Sonnet, turn cap exhaustion, mutating-op rejection surfaces as
tool_result error, extractSlugs regex.

All 12 agent tests take ~23s because PGLite runs 13 schema migrations per
test; the alternative of shared-engine-across-tests was rejected so each
test is isolated.

Total eval suite now: 167 pass, 0 fail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(eval): Day 6 — adversarial-injections + Cat 6 prose-scale + Cat 11 multi-modal

Three modules that together cover BrainBench v1 Cat 6 (prose-scale
extraction fidelity) and Cat 11 (multi-modal ingest fidelity).

**eval/runner/adversarial-injections.ts** — 6 deterministic content
transforms shared by Cat 10 (adversarial.ts, 22 hand-crafted cases) and
Cat 6 (prose-scale variants). Each injection produces a modified content
string + a structured GoldDelta describing what the extractor MUST and
MUST NOT produce. Kinds:
  - code_fence_leak — fake [X](people/fake) inside ``` fence, must NOT extract
  - inline_code_slug — `people/fake` in backticks, must NOT extract
  - substring_collision — "SamAI" near real `people/sam`, exactly one link
  - ambiguous_role — "works with" vs "works at", downgrade type to mentions
  - prose_only_mention — strip markdown link syntax, bare name → mentions only
  - multi_entity_sentence — pack 4+ entities into one clause, extract all

Mulberry32 PRNG keeps variant generation deterministic under fixed seed.
Codex flagged the original plan's wording ("extract injection engine from
adversarial.ts") as overstated — adversarial.ts is a static case list,
not a reusable engine. This module is NEW code.

**eval/runner/cat6-prose-scale.ts** — Runner. Loads world-v1, applies all
6 injection kinds to sampled base pages (default 50 variants per kind ×
6 kinds = 300 variants), runs extractPageLinks on each, compares to gold
delta. Emits per-kind + overall metrics (precision, recall, F1,
code_fence_leak_rate, substring_fp_rate, pages_with_links_coverage,
mean_links_per_page). **v1 verdict is always "baseline_only"** — no
gating threshold per codex fix #9 (current extractor residuals make
>0.80 unreachable; v1 records a baseline, regression guard triggers on
drop below it).

**eval/runner/cat11-multimodal.ts** — PDF + HTML + audio runners.
Fixtures load from eval/data/multimodal/<modality>/fixtures.json
manifests; each modality skips gracefully when manifest missing or
(audio) when neither GROQ_API_KEY nor OPENAI_API_KEY is set. Metrics:
  - PDF: char-level similarity via Levenshtein + optional entity_recall
  - HTML: word-recall over normalized tokens (multiset semantics)
  - Audio: WER (word error rate) via Levenshtein on word sequences
Fixtures are NOT committed; a future eval:fetch-multimodal script will
download them hash-verified from public sources (arXiv CC-licensed
papers, Wikipedia CC-BY-SA, Common Voice CC0).

Injectable audio transcriber (`opts.transcribe`) means tests don't need
GROQ/OpenAI keys — stubbed transcriptions exercise the WER math path
directly.

**Tests (60 new):** adversarial-injections (19) — per-kind assertions +
dispatcher coverage + slug regex conformance; cat6 (12) — variant
determinism, scoreVariant shape, aggregate per-kind + overall metrics,
corpus resolver slug rules; cat11 (29) — charSimilarity / wordRecall /
wer math, htmlToText strips scripts + decodes entities, HTML modality
with real fixtures, audio modality gracefully skips without key + uses
stub transcriber correctly.

All 60 tests pass in 48ms + 41ms.
Total eval suite now: 227 pass, 0 fail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(eval): Day 7 — Cat 5 provenance runner + structured classify_claim judge

**eval/runner/cat5-provenance.ts** — BrainBench Cat 5 scoring. Samples
claims from gbrain brain-export and classifies each against its source
material via a dedicated Haiku judge (classify_claim tool with a
three-label enum: supported | unsupported | over-generalized).

Separate from judge.ts by design: Cat 5 is a single three-way
classification per claim, not a weighted rubric. Rather than overload
judge.ts with a mode switch, Cat 5 has its own tool definition
(CLASSIFY_CLAIM_TOOL) and prompt. The retry-once pattern, $20 cost gate
semantics, and structured parsing are mirrored from judge.ts so failures
look the same across Cats.

Metric: `citation_accuracy` = fraction where predicted label equals
gold expected_label. Threshold (informational): >0.90 per design-doc
METRICS.md. v1 ships with `enableThreshold: false` so the verdict is
always baseline_only — we don't have hand-authored gold claims yet, and
codex flagged that threshold gating should wait until the amara-life-v1
corpus + gold file authoring lands in Day 3b.

runCat5 uses a bounded-concurrency worker pool (default 4) to respect
Haiku rate limits across 100+ claim batches. Evidence pages are looked
up by slug from a caller-provided pagesBySlug map — missing pages don't
crash, they just pass an empty source list to the judge (correct
behavior for genuinely unsupported claims).

**Tests (23):** classifyClaim happy/retry/fallback paths with stubbed
Haiku, aggregate accuracy math, threshold gating (pass/fail vs
baseline_only), runCat5 concurrency + missing-page handling,
renderClaimPrompt embeds claim + sources correctly, parseClassification
rejects invalid enum values + plain-text responses.

Total eval suite now: 250 pass, 0 fail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(eval): Day 8 — Cat 8 skill compliance + Cat 9 end-to-end workflows

**eval/runner/cat8-skill-compliance.ts** — Deterministic, judge-free Cat 8
scoring. Replays inbound signals through the agent adapter (Day 5) and
extracts four iron-law metrics directly from the tool-bridge state:

  - brain_first_compliance: agent called search/get_page BEFORE producing
    its final answer. Non-compliance = hallucinating from general knowledge.
  - back_link_compliance: every dry_run_put_page intent has at least one
    markdown [Name](slug) back-link in its compiled_truth.
  - citation_format: timeline entries use canonical `- **YYYY-MM-DD** |
    Source — Summary`; long final answers cite at least one slug.
  - tier_escalation: simple probes use light tooling (≥1 brain call);
    complex probes require ≥2 brain calls or a dry_run write when
    expects_dry_run_write is set.

No judge call required — everything is computable from
`tool_bridge_state.made_dry_run_writes` + `count_by_tool` + final_answer
regex. Fast, deterministic, reproducible.

Bounded concurrency (p-limit style) worker pool at default 4 to keep
Sonnet rate limits comfortable across 100-probe batches.

**eval/runner/cat9-workflows.ts** — Rubric-graded Cat 9. 5 canonical
workflows (meeting_ingestion, email_to_brain, daily_task_prep, briefing,
sync) × ~10 scenarios each. Each scenario runs through the agent adapter,
then judge.ts scores the answer against a per-scenario rubric.

`buildEvidence(scenario, agentResult, pagesBySlug)` composes the
JudgeEvidence contract: resolves ground_truth_slugs to full
GroundTruthPage[] from a slug-map, pulls tool_call_summary directly from
tool_bridge_state (no raw tool_result content — Section-3 defense),
attaches rubric from the scenario.

Per-workflow rollup: each workflow gets its own pass_rate so the verdict
can fail one workflow without failing the whole Cat. Overall verdict
requires every populated workflow's pass_rate ≥ threshold (default 0.80)
when enableThreshold=true.

Both Cats default to verdict=baseline_only in v1 per codex fix #9: real
thresholds return after 10-probe Haiku-vs-hand-score calibration (κ > 0.7)
runs against the Day 3b amara-life-v1 corpus.

**Tests (23):** Cat 8 per-metric scorer unit tests covering every branch
(brain_first ordering, back-link compliance on mixed writes, long vs
short answer citation requirement, tier escalation for simple/complex/
writey probes, finalAnswerCiteCount dedups across syntaxes). Cat 9
buildEvidence contract shape — evidence_refs flow from agent, missing
slugs skip gracefully, no raw_transcript/tool_result leakage to judge.
Cat 9 runCat9 integration with stubbed agent + mixed-verdict judge
produces fractional pass rates correctly.

Total eval suite now: 273 pass, 0 fail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(eval): Day 9 — sealed qrels via PublicPage + PublicQuery at adapter boundary

Codex fixes #1, #2, #3 from the plan's outside-voice review. Enforcement
shifts from SOFT-VIA-TYPE-COMMENT to SOFT-VIA-SANITIZED-OBJECT. Hard
enforcement via process isolation waits for BrainBench v2 Docker sandbox.

**eval/runner/types.ts** additions:
  - `PublicPage = Pick<Page, 'slug' | 'type' | 'title' | 'compiled_truth' |
    'timeline'>` — the exact 5 fields adapters should see. No _facts.
    No frontmatter (a known hiding spot for accidental gold leaks).
  - `sanitizePage(p: Page): PublicPage` — returns a NEW object with the 5
    fields only. Cannot be bypassed by `(page as any)._facts` because the
    field does not exist on the sanitized object.
  - `PublicQuery = Omit<Query, 'gold'>` — strips the gold field.
  - `sanitizeQuery(q: Query): PublicQuery` — enumerates public fields
    explicitly (not spread+delete) so no prototype weirdness leaves gold
    reachable.

**eval/runner/multi-adapter.ts** — scoreOneRun now calls sanitizePage /
sanitizeQuery before passing to adapter.init / adapter.query. The scorer
retains the full Query shape (including gold.relevant) for precision /
recall computation. Adapter signatures unchanged — the sealing is at the
OBJECT level, not the type level. This keeps existing adapters
(ripgrep-bm25, vector-only, hybrid-nograph, gbrain-after) binary-compatible.
Verified: no existing adapter reads q.gold or page._facts, so the change
is safe without further adapter updates.

**test/eval/sealed-qrels.test.ts** (17 tests):
  - sanitizePage strips _facts + frontmatter + arbitrary hidden keys
  - Output has exactly the 5 public keys (deep introspection)
  - Proxy tripwire simulates a malicious adapter: any access to _facts or
    gold throws `sealed-qrels violation`
  - sanitizeQuery retains optional fields (as_of_date, tags, author,
    acceptable_variants, known_failure_modes) but omits undefined ones
  - Honest documentation of the seal's limits: filesystem bypass and
    Proxy attacks would still work in v1; Docker isolation (v2) is the
    real enforcement

Every existing eval test still passes (273 before + 17 sealed-qrels = 290).

Total eval suite now: 290 pass, 0 fail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat(eval): Day 10 — all.ts rewrite + llm-budget + BrainBench N tiers

Final wiring of BrainBench v1 Complete. all.ts now orchestrates the full
Cat catalog (1-12) via a mix of subprocess dispatch (Cats 1, 2, 3, 4, 6,
7, 10, 11, 12 — standalone runners with CLI entry points) and
programmatic invocation (Cats 5, 8, 9 — require runtime inputs that
can't come via CLI flags). Subprocess Cats run concurrently under a
p-limit(2) bound to cap peak memory around ~800MB (two PGLite instances
at ~400MB each).

Cats 5/8/9 show as "programmatic" in the report with a one-line
reference to their `runCatN({...})` harness API. They're deliberately
skipped from the master runner because their inputs (claim catalog,
probe catalog, scenario catalog, pre-seeded agent state, evidence
pagesBySlug) are task-specific and assembled at the caller.

**eval/runner/all.ts** — rewritten:
  - CATEGORIES is a tagged union of SubprocessCategory | ProgrammaticCategory
  - runCatSubprocess spawns Bun with pipe'd stdout/stderr, 10-min timeout
    per Cat (124 exit + SIGTERM on timeout; no hung subprocesses)
  - runConcurrently is a bounded worker pool preserving input order
  - buildReport emits the full markdown with per-Cat elapsed times,
    migration-noise filter, and a separate programmatic-only section
  - Honors BRAINBENCH_N (1/5/10 for smoke/iteration/published),
    BRAINBENCH_CONCURRENCY (default 2),
    BRAINBENCH_LLM_CONCURRENCY (default 4, consumed by llm-budget)

**eval/runner/llm-budget.ts** — shared LLM rate-limit semaphore. A full
N=10 published scorecard makes ~900 Anthropic calls (150 Cat 8/9 probes
× N=10 + 100 Cat 5 claims × N=10). Without coordination, concurrent
adapters trigger 429s on per-minute limits.

  - LlmBudget class: acquireSlot/releaseSlot + withLlmSlot(fn) wrapper
    that releases on success AND throw (try/finally)
  - getDefaultLlmBudget() singleton reads BRAINBENCH_LLM_CONCURRENCY,
    falls back to 4 on missing/garbage values
  - capacity enforced ≥1 (rejects 0/negative)
  - Double-release is a no-op (guards against upstream double-call bugs)
  - Active + waiting counts exposed for observability / tests

**package.json** scripts:
  - eval:brainbench           — default N=5 iteration
  - eval:brainbench:smoke     — N=1 for fast iteration
  - eval:brainbench:published — N=10 for committed baselines
  - eval:cat6 / eval:cat11    — individual new subprocess Cats

**Tests (24):** CATEGORIES catalog enforces the exact Cat-number partition
(subprocess: 1,2,3,4,6,7,10,11,12; programmatic: 5,8,9). runConcurrently
respects the cap (observable via peak in-flight counter), preserves input
order under non-uniform delays, handles empty input. LlmBudget enforces
capacity, releases on throw, honors env var, rejects 0/negative.
buildReport filters migration noise, counts passed/failed/programmatic
correctly, includes every Cat + programmatic-only section.

Full eval suite now: 314 pass, 0 fail (15 test files).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(eval): drop top_p from amara-life-gen Opus params + gitignore _cache/

Two fixes surfaced during the Day 3b real-corpus run against Opus 4.5:

**eval/generators/amara-life-gen.ts** — Current Opus rejects
`temperature` and `top_p` together:
```
400 invalid_request_error: `temperature` and `top_p` cannot both be
specified for this model. Please use only one.
```
top_p=1.0 was a no-op (no nucleus truncation), so removing it has zero
semantic effect. The field is still part of MODEL_PARAMS for the cache
key so any past cache entries (none in v1) would invalidate cleanly
on the next schema version bump.

**.gitignore** — `eval/data/amara-life-v1/_cache/` is runtime Opus
cache (398 files, ~1.6MB). Regenerable from seed; no point in source
control. The corpus itself (inbox/slack/calendar/meetings/notes/docs +
corpus-manifest.json with per-item content_sha256) stays committable
for reproducibility, just the cache directory gets excluded.

Real corpus generation ran cleanly after these two fixes: 398 LLM
calls, 84,424 input / 38,062 output tokens, \$4.12 spent (vs \$20 cap,
vs \$12 estimate). All 418 items produced. Poison fixtures use
subtle paraphrased injection ("for anyone on your team who might be
triaging this thread later…") — exactly the pattern that defeats
regex redaction and requires the structured-evidence judge contract
from Day 5.

Corpus itself stays local (will move to the brainbench sibling repo
during the v0.16 split per the design doc). No eval/data/amara-life-v1/
content landing in this PR.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: bump version to 0.20.0

Renumbered from 0.17.0 per the gbrain-versioning slot. Other work is
landing on master around this PR; 0.18 is the slot locked for this
BrainBench v1 Complete release. Also pushed the "brainbench split"
forward reference in the CHANGELOG from v0.18 → v0.19 to match.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: extract BrainBench to sibling gbrain-evals repo

BrainBench lived in this repo through v0.17, which meant every gbrain install
pulled down ~5MB of eval corpus, benchmark reports, and a pdf-parse devDep
that the 99% of users who never run benchmarks don't need.

v0.18 moves the full eval harness, 14 eval test files (314 tests), all
docs/benchmarks scorecards, and the pdf-parse devDep to
github.com/garrytan/gbrain-evals. That repo depends on gbrain via GitHub URL
and consumes it through a new public exports map.

What stays in gbrain:
- Page.type enum extensions (email | slack | calendar-event | note | meeting)
  useful for any ingested format, not just evals
- inferType() heuristics for /emails/, /slack/, /cal/, /notes/, /meetings/
- 11 new public exports covering the gbrain internals gbrain-evals consumes
  (gbrain/engine, gbrain/pglite-engine, gbrain/search/hybrid, etc.) — now
  gbrain's stable third-party contract

What moved:
- eval/ — 4.6MB of schemas, runners, adapters, generators, CLI tools
- test/eval/ — 14 test files, 314 tests
- docs/benchmarks/ — all scorecards and regression reports
- eval:* package.json scripts
- pdf-parse devDep

Tests: 1760 pass, 0 fail, 174 skipped (E2E require DATABASE_URL).

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

* Merge origin/master into garrytan/gbrain-evals

Master landed significant work since this branch was cut (v0.15.x → v0.16.x →
v0.17.0 gbrain dream + runCycle → v0.18.0 multi-source brains → v0.18.1 RLS
hardening). Bumped this branch's version from the claimed 0.18.0 to 0.19.0
because master already owns 0.18.x.

Conflicts resolved:
- VERSION: 0.19.0 (was 0.18.0 on HEAD vs 0.18.1 on master)
- package.json: 0.19.0, kept all 11 eval-facing exports, merged master's
  typescript devDep + postinstall script + test script (typecheck added)
- src/core/types.ts: union of both PageType additions. Master had added
  `meeting | note`; this branch added `email | slack | calendar-event`
  for inbox/chat/calendar ingest. Final enum carries all five.
- CHANGELOG.md: renumbered the BrainBench-extraction entry to 0.19.0 and
  placed it above master's 0.18.1 RLS entry. Tweaked copy ("In v0.17 it
  lived inside this repo" → "Previously it lived inside this repo") to
  stop implying a specific version that never shipped.
- CLAUDE.md: adjusted "BrainBench in a sibling repo" heading from
  (v0.18+) → (v0.19+).
- docs/benchmarks/2026-04-18-minions-vs-openclaw-production.md:
  resolved modify-vs-delete conflict in favor of delete (the extraction).
- scripts/llms-config.ts: dropped the docs/benchmarks/ entry (directory
  no longer exists here; lives in gbrain-evals).
- llms.txt / llms-full.txt: regenerated after the config change.
- bun.lock: accepted master's (master already dropped pdf-parse as a
  drive-by; aligned with our removal).

Tests: 2094 pass, 236 skip, 18 fail. Spot-checked failures — build-llms,
dream, orphans tests all pass in isolation. Failures reproduce only under
full-suite parallel load and are pre-existing master flakiness (matches the
graph-quality flake noted in the earlier summary). Not merge-introduced.

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

* chore: bump to v0.20.0

Master is now at v0.18.2 (migration hardening + RLS + multi-source brains).
BrainBench extraction ships as v0.20.0 to leave v0.19 free for any in-flight
work on other branches.

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

* ci: remove eval-tests workflow (moved to gbrain-evals)

The Eval tests workflow ran `bun run eval:query:validate`, `test:eval`, and
`eval:world:render` — all three scripts moved to the gbrain-evals repo when
BrainBench was extracted in v0.20.0. The workflow has been failing on master
since the split because the scripts no longer exist here.

Eval CI now runs from gbrain-evals's own workflows.

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

* fix(tests): bump PGLite hook timeouts to 60s for parallel-load stability

Six test files spin up PGLite + 20 migrations + git repos in beforeEach/
beforeAll hooks. Under 136-way parallel test file execution, bun's default
5s hook timeout wasn't enough, producing 18 flaky failures that only
reproduced under full-suite parallel load (all 6 files passed in isolation).

Root cause: PGLite.create() + initSchema() takes ~3-5s under idle load, but
under 136 concurrent WASM instantiations the OS thrashes and hooks stall
well past 5s. The bunfig.toml `timeout = 60_000` applies to TESTS, not HOOKS
— bun requires per-hook timeouts as the third beforeEach/beforeAll argument.

Files touched (hook timeouts added, no test logic changed):
- test/dream.test.ts           — 5 describe blocks × before/afterEach
- test/orphans.test.ts         — 1 beforeEach + afterEach
- test/core/cycle.test.ts      — shared beforeAll + afterAll
- test/brain-allowlist.test.ts — beforeAll + afterAll
- test/extract-db.test.ts      — beforeAll + afterAll
- test/multi-source-integration.test.ts — beforeAll + afterAll

Results: 2317 pass / 0 fail (was 2253 pass / 18 fail).

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

* test: coverage for inferType() BrainBench corpus dirs

Closes the 1 gap surfaced by Step 7 coverage audit. 9 table-driven
assertions covering the new Page.type branches:
  emails/*.md, email/*.md       -> 'email'
  slack/*.md                    -> 'slack'
  cal/*.md, calendar/*.md       -> 'calendar-event'
  notes/*.md, note/*.md         -> 'note'
  meetings/*.md, meeting/*.md   -> 'meeting'

The fixtures use realistic paths from the amara-life-v1 corpus in the
sibling gbrain-evals repo (em-0001, sl-0037, evt-0042, mtg-0003) so the
test doubles as a contract check between the two repos.

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

* docs(TODOS): mark BrainBench Cats 5/6/8/9/11 + v0.10.5 inferLinkType as completed

All five BrainBench categories shipped in v0.20.0 (to the gbrain-evals
sibling repo). v0.10.5 inferLinkType regex expansion shipped in-tree.

Remaining P1 BrainBench work: Cat 1+2 at full scale (2-3K pages) —
currently 240 pages in world-v1 corpus.

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

* docs: sync CLAUDE.md + polish CHANGELOG voice for v0.20.0

CLAUDE.md: add v0.19 commands to key-files list (skillify, skillpack,
routing-eval, filing-audit, skill-manifest, resolver-filenames);
add 8 new test files + openclaw-reference-compat E2E to test index;
repoint the release-summary template's benchmark source from
`docs/benchmarks/[latest].md` to `gbrain-evals/docs/benchmarks/` since
those files now live in the sibling repo.

CHANGELOG voice polish for v0.20.0: replace em dashes with periods,
parens, or ellipses per project style guide. No content changes.

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

* docs: regenerate llms-full.txt after CLAUDE.md + CHANGELOG edits (fixes CI)

The v0.20.0 doc-sync commit (9e567bb) added 7 new v0.19 modules to the
CLAUDE.md Key Files index and polished CHANGELOG voice. Both are
includeInFull: true inputs to llms-full.txt but the generator wasn't
re-run, so the drift-detection guard (test/build-llms.test.ts) failed CI.

One-line fix: regenerate. No content changes beyond what the two source
docs already carry.

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-24 00:08:54 -07:00
246cd8be46 v0.19.1 — smoke-test skillpack (post-restart health + auto-fix) (#369)
* feat: smoke-test skillpack — post-restart health checks + auto-fix

Adds `gbrain smoke-test` CLI command that runs 8 health checks after
container restart, auto-fixes known issues, and reports results.

Built-in tests:
  1. Bun runtime (auto-install if missing)
  2. GBrain CLI loads (auto-reinstall deps)
  3. GBrain database connection (doctor health score)
  4. GBrain worker process (auto-start)
  5. OpenClaw Codex plugin Zod CJS (auto-reinstall broken zod@4)
  6. OpenClaw gateway responding
  7. Embedding API key present
  8. Brain repo exists

User-extensible: drop scripts in ~/.gbrain/smoke-tests.d/*.sh

Includes SKILL.md with full documentation, pattern for adding tests,
and known-issue database (e.g. Zod core.cjs publish bug).

Designed to run from OpenClaw bootstrap hooks so every container
restart automatically verifies and repairs the environment.

* fix: register smoke-test in RESOLVER + add required SKILL sections

Fixes the 7 failing unit tests + 1 failing Tier 1 E2E:

- `skills/RESOLVER.md`: add smoke-test under Operational (mirrors
  skillpack-check placement). Fixes resolver_health check failure which
  cascaded into skillpack-check tests, doctor exit code, and the E2E
  'gbrain doctor exits 0 on healthy DB' assertion.

- `skills/smoke-test/SKILL.md`: add `## Anti-Patterns` and
  `## Output Format` sections required by skills-conformance.test.ts.

Root cause: PR #369 added skills/smoke-test/ to the manifest but never
wired it into RESOLVER.md and never added the sections the conformance
test requires for every manifest entry.

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

* fix: regenerate llms-full.txt to pick up RESOLVER smoke-test row

build-llms drift guard (test/build-llms.test.ts:58) failed because
llms-full.txt inlines skills/RESOLVER.md and the last commit added a
smoke-test trigger row there. Regenerated via `bun run build:llms`.

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

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

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:53:53 -07:00
78ba0b5b53 v0.19.0 check-resolvable: add OpenClaw skills-dir fallback + docs/tests (#326)
* Add OpenClaw skills fallback for check-resolvable

* feat: v0.17.0 foundation — errors/warnings split + AGENTS.md support + auto-manifest

First two workstreams of the v0.17.0 "skillify end-to-end" release. Landed
together because the D-CX-3 exit-code refactor is a prerequisite for W1's
warning-surfaced filing audit in Workstream 3.

## D-CX-3: split ResolvableReport into errors[] + warnings[] + --strict

Prior: `env.ok = report.issues.length === 0` treated warnings and errors
identically for exit status. Any warning forced exit 1, which meant the
planned filing-audit (W3) would break CI for every OpenClaw deployment
emitting advisory warnings.

New contract:
- `ResolvableReport.errors[]` and `warnings[]` as separate arrays.
- `issues[]` stays as deprecated backcompat union (remove in v0.18).
- Default: exit 0 unless any errors. Warnings are advisory.
- `--strict` flag promotes warnings to fail CI (explicit opt-in).

Files: src/core/check-resolvable.ts, src/commands/check-resolvable.ts
(added --strict flag + help text + header doc), src/commands/doctor.ts
(use new fields), test/check-resolvable-cli.test.ts (rewrite REGRESSION-GATE
to document the new contract, add 3 D-CX-3 cases).

## W1: AGENTS.md support + auto-manifest + priority fix

The reference OpenClaw deployment uses AGENTS.md (not RESOLVER.md) at the
workspace root, and ships without a manifest.json. check-resolvable
silently false-passed against it pre-W1: 0 manifest entries meant 0
reachability iterations meant 0 errors reported.

Post-W1 behavior against ~/git/<redacted>/workspace (smoke-tested live):
- Detects 102 skills via SKILL.md walk (no manifest.json needed)
- Flags 15 unreachable errors (exactly the essay's '~15% dark' finding)
- Flags 108 warnings (overlaps, gaps) — advisory, not blocking
- Auto-detects via \$OPENCLAW_WORKSPACE without --skills-dir

Changes:

- NEW src/core/resolver-filenames.ts: one source of truth for the
  filename policy. \`RESOLVER_FILENAMES = ['RESOLVER.md', 'AGENTS.md']\`.
  Callers import from here, never hardcode either name.

- NEW src/core/skill-manifest.ts: \`loadOrDeriveManifest()\` — reads
  manifest.json when present+valid, otherwise walks \`skillsDir/*/SKILL.md\`
  to derive a synthetic manifest. Both check-resolvable.ts AND dry-fix.ts
  now call this, replacing the two duplicated loaders that silently
  returned [] on missing file (F-ENG-1, D-CX-12).

- src/core/repo-root.ts (rewrite): auto-detect priority changed to put
  \$OPENCLAW_WORKSPACE ahead of findRepoRoot() walk when explicitly set
  (D-CX-4). Adds workspace-root AGENTS.md detection — OpenClaw layout
  places routing at workspace/AGENTS.md with skills/ below. New
  SkillsDirSource variants \`openclaw_workspace_env_root\` and
  \`openclaw_workspace_home_root\` for --verbose log clarity.

- src/core/check-resolvable.ts: accepts RESOLVER.md or AGENTS.md at the
  skills dir or one level up (workspace root). Uses loadOrDeriveManifest
  for reachability. Updated error messages reference both filenames.

- src/core/dry-fix.ts: unified manifest loader — auto-fix now works in
  AGENTS.md-only workspaces where it previously no-op'd silently.

- src/commands/check-resolvable.ts: new AUTO_DETECT_HINT import for
  clearer missing-skills-dir errors; updated sourceLabel map for the
  two new workspace-root variants.

Tests:
- test/skill-manifest.test.ts: 14 cases covering explicit-manifest,
  derived-manifest, malformed JSON, wrong shape, empty explicit array
  (honored as 'zero skills' declaration), dirname fallback when no
  name: frontmatter, underscore/dotfile dir skipping.
- test/repo-root.test.ts: new tests for the priority swap, AGENTS.md
  skills-dir variant, AGENTS.md workspace-root variant, both-files
  present (RESOLVER.md wins).
- test/check-resolvable-cli.test.ts: updated regression-gate to the
  new contract; added three D-CX-3 cases.

All 105 tests passing across the foundation surface.

Plan + reviews: ~/.claude/plans/p1-lets-just-vast-blanket.md

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

* feat: v0.17.0 W2 — Check 5 trigger routing eval (structural)

Check 5 of the 10-step skillify checklist (the essay's "resolver
trigger eval") now runs structurally by default and has a dedicated
CLI verb for CI. Ships Layer A; Layer B (LLM tie-break) is reserved
for v0.18.

## New module: src/core/routing-eval.ts

The harness. Pure functions:

- `normalizeText(s)`: lowercase, strip non-alnum to spaces, collapse
  whitespace. Unicode-friendly, quote-agnostic, punctuation-tolerant.
- `extractTriggerPhrases(cellText)`: split quoted alternatives like
  `"search for", "find me"` into separate normalized phrases; fall
  back to the whole cell when unquoted (OpenClaw-style descriptions).
- `indexResolverTriggers(resolverContent)`: build a skill-slug →
  normalized-trigger-phrases map from the resolver table.
- `structuralRouteMatch(intent, index)`: substring-match the
  normalized intent against every trigger phrase; return the set of
  matched skills + whether the match was ambiguous (more than one
  specific skill, excluding always-on family).
- `lintRoutingFixtures`: rejects fixtures whose intent is
  verbatim-equal to a trigger (D-CX-6: fixtures must paraphrase the
  framing, not copy the trigger text) and unknown expected_skill
  references.
- `loadRoutingFixtures(skillsDir)`: walks `skills/<name>/routing-eval.jsonl`,
  handles JSONL line-comments (`//` / `#`), collects malformed lines
  separately without crashing.
- `runRoutingEval(resolver, fixtures)`: pure scoring. Supports
  negative cases (`expected_skill: null` — nothing should match) and
  an `ambiguous_with` allow-list for skills that co-fire with
  always-on handlers (signal-detector, brain-ops, ingest).

Outcomes per fixture: `pass`, `missed`, `ambiguous`, `false_positive`.
Metrics: `top1Accuracy`, `passed`, `missed`, `ambiguous`,
`falsePositives`.

## Integration: check-resolvable runs Layer A by default

`checkResolvable()` now loads `routing-eval.jsonl` fixtures from every
skill, runs the structural eval, and appends non-pass outcomes as
warning-severity issues. New issue types:

- `routing_miss`        — expected skill did not match
- `routing_ambiguous`   — expected matched AND unexpected skills
- `routing_false_positive` — negative case unexpectedly matched
- `routing_fixture_lint` — linter or malformed-JSONL finding

All four are warnings — routing issues don't break exit in default
mode, but `--strict` promotes them (D-CX-3 contract). Advisories
without breaking CI.

## New CLI verb: `gbrain routing-eval`

Standalone Check 5 runner. `--json` envelope, `--llm` flag reserved,
`--skills-dir` override. Exit codes: 0 clean, 1 any failure/lint, 2
setup error. Suitable for CI gating separately from check-resolvable.

Removed from DEFERRED in CLI: `{check: 5, name: trigger_routing_eval}`.
Check 6 (brain_filing) still deferred; lands in W3.

## Seed fixtures

- skills/query/routing-eval.jsonl
- skills/citation-fixer/routing-eval.jsonl (includes a negative case)

These are intentionally modest. Additional fixtures per skill are the
natural next step; routing-eval itself passes cleanly under
check-resolvable default mode even when fixtures surface real gaps
(they're warnings, not errors). Running `gbrain routing-eval` reveals
the gaps immediately.

## Tests (34 new cases + updated integrations)

- test/routing-eval.test.ts: full harness coverage including
  normalization, trigger extraction (quoted and unquoted), indexer,
  structural match with ambiguity + always-on exemption, fixture
  linter (verbatim-equality rule, unknown-skill rule, shape rule,
  negative-case skip), JSONL loader (comments, malformed lines,
  missing dirs, underscore/dot skipping), and every runRoutingEval
  outcome (pass, miss, ambiguous, negative-pass, false-positive, empty).

- test/check-resolvable-cli.test.ts: updated DEFERRED unit test +
  `--json` envelope test + `--verbose` test to reflect Check 5
  shipping.

140/140 passing across the W1 + W2 surface.

## Live smoke

`gbrain routing-eval --json` against the current gbrain repo: 6
fixtures, 1 passing, 5 missed. The misses correctly surface
resolver-trigger narrowness (intents users naturally phrase differently
than trigger text). Fixtures will iterate in follow-up PRs; the
machinery ships now.

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

* feat: v0.17.0 W3 — Check 6 brain filing audit

Check 6 ships. Every skill that writes brain pages is now audited
against a machine-readable filing-rules doc at
`skills/_brain-filing-rules.json`.

## New: skills/_brain-filing-rules.json

Canonical filing rules, JSON (D-CX-8: the pre-existing yaml-lite
parser handles flat maps only, so YAML would have needed a new
dependency for one file). The companion `_brain-filing-rules.md`
stays as the human explainer. 14 rule entries + explicit
`sources_dir` carve-out for bulk/raw data.

## New module: src/core/filing-audit.ts

- `loadFilingRules(skillsDir)`: returns parsed doc or null (missing
  file → no-op; malformed JSON throws loud).
- `allowedDirectories(rules)`: normalized set of every rules[]
  directory + sources_dir.
- `runFilingAudit(skillsDir)`: walks skills/*/SKILL.md, parses
  frontmatter, audits any skill with `writes_pages: true`.

Two checks per qualifying skill:
  1. `writes_to:` list is non-empty.
  2. Every entry in `writes_to:` appears in allowedDirectories.

Both failures emit warning-severity issues. No errors — advisories
only, per D-CX-3.

## Distinction: writes_pages vs mutating (D-CX-7)

v0.17 introduces a new boolean frontmatter field `writes_pages:`.
`mutating: true` already means "has any side effect" (cron
schedulers, report writers, config mutators). Filing audit targets
ONLY skills with `writes_pages: true`, correctly excluding side-
effect-but-not-page-writing skills. The codex outside voice caught
this: conflating the two fields would drag ~100 skills into
filing-audit noise in the reference OpenClaw deployment.

## Integration: check-resolvable runs Check 6 by default

`checkResolvable()` calls `runFilingAudit(skillsDir)` and appends
issues as warnings. On missing/malformed rules doc, surfaces a
single advisory rather than bailing.

`DEFERRED` array in the CLI is now empty — v0.17 ships both Check 5
(W2) and Check 6 (W3). The export stays in place (stable --json
field) for future deferred checks.

## Seeded frontmatter on 7 canonical writers

Added `writes_pages: true` + `writes_to:` to:
- brain-ops (people, companies, deals, concepts, meetings)
- enrich (people, companies)
- ingest (people, companies, concepts, meetings, sources)
- idea-ingest (people, concepts, sources)
- media-ingest (concepts, people, companies, sources)
- meeting-ingestion (meetings, people, companies)
- signal-detector (people, companies, concepts)

Live smoke: `gbrain check-resolvable --json` on gbrain repo shows
`ok: true`, zero filing errors, zero filing warnings on seeded
skills. Every other mutating:true skill (citation-fixer,
cron-scheduler, data-research, maintain, migrate, minion-orchestrator,
reports, setup, skill-creator, soul-audit, webhook-transforms)
correctly skipped as side-effectful-but-not-page-writing.

## Tests (17 new cases + 3 updated CLI integrations)

test/filing-audit.test.ts covers:
  - rules loader: missing (null), valid, malformed (throw),
    non-array rules (throw)
  - directory normalization (trailing slash, leading slash)
  - clean case
  - missing writes_to on writes_pages:true
  - unknown directory
  - D-CX-7: mutating:true alone does not trigger audit
  - writes_pages:false skips
  - no frontmatter skips
  - inline `writes_to: [a, b]` syntax
  - block `writes_to:\n  - a` syntax
  - sources/ allowed
  - underscore/dot dir skipping
  - total counts (totalScanned vs writesPagesSkills)
  - missing dir graceful
  - action string quality guard

Plus: CLI integration tests updated for empty DEFERRED array (Checks
5 and 6 both shipped).

158/158 passing across the v0.17 foundation + W1 + W2 + W3 surface.

## v0.18 preview (D-CX-13)

v0.17 filing-audit is declaration-level only. A future
`gbrain filing-audit --pages` walks the brain itself, infers primary
subject from page content via LLM judgment, and flags actual
misfilings vs. declarations. Declaration audit is the leading
indicator; pages audit is the ground truth.

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

* feat: v0.17.0 W4 — gbrain skillify {scaffold,check} subcommand namespace

The essay's "skillify it!" verb becomes a CLI primitive pair. Two
subcommands, both promoted/factored so there's one source of truth:

## `gbrain skillify scaffold <name>` (mechanical)

Pure file generation. Zero LLM, zero judgment. Writes 5 stub files
atomically:

  1. skills/<name>/SKILL.md              frontmatter + body template
  2. skills/<name>/scripts/<name>.mjs    deterministic-code stub
  3. skills/<name>/routing-eval.jsonl    routing fixture seed
  4. test/<name>.test.ts                 vitest skeleton
  5. Appended trigger row to the detected resolver file (RESOLVER.md
     or AGENTS.md — whatever W1's auto-detect found)

Flags: --description (required), --triggers, --writes-to,
--writes-pages, --mutating, --force, --dry-run, --json, --skills-dir.

Kebab-case name validation (`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`).
Works against gbrain-native RESOLVER.md layout AND OpenClaw-native
AGENTS.md-at-workspace-root layout (W1 interop).

## `gbrain skillify check [path]` (audit)

Promoted from scripts/skillify-check.ts per codex D-CX-2. The legacy
script stays as a 12-line shim that delegates to the new module so
existing callers (docs, cron, tests) keep working.

Wrapped in a subcommand namespace: `gbrain skillify {scaffold, check}`
is one coherent verb for the whole post-task loop. The essay's
"skillify it!" triggers the markdown skill, which orchestrates the
CLI primitives.

## Idempotency contract (D-CX-7)

`skillify scaffold --force` regenerates stub FILES but never re-appends
a resolver row that already references `skills/<name>/SKILL.md`.
Unit test pins this: two applies produce one resolver row, not two.

## D-CX-9 SKILLIFY_STUB sentinel

Every scaffolded script + SKILL.md body carries a SKILLIFY_STUB
sentinel. `check-resolvable` walks every skill's script dir looking
for the marker and emits a `skillify_stub_unreplaced` warning when
found. Default mode: advisory. `--strict` mode: error, blocks CI.

This is the gate that catches "we scaffolded and forgot to implement"
— the exact failure codex flagged as "scaffold verification is
theater" in the outside-voice review.

## Files

- NEW src/core/skillify/templates.ts (template strings)
- NEW src/core/skillify/generator.ts (planScaffold / applyScaffold +
  SkillifyScaffoldError with typed error codes)
- NEW src/commands/skillify.ts (top-level dispatcher + scaffold handler)
- NEW src/commands/skillify-check.ts (promoted check logic)
- scripts/skillify-check.ts: rewritten to 12-line shim
- skills/skillify/SKILL.md: Phase 2 now references the scaffold
  primitive; legacy manual path kept for extending existing skills
- src/cli.ts: `skillify` added to CLI_ONLY + dispatcher
- src/core/check-resolvable.ts: SKILLIFY_STUB sentinel scan + new
  issue type `skillify_stub_unreplaced`

## Tests (14 new scaffold cases)

test/skillify-scaffold.test.ts covers:
  - SKILL_NAME_PATTERN validation (kebab-case, no spaces, no
    leading digit, no underscores/uppercase)
  - planScaffold against fresh + existing-file + --force paths
  - SKILLIFY_STUB sentinel presence in SKILL.md AND script stub
    (both gate paths)
  - D-CX-7 idempotency: resolverAppend null when row pre-exists,
    second apply doesn't duplicate the row
  - TBD-trigger placeholder when --triggers empty
  - writes_pages / writes_to / mutating flow through to frontmatter
  - applyScaffold writes files + appends resolver
  - Full AGENTS.md-layout workspace interop (W1)

Existing test/skillify-check.test.ts still passes against the legacy
shim — zero regression for downstream consumers.

178/178 passing across v0.17 foundation + W1..W4.

## Live smoke

\`gbrain skillify scaffold webhook-verify --description "verify incoming
webhook signatures" --triggers "verify webhook,check tunnel"
--skills-dir /tmp/smoke --dry-run\` produces the expected 4-file plan
plus a 115-byte resolver append. \`--help\` works on both the top-level
and scaffold levels.

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

* feat: v0.17.0 W5 — gbrain skillpack install (deps closure + lockfile + diff/dry-run)

The essay's "drop it into YOUR OpenClaw" promise lands as a CLI
verb. One command installs a curated bundle of gbrain skills + the
shared convention files they depend on into a target OpenClaw
workspace. Data-loss protected, concurrency-safe, atomic on the
AGENTS.md managed block.

## openclaw.plugin.json refresh

- Bumped version from stale 0.4.1 → 0.17.0 (codex flagged this drift
  F-ENG-4 / D-CX-4).
- Expanded curated skill list from 7 → 25. Uses skills/manifest.json
  top-level (v0.10.0 sourced) minus setup/migrate/publish
  (install-time / code+skill pairs) minus private skills.
- Added \`shared_deps: [...]\` listing convention files every skill
  references: conventions/, _brain-filing-rules.{md,json},
  _output-rules.md. Installer always pulls these (D-CX-10
  dependency closure).
- Added \`excluded_from_install: [...]\` for setup/migrate/publish —
  surfaces the intentional exclusion as data rather than a comment.

## New module: src/core/skillpack/bundle.ts

- \`findGbrainRoot(start)\` — walks up looking for openclaw.plugin.json
  + src/cli.ts. The pair identifies a gbrain checkout.
- \`loadBundleManifest(root)\` — strict validation + typed BundleError
  codes (manifest_not_found, manifest_malformed, skill_not_found).
- \`enumerateBundle({gbrainRoot, skillSlug?, manifest})\` — flat list
  of source → target-relative paths. When skillSlug is set, scopes
  to that one skill BUT always pulls shared_deps. \`--all\` walks every
  skill in the manifest.
- \`bundledSkillSlugs(manifest)\` — sorted slugs for \`skillpack list\`.

## New module: src/core/skillpack/installer.ts

- \`planInstall(opts)\` — builds InstallPlan with per-file
  existing/identical diff state. Pure; no writes.
- \`applyInstall(plan, opts)\` — writes files + managed block with
  the contracts below.
- \`diffSkill(root, slug, skillsDir)\` — read-only per-file status
  for \`skillpack diff <name>\`.

**Per-file diff protection (D-CX-3 / F4):**
  wrote_new            fresh file
  wrote_overwrite      local diff + --overwrite-local passed
  skipped_identical    bytes match the bundle (silent re-install)
  skipped_locally_modified  target differs + no --overwrite-local
  → PROTECTED DEFAULT

**Concurrency + atomic AGENTS.md (D-CX-11):**
  - \`.gbrain-skillpack.lock\` at workspace root. Acquired on the
    first write, released in finally.
  - Lock stale threshold configurable (default 10min). --force-unlock
    overrides.
  - Managed-block writes via tmp-file-plus-rename (atomic on POSIX).

**Managed-block format:**
  <!-- gbrain:skillpack:begin -->
  <!-- Installed by gbrain <version> — do not hand-edit between markers. -->
  | Trigger | Skill |
  |---------|-------|
  | "alpha" | \`skills/alpha/SKILL.md\` |
  | ...
  <!-- gbrain:skillpack:end -->

  extractManagedSlugs() roundtrips: single-skill installs accumulate
  into the same block rather than overwriting each other.

## New CLI: gbrain skillpack {list, install, diff, check}

Namespaced alongside W4's \`gbrain skillify\`. Subcommands:
  list             bundle inventory (human + --json)
  install <name>   single skill + deps closure
  install --all    entire curated bundle
  diff <name>      per-file diff vs target; read-only
  check            delegates to the pre-existing skillpack-check
                   (same CLI just namespaced)

Flags on install: --overwrite-local, --force-unlock, --dry-run,
--json, --skills-dir, --workspace.

Exit codes: 0 clean, 1 files skipped (protected local edits),
2 setup error / lock held.

## Live smoke

\`gbrain skillpack list\`: 25 skills. \`skillpack install query --dry-run\`
against a fresh temp workspace: 12 files planned (SKILL.md,
routing-eval.jsonl, 7 convention files, 3 rule files, managed block
to AGENTS.md). All shared_deps flagged [shared].

## Tests (36 new cases)

test/skillpack-install.test.ts:
  - findGbrainRoot walks up, returns null when absent
  - loadBundleManifest validates + rejects malformed
  - enumerateBundle pulls shared_deps on single-skill scope (D-CX-10)
  - buildManagedBlock + updateManagedBlock: append when absent,
    in-place replace when present, extractManagedSlugs roundtrip
  - planInstall + applyInstall: fresh install, dry-run, idempotency
    (skipped_identical), local-edit protection, --overwrite-local,
    lock-held concurrency (D-CX-11), --force-unlock, atomic
    managed-block write, multi-skill accumulation in managed block,
    AGENTS.md-at-workspace-root interop (W1 cross-check)
  - diffSkill: missing, identical, differs

test/skillpack-sync-guard.test.ts (F-ENG-4):
  - both manifests exist
  - every skill in plugin.json exists on disk
  - every shared_dep exists on disk
  - plugin.json skills ⊂ skills/manifest.json
  - excluded skills aren't in the install list
  - plugin version ≥ 0.17 (kills the 0.4.1 stale drift)

204/204 passing across the v0.17 foundation + W1..W5.

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

* feat: v0.17.0 guards — privacy scrub + OpenClaw-reference E2E + v0.16.4 regression

Three ship-blocker work items from the eng review + codex outside
voice round out v0.17:

## scripts/check-privacy.sh (CLAUDE.md:550 enforcement)

Greps for the banned OpenClaw fork name (case-insensitive) across
tracked files. Two modes:
  scripts/check-privacy.sh           scan working tree
  scripts/check-privacy.sh --staged  scan git-staged files (pre-commit)

Exit 1 on any finding outside the allow-list. Allow-list covers files
where the name is legitimately present: this script itself (defines
the rule), CLAUDE.md (the canonical rule text), llms-full.txt
(auto-generated from CLAUDE.md), the historical upgrade guide, and
test/integrations.test.ts (whose personal-info regex ENFORCES the
rule against recipes/).

Scrubbed existing leaks:
  - CHANGELOG.md:366 reference in a closes-# line → "from the
    OpenClaw reference deployment"
  - test/doctor-minions-check.test.ts:171 comment → "an OpenClaw
    host's cron script"
  - test/plugin-loader.test.ts fixture plugin name → "openclaw-ref"

## test/e2e/openclaw-reference-compat.test.ts (ship-blocker gate)

The test that proves v0.17 delivers on the headline claim. New
fixture at test/fixtures/openclaw-reference-minimal/ mimics the
reference OpenClaw deployment layout: AGENTS.md at workspace root,
skills/ below, no manifest.json. Four fixture skills
(signal-detector, query, brain-ops, context-now).

Every v0.17 surface gets exercised end-to-end:
  - autoDetectSkillsDir with $OPENCLAW_WORKSPACE (D-CX-4 priority)
  - loadOrDeriveManifest walks SKILL.md (F-ENG-1 auto-manifest)
  - checkResolvable accepts AGENTS.md at workspace root, all 4
    skills reachable via resolver rows, zero errors
  - Filing audit clean (brain-ops declares writes_pages+writes_to)
  - CLI subprocess via `--skills-dir` → exit 0
  - CLI subprocess via $OPENCLAW_WORKSPACE (no flag) → exit 0,
    correct skillsDir detection
  - skillpack install against the layout writes managed block into
    AGENTS.md at workspace root

This is THE ship-blocker test. If the W1 + W5 stack ever regresses
against an AGENTS.md-layout workspace, this fails first.

## test/regression-v0_16_4.test.ts (F-ENG-8)

Guards v0.17 against adding "surprise" warnings. Builds a clean
fixture matching v0.16.4 canonical shape (manifest.json, RESOLVER.md,
2 skills, no routing-eval fixtures, no writes_pages). Runs v0.17
checkResolvable and asserts:
  - zero errors, zero routing_*/filing_*/skillify_stub_* warnings
  - JSON envelope keys unchanged (errors, warnings, issues, ok,
    summary) — deprecated `issues[]` still equals errors ∪ warnings
  - summary shape unchanged

If someone adds a new check that fires unexpectedly on a v0.16.4-era
fixture, this test catches it immediately.

## Fixture

test/fixtures/openclaw-reference-minimal/
├── AGENTS.md                       (4 rows, 3 sections)
└── skills/
    ├── brain-ops/SKILL.md          (writes_pages+writes_to)
    ├── context-now/SKILL.md
    ├── query/SKILL.md
    └── signal-detector/SKILL.md

Intentionally small (4 skills, 1 AGENTS.md, ~30 lines total) so the
fixture is maintainable. The OPENCLAW-reference deployment has 107
skills — this fixture is the minimum shape that exercises the full
v0.17 code path.

## Tests

215/215 passing across the full v0.17 surface:
  - foundation + W1 + W2 + W3 + W4 + W5 (204)
  - regression-v0_16_4 (3)
  - openclaw-reference-compat (7)
  - privacy guard (separate bash; exits 0 clean)

Plus: privacy pre-commit hook is a drop-in wrapper (documented in
the script header). Wiring into .github/workflows is a follow-up.

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

* release: v0.17.0 — skillify goes end-to-end

Every skill. Every check. Every install. One command each.

Five workstreams land in one release:
  - W1: AGENTS.md + auto-manifest + env-priority
  - W2: Check 5 routing eval
  - W3: Check 6 brain filing
  - W4: gbrain skillify {scaffold,check}
  - W5: gbrain skillpack {list,install,diff}

Plus D-CX-3 foundation (errors/warnings split + --strict), plus
codex outside-voice fixes (D-CX-1..12 applied), plus privacy pre-
commit guard, plus OpenClaw-reference E2E fixture, plus v0.16.4
regression guard.

Live against the reference OpenClaw deployment: 102 skills detected
via auto-manifest, 15 unreachable errors + 108 warnings surfaced —
exactly the essay's "~15% dark" finding. The magic word from the
essay finally works the way the essay describes.

Tests: 2156 unit (178 new) + 152 E2E Tier 1 + 3 Tier 2 + 8 new
openclaw-reference fixture cases. 0 failures across all tiers.
Plan + reviews: ~/.claude/plans/p1-lets-just-vast-blanket.md.

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

* fix(test): add missing 'strict' field to 5 Flags literals in check-resolvable-cli.test.ts

CI failed `tsc --noEmit` after the D-CX-3 errors/warnings split added
`strict: boolean` as a required field on the `Flags` interface. Five
test sites in test/check-resolvable-cli.test.ts still construct
Flags object literals (for direct `resolveSkillsDir()` calls) and
hadn't been updated.

Added `strict: false` to all five literals:
  - line 129  --skills-dir absolute path
  - line 135  --skills-dir relative path
  - line 148  no --skills-dir
  - line 160  no --skills-dir + no env
  - line 178  --skills-dir + OPENCLAW_WORKSPACE (REGRESSION-GATE)

Unit tests: 207/207 pass across the v0.19 surface. tsc --noEmit
exits 0.

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

* docs: adopt gstack's branch-scoped CHANGELOG rule + rewrite v0.19.0 entry

CLAUDE.md gains a new top section before "CHANGELOG voice" that codifies
what gstack's CLAUDE.md already says: CHANGELOG is user-facing product
release notes, not a log of internal decisions. Every entry describes
what THIS branch adds vs master. Plan-file IDs, decision tags (D-CX-#,
F-ENG-#), review rounds, test counts as marketing, and contributor-
facing metrics don't belong in it.

The v0.19.0 entry is rewritten to the new bar:

Removed:
- Version-collision note about v0.17.0/v0.18.0 shipping on master
- All D-CX-## and W# tags (meaningless outside the plan file)
- "codex caught" / CEO + Eng review round-up narrative
- Plan file path reference
- "215 new cases across 13 test files" marketing metrics
- W1..W5 bucketing in itemized changes

Kept / sharpened:
- User-facing headline (what your agent can now do)
- Numbers that mean something to users (unreachable-skills count,
  scaffold timing, pre/post AGENTS.md support)
- Upgrade instructions
- Added/Changed/Fixed/For-contributors itemized sections (standard
  keep-a-changelog shape)

Version sequence (`grep "^## \["`) is contiguous v0.19.0 → v0.16.4.
Privacy guard clean. Tests green.

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

* docs: update README/CLAUDE/TODOS for v0.19.0 skills + skillify loop

Skill count was stale (README said 26, actual is 28: skillify + skillpack-check
were missing from the tables and count). Corrected throughout. Marked TODOS item
"Checks 5 + 6 deferred in PR #325" as completed in v0.19 — they shipped as real
implementations, not just filed issues.

README:
- Skill count 26 → 28 (headline, install flow, table section, architecture diagram)
- Added `skillify` + `skillpack-check` rows to the operational skills table
- Rewrote the "Skillify" section to lead with the four v0.19 CLI verbs
  (`gbrain skillify scaffold/check`, `gbrain skillpack list/install/diff`,
  `gbrain routing-eval`, `gbrain check-resolvable --strict`) instead of
  describing the pre-v0.19 state. Added the "works on your OpenClaw" pitch
  around AGENTS.md + auto-manifest. Added the "drop 25 curated skills into
  your OpenClaw" section for skillpack install.
- Added v0.19 skills block + v0.18 multi-source + v0.17 dream to the Commands
  reference at the bottom.
- Standalone instruction sets count: 25 → 28 (with a parenthetical noting
  the curated 25-skill bundle that `skillpack install` ships).

CLAUDE.md:
- Skill count 26 → 28 in the Skills section.
- New "Skillify loop (v0.19)" sub-bullet listing skillify + skillpack-check.
- Noted that `AGENTS.md` is also accepted as a resolver filename.

TODOS.md:
- Created "## Completed" section at the top.
- Moved the "Checks 5 + 6" item there with completion note linking to the
  actual implementation files (routing-eval.ts + filing-audit.ts).

Privacy scan clean. Version sequence contiguous v0.19.0 → v0.16.4.

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

* fix(test): regenerate llms-full.txt + llms.txt after README/CLAUDE edits

CI failed on `build-llms generator > committed llms.txt + llms-full.txt
match current generator output`. The drift was expected: the prior
commit edited README.md and CLAUDE.md (skill count + skillify section),
both of which are inlined into llms-full.txt by `scripts/build-llms.ts`.

Fix: `bun run build:llms` + commit the regenerated output.

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

---------

Co-authored-by: Wintermute <wintermute@garrytan.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 19:34:27 -07:00
08b3698e90 v0.18.2: migration hardening — integrity fix + reserved-connection primitive (#356)
* fix: migration hardening — timeout handling, lock detection, diagnostics

Addresses all 8 issues from the v0.18.0 production upgrade field report:

1. LATEST_VERSION now uses Math.max() instead of array-last (was wrong
   when MIGRATIONS array is out of order: [.., 23, 22, 21, 20, 15, 16])

2. Pre-flight lock check: runMigrations() queries pg_stat_activity for
   idle-in-transaction connections >5min before attempting DDL, prints
   PIDs and kill advice

3. SET LOCAL statement_timeout = 600s inside migration transactions for
   Supabase compatibility (server-enforced timeout overrides session SET)

4. Catches Postgres error 57014 (statement_timeout) with actionable
   diagnostics instead of raw stack trace

5. Better progress output: prints schema version range, migration names
   before/after, checkmarks on success

6. Migration 21 fix: drops files.page_slug_fkey before swapping the
   pages unique constraint (guarded for PGLite which has no files table)

7. idle_in_transaction_session_timeout = 5min on all Postgres connections
   (both instance-level and module-level) to prevent 24h stale locks

8. apply-migrations CLI warns when schema migrations are pending, since
   it only runs orchestrator migrations (System B) not schema DDL (System A)

All 34 migrate tests pass. Typecheck clean.

* feat(engine): BrainEngine.withReservedConnection() primitive + DRY session defaults

Adds a ReservedConnection interface and withReservedConnection(fn) method to
BrainEngine. Postgres uses postgres-js sql.reserve() to pin a single backend for
the callback; PGLite passes through its single backing connection. Used
immediately for non-transactional DDL timeout handling (next commit) and
foundation for the future write-quiesce design.

Extracts setSessionDefaults(sql) helper in db.ts, absorbing the duplicated
idle_in_transaction_session_timeout block that was copy-pasted between db.ts and
postgres-engine.ts (Gap 5 / ER-C1). Single write site, both connect paths call
the helper now.

Codex plan-review flagged that advisory-lock designs on postgres.js pools
require a reserved-connection primitive; this is that primitive.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(migrate): close v21/v23 integrity window + non-transactional DDL timeout

Two codex-caught issues that both the initial review and the engineering review
missed:

1. Migration 21 integrity window. Original v21 dropped files_page_slug_fkey and
   persisted config.version=21, leaving files WITHOUT any FK to pages until v23
   ran and added the replacement files.page_id. Process death between v21 and
   v23 left files unconstrained while file_upload / `gbrain files` kept
   accepting writes. Fix: v21 uses sqlFor to split engines (Postgres gets
   additive-only, PGLite gets the full UNIQUE swap since it has no concurrent
   writers). v23's handler now wraps the FK drop + UNIQUE swap + page_id
   addition + backfill + ledger creation in one engine.transaction(). Atomic.

2. Non-transactional DDL timeout gap. runMigrationSQL's else-branch (for
   migrations with transaction:false, like CREATE INDEX CONCURRENTLY) ran the
   DDL on the shared pool with no timeout override. Supabase's 2-min server
   statement_timeout would abort a CONCURRENTLY index on any large table.
   Fix: use engine.withReservedConnection + SET statement_timeout='600000'
   inside the isolated connection.

Also: extracted getIdleBlockers(engine) helper — single source of truth for the
pg_stat_activity query. Shared by the DDL pre-flight warning and the new
`gbrain doctor --locks` CLI (next commit).

57014 diagnostic rewritten to the 4-part "what / why / fix / verify" pattern.
No longer references a non-existent CLI flag.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(doctor): gbrain doctor --locks CLI flag

The v0.18.0 57014 diagnostic referenced `gbrain doctor --locks` but the flag
didn't exist. Users hitting statement_timeout would run the suggested command
and get "unknown option". Implemented now.

On Postgres: queries pg_stat_activity via the new getIdleBlockers() helper,
prints each blocker's PID, state, query_start, truncated query, and the exact
`SELECT pg_terminate_backend(<pid>);` command. Exits 1 on blockers, 0 on clean.

On PGLite: prints "not applicable" (no pool, no idle-in-tx concept) and exits
0. The flag is a safe no-op there.

--json emits structured output: {status, blockers: [...]}.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* test: migration hardening regression guards (unit + E2E)

test/migrate.test.ts — 10 new regression guards:
- LATEST_VERSION equals max(versions) under any array order. Guards against
  regression to array[-1] (the field report's "told I'm at v16 while 7
  migrations behind" bug).
- getIdleBlockers shape: pglite returns [], postgres returns rows, query
  failure returns [] (not throw).
- 57014 catch path: mocked engine throws err.code='57014', assert the 4-part
  diagnostic hits stderr with what/why/fix/verify markers.
- apply-migrations pre-flight warning structural check.
- setSessionDefaults DRY check: helper defined once in db.ts, postgres-engine
  calls it, neither path inlines the SET.
- runMigrationSQL reserved-connection usage structural check.
- Migration 21 test updates for engine-split sqlFor (codex restructure).
- Migration 23 atomic-transaction assertion.

test/e2e/migrate-chain.test.ts (new): 11 E2E tests against real Postgres:
- Post-chain schema invariants (composite UNIQUE exists, old pages_slug_key
  gone, files_page_slug_fkey gone, files.page_id column present,
  file_migration_ledger table populated).
- doctor --locks real-PG integration (second connection + BEGIN + idle,
  assert the PID appears in pg_stat_activity).
- runMigrationsUpTo advances config.version to target, not past.
- withReservedConnection round-trip (executes queries, session GUC visible
  inside callback).

test/e2e/helpers.ts: new runMigrationsUpTo(engine, targetVersion) and
setConfigVersion(version) helpers. The v15→v23 chain E2E needed a way to stop
at intermediate schema versions; neither `gbrain init --migrate-only` nor the
existing setupDB() supported this. Codex caught that the proposed E2E wasn't
implementable without new harness work.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

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

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs(changelog): rewrite v0.18.2 entry to match gstack CLAUDE.md format

Applied the gstack CHANGELOG style rules from ~/git/gstack/CLAUDE.md:

- Two-line bold headline lands a verdict, not a feature list.
- Single coherent lead story instead of "Second headline... Third headline..."
- "The numbers that matter" table with BEFORE / AFTER / Δ columns, counted
  against the v0.18.0 field report (the concrete source).
- "What this means for your workflow" closing paragraph with the 4-command
  recovery path.
- TODOS.md references removed from user-facing body (explicit rule: never
  mention TODOS, internal tracking, or contributor-facing details in the
  user-read portion).
- Contributor-only detail (helper extraction, test file paths, interface
  specifics) moved to a "For contributors" subsection.
- Itemized changes reorganized as Added / Changed / Fixed / For contributors.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs(changelog): v0.18.2 voice-rule audit — headline, em dashes

Audit against ~/git/gstack/CLAUDE.md voice rules:

- Headline tightened from 32 words to 19 (rule says 10-14; repo convention
  on v0.18.1 was 22, this is closer).
- Em dashes removed from 7 lines. Replaced with commas, colons, or periods
  per the "no em dashes" rule.
- AI vocabulary audit: clean.
- Banned phrases audit: clean.

Content unchanged. Only voice/punctuation.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: root <root@localhost>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-23 10:39:28 -07:00
275158137a fix: v0.18.1 — RLS hardening + schema backfill (supersedes #336) (#343)
* fix(doctor): check ALL public tables for RLS, not just gbrain's own

The RLS check was hardcoded to only verify 10 gbrain-managed tables:
pages, content_chunks, links, tags, raw_data, page_versions,
timeline_entries, ingest_log, config, files.

Any other table in the public schema (created by the application,
extensions, or manually) was invisible to the check. This allowed
12 tables to exist without RLS for months — publicly readable by
anyone with the Supabase anon key.

Changes:
- Query ALL tables in public schema, not a hardcoded list
- Upgrade severity from 'warn' to 'fail' — missing RLS is a security
  issue, not a suggestion
- Include table count in success message for visibility
- Include remediation SQL in failure message

Supabase exposes the public schema via PostgREST. Any table without
RLS is readable/writable by the anon key by default.

* fix(schema): enable RLS on 10 gbrain-managed public tables

The base schema and prior migrations shipped 10 public tables
without Row Level Security enabled: access_tokens, mcp_request_log,
minion_inbox, minion_attachments, subagent_messages,
subagent_tool_executions, subagent_rate_leases, gbrain_cycle_locks,
budget_ledger, budget_reservations.

Supabase exposes the public schema via PostgREST, so tables without
RLS are readable and writable by anyone holding the anon key.
access_tokens and the subagent conversation history tables carry
the most sensitive data in the set.

Fix: add the missing ENABLE RLS statements to src/schema.sql
(inside the existing BYPASSRLS-gated DO block, so dev sessions
without bypass don't get locked out). Add a new schema migration
v17 rls_backfill_missing_tables that does the same on existing
brains. budget_ledger and budget_reservations were previously
migration-only (v12); promoted to the base schema so fresh installs
pick up RLS from the standard gate.

Regenerated src/core/schema-embedded.ts.

* fix(doctor): widen RLS check to all public tables, add GBRAIN:RLS_EXEMPT escape hatch

The RLS check was hardcoded to 10 gbrain-managed tables; any other
table in the public schema (plugin-created, user-created, extension-
created) was invisible to the check. Widen the scan to every
pg_tables row in the public schema.

Upgrade severity warn to fail. Missing RLS is a security issue, not
a suggestion. gbrain doctor now exits 1 when any public table lacks
RLS. Cron and CI wrappers that call gbrain doctor should be aware
of the exit-code flip.

Add an explicit escape hatch for tables that should stay readable
by the anon key on purpose (analytics, public materialized views,
plugin tables). The doctor reads pg_description for each non-RLS
table and treats a comment matching GBRAIN:RLS_EXEMPT reason=<why>
as an intentional exemption. Doctor enumerates exempt tables by
name on every successful run so they never go invisible.

There is no gbrain rls-exempt CLI subcommand by design. The escape
hatch is deliberately painful: operators drop to psql and type the
justification as raw SQL. Comment lives in pg_description, survives
pg_dump, shows up in schema diffs, and appears in shell history.

PGLite is now explicitly skipped with an ok status (embedded and
single-user, no PostgREST exposure). Previously hit the
db.getConnection() throw-catch path and surfaced a misleading warn.

Remediation SQL now quotes identifiers (ALTER TABLE "public"."<name>"
...) so it works on tables with hyphens, reserved words, or mixed
case.

See docs/guides/rls-and-you.md for the full user-facing guide.

* test: coverage for RLS hardening (doctor + migration + e2e)

Four layers of guard for the v0.18 RLS changes:

test/doctor.test.ts: source-grep structural regression guards on
the doctor RLS block — absence of the old tablename IN filter,
presence of status=fail on the gap branch, quoted-identifier
remediation SQL, PGLite skip wrapper, GBRAIN:RLS_EXEMPT parsing
with required reason=. Fast, no DB needed. Mirrors the
statement_timeout regression pattern in test/postgres-engine.test.ts.

test/migrate.test.ts: structural guard for migration v17. Asserts
the migration exists with the expected name, all 10 ALTER TABLE
statements are present, BYPASSRLS gating is in place, and
LATEST_VERSION has caught up.

test/e2e/mechanical.test.ts: rewrote the E2E RLS Verification
block. The old hardcoded-allowlist query is replaced with an
every-public-table-has-RLS assertion. Four new CLI-spawn cases
verify real end-to-end behavior: (a) no-RLS public table makes
gbrain doctor --json return status=fail with ALTER TABLE in the
message and exit code 1, (b) a GBRAIN:RLS_EXEMPT comment with a
valid reason makes doctor report the table as explicitly exempt
and keep status=ok, (c) a GBRAIN:RLS_EXEMPT prefix without a
reason= segment still fails doctor, (d) an unrelated comment on
a no-RLS table still fails doctor.

All helpers use try/finally with unique-per-run suffixes
(gbrain_rls_..._<pid>_<timestamp>) so assertion failures don't
pollute subsequent tests.

* docs: one-page guide for RLS and GBRAIN:RLS_EXEMPT escape hatch

Covers why RLS matters on Supabase (PostgREST exposes the public
schema to the anon key), what to do when gbrain doctor fails, the
exact SQL template for an intentional exemption, how to audit
exemptions later, and how the check behaves on PGLite vs
self-hosted Postgres.

Emphasizes that the escape hatch is deliberately painful on
purpose: there is no gbrain rls-exempt CLI subcommand and no
config-file allowlist. The operator drops to psql and writes the
justification in SQL, which makes the action visible in shell
history, pg_dump, schema diffs, and doctor output on every run.

Referenced from gbrain doctor's failure message when any public
table lacks RLS.

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

Reconciles VERSION and package.json (were drifting: 0.17.0 vs
0.16.4). Runtime gbrain --version reads from package.json via
src/version.ts, so prior ships were reporting 0.16.4. Both now
land on 0.18.0.

Minor bump (not patch) because gbrain doctor's exit code semantics
change: missing RLS on a public table was warn+exit-0, is now
fail+exit-1. Any external cron, CI, or skillpack-check wrapper
around gbrain doctor needs to be aware. skillpack-check.ts itself
is unaffected (uses --fast, skips DB checks).

CHANGELOG entry follows the release-summary format from CLAUDE.md:
headline, lead paragraph, numbers-that-matter table, what-this-
means-for-your-workflow, To take advantage of v0.18.0 block with
remediation SQL + exemption format, itemized changes.

Also sweeps a stale @Wintermute reference in the 0.17.0 entry to
"Garry's OpenClaw" per the CLAUDE.md privacy rule.

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

* fix(v0.18.1): address codex review (orchestrator wiring + fail-closed + identifier escape)

Four fixes from `/codex` review of the merged diff:

1. HIGH — wire migration v24 into the `gbrain apply-migrations`
   upgrade path. Without an orchestrator entry, `gbrain upgrade`'s
   post-upgrade step runs `apply-migrations --yes`, which walks the
   registry in `src/commands/migrations/index.ts`. The registry
   stopped at v0_18_0, so v24 never fired on upgrade (connectEngine
   and doctor do not call initSchema). New `v0_18_1.ts` orchestrator
   mirrors v0.18.0's Phase A: shells out to `gbrain init
   --migrate-only`, which triggers initSchema → runMigrations → v24
   applies. Registered in the migrations array.

2. HIGH — fail loudly when v24 runs under a non-BYPASSRLS role
   instead of RAISE WARNING-then-silently-bumping-version. The
   runner at migrate.ts:773 unconditionally calls
   `setConfig('version', String(m.version))` when a migration
   completes without throwing, so a WARNING-and-continue path would
   permanently lock the backfill out: schema_version=24 on the next
   run means `m.version > current` is false and v24 is skipped
   forever, even after the role gets BYPASSRLS. Changed `RAISE
   WARNING` → `RAISE EXCEPTION` so the transaction aborts,
   schema_version stays at 23, and a subsequent initSchema retries
   cleanly after the role is fixed. Test asserts the SQL uses
   EXCEPTION and does not use WARNING.

3. MEDIUM — escape double-quote characters in the remediation SQL
   output. doctor.ts was building `ALTER TABLE "public"."${n}"`
   with `n` un-escaped, so a pathological table name containing a
   literal `"` would break out of the quoted identifier and produce
   invalid copy-paste SQL. Double the `"` before interpolating,
   matching Postgres quoted-identifier escaping rules. Extremely
   rare in practice, cheap to get right.

4. LOW — CHANGELOG cleanup: corrected the upgrade-behavior claim
   (v24 runs via `apply-migrations --yes` through the new
   orchestrator, not during `gbrain doctor`) and split the "tables
   with RLS" row into two metrics (21 base-schema tables + 2
   migration-only budget_* tables = 23 managed total, all covered).

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

* test: add v0.18.1 to apply-migrations skippedFuture expectations

CI-only failure: test/apply-migrations.test.ts hardcodes the
orchestrator-migration version list in two `skippedFuture` expectations.
The v0.18.1 orchestrator I added in the prior commit pushed the list to
8 entries. Both assertions now include 0.18.1 at the tail.

Caught by the gbrain CI run on the merged branch — locally the rest of
the unit suite (dream/orphans) is flaky due to unrelated PGLite
parallelism, but `bun test test/apply-migrations.test.ts` now passes
18/18. CI should follow.

* docs: scrub v0.18.1 CHANGELOG — remove specific-table attack surface

Responsible-disclosure pass on the public-facing release notes. The
prior CHANGELOG entry enumerated which gbrain-managed public tables
had shipped without RLS and highlighted the most sensitive ones by
name. That gives anyone reading the CHANGELOG a directed probe list
for unpatched Supabase installs before operators have had a chance
to run `gbrain upgrade`.

Rewritten to describe the change at a functional level (what doctor
does now, what the upgrade path does, what the escape hatch is)
without naming the specific tables or quantifying the gap. The actual
SQL remains in the binary — anyone reverse-engineering can find it
there — but we shouldn't put it on the release page with a banner.

User-facing content kept intact: the "To take advantage of" block,
the upgrade commands, the exemption SQL template, the breaking
exit-code note.

* docs(CLAUDE.md): add responsible-disclosure rule for release notes

Prior incident on this branch: the original v0.18.1 CHANGELOG entry
enumerated the specific public tables that had shipped without RLS,
quantified the exposure duration, and highlighted the most sensitive
ones by name. Garry caught it. Scrubbed in ecd06a0.

This directive codifies the rule so future sessions (or other agents
working in this repo) don't repeat the mistake:

- Describe security fixes functionally, not by attack surface.
- Public artifacts (CHANGELOG, README, docs/, PR titles/bodies,
  commit messages, release pages) get the functional description.
- Private artifacts (plan files under ~/.claude/plans/ or
  ~/.gstack/projects/) keep the detailed before/after tables.
- Source code will disclose the specifics to reverse engineers
  anyway — that's intrinsic. The concern is the broadcast-channel
  asymmetry of a release page.

Also added a corresponding feedback memory at
~/.claude/projects/.../feedback_responsible_disclosure.md so the rule
carries across sessions and other projects, not just gbrain.

Placed right after the existing privacy rule (scrub real names) since
they share the same "public artifact hygiene" posture.

* chore: regenerate llms.txt + llms-full.txt (CLAUDE.md drift)

Adding the responsible-disclosure rule to CLAUDE.md in ffe340d
diverged the committed llms-full.txt from the generator output.
The build-llms drift-guard test caught it in CI. Regenerated.

* fix(v24): guard budget_ledger + budget_reservations with IF EXISTS

Garry flagged: migration v24 fires `ALTER TABLE budget_ledger ENABLE
ROW LEVEL SECURITY` unconditionally. budget_ledger and
budget_reservations are migration-only (v12) — not in schema.sql,
not re-created on every initSchema. In the normal flow v12 runs
before v24 so they exist, but two edge cases break that assumption:

  1. An operator manually dropped them (budget data is regenerable
     from resolver call logs, so `DROP TABLE` is a reasonable
     cleanup move).
  2. A brain was somehow running an old gbrain that lacked v12, and
     is only catching up now.

Bare ALTER hits 42P01 (relation does not exist), aborts the
transaction, and leaves schema_version at 23. On next initSchema,
v24 retries and hits the same error — stuck in a loop.

Fix: wrap each of the two budget ALTERs in
    IF EXISTS (SELECT 1 FROM information_schema.tables
                WHERE table_schema = 'public'
                  AND table_name = '<tbl>') THEN ... END IF;

The other 8 tables are not guarded. schema.sql creates them
idempotently on every initSchema run before migrations fire, so
they are guaranteed to exist by the time v24 runs. Adding guards
there would be unnecessary and make the SQL noisier.

Also simplified the DECLARE/BEGIN structure: moved the
non-BYPASSRLS early-exit to the top so the happy path reads
cleanly without the outer IF.

Tests:
  - test/migrate.test.ts: new assertion that both budget_* ALTERs
    are wrapped in information_schema.tables IF EXISTS blocks;
    BYPASSRLS gate assertion relaxed to match either phrasing.
  - Manual e2e: fresh Postgres init (v0→v24), then DROP TABLE
    budget_ledger + budget_reservations, reset version=23, re-run
    init. v24 applied cleanly, version advanced to 24, budget_*
    stayed dropped. Without the guard this would have errored out.

* test(e2e): v24 self-heals when budget_* tables are missing

Behavioral e2e proof for the IF EXISTS guard added in 2fc7780. Scenario:

  1. Fresh Postgres init to v24 (setupDB in beforeAll).
  2. DROP TABLE budget_ledger + budget_reservations.
  3. Roll config.version back to '23'.
  4. CLI-spawn `gbrain init --non-interactive` to re-trigger initSchema.
  5. Assert: exit 0, no 42P01 in stderr, version advances to 24,
     budget_* stay dropped (since v12 doesn't re-run at
     current=23 > v12=12).

Without the guard, step 4 hits 42P01 (relation does not exist),
aborts the transaction, leaves version at 23, and the next
initSchema re-runs v24 forever — an infinite retry loop. This test
catches any future regression that strips the guard.

Cleanup (finally block) restores budget_* with the exact migration
v12 schema so downstream tests that reference these tables see the
original shape. Version is restored from the pre-test snapshot.

Runs with the rest of the E2E: RLS Verification block. 78/78 in
test/e2e/mechanical.test.ts with the addition.

---------

Co-authored-by: Wintermute <wintermute@garrytan.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 07:17:40 -07:00
Garry TanandClaude Opus 4.7 90c5d93fce feat: v0.18.0 — multi-source brains (one DB, many repos, federation + dotfile resolution) (#337)
* feat(v0.17.0 step 1/9): sources primitive — additive-only multi-source foundation

Lane A of the multi-repo plan. Installs the sources table and seeds a
'default' row that inherits sync.repo_path/last_commit from existing
config. This is the bisectable foundation every later step builds on;
the breaking schema changes (composite UNIQUE, files FK rewrite,
resolution_type, ingest_log.source_id) land with their paired code
rewrites in Steps 2/4/5/7 so no single commit breaks the engine.

- migration v16 (sources_table_additive) + v0_17_0 orchestrator skeleton
- sort-by-version guard in runMigrations (array insertion order can
  never cause a later migration to skip a lower one again)
- default source seeded with config '{"federated": true}' so pre-v0.17
  brains keep single-namespace search semantics after upgrade
- orchestrator phase B detects absence of file_migration_ledger and
  no-ops until Step 7 lands it
- 8 new structural tests in test/migrate.test.ts (shape, idempotency,
  scope-guard that nothing else was smuggled into v16)
- apply-migrations tests include v0.17.0 in the registered list

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

* feat(v0.17.0 step 2/9): pages.source_id + composite UNIQUE (Lane B)

Migration v17 adds pages.source_id with DEFAULT 'default' and swaps the
global UNIQUE(slug) for composite UNIQUE(source_id, slug). Ships atomically
with the engine's ON CONFLICT rewrite so the constraint swap and the code
that writes under it land in the same commit — no window where the engine
sees one shape and the schema has another.

Minimum-surface engine change: only putPage's ON CONFLICT target needs
re-targeting. Other slug-based queries work unchanged because single-
source brains (the only brain shape pre-Step-5) have exactly one source
'default', so slug remains effectively unique within it. Step 5+ will
surface an explicit sourceId param on putPage for cross-source sync.

- migration v17 (pages_source_id_composite_unique) in src/core/migrate.ts
- pages.source_id + composite UNIQUE added to schema.sql + pglite-schema.ts
  for fresh installs
- ON CONFLICT (slug) → ON CONFLICT (source_id, slug) in both pglite-engine
  and postgres-engine putPage
- DEFAULT 'default' closes the Codex-flagged race where an INSERT between
  ADD COLUMN and SET NOT NULL could leave source_id NULL
- 5 new v17 structural tests (29 pass / 0 fail in migrate.test.ts)
- Full suite: 1979 pass / 3 fail (same as baseline — no regressions)

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

* feat(v0.17.0 step 6/9): sources CLI + source-resolver (Lane C)

Adds the CLI surface for multi-source management. Users can now register,
list, rename, federate/unfederate, and attach-to-directory a source. The
source-resolver is the shared 6-priority helper that Steps 4/5 will use
when they start surfacing an explicit --source flag on sync/extract/query.

Commands:
  gbrain sources add <id> --path <p> [--name <n>] [--federated|--no-federated]
  gbrain sources list [--json]
  gbrain sources remove <id> [--yes] [--dry-run] [--keep-storage]
  gbrain sources rename <id> <new-name>
  gbrain sources default <id>
  gbrain sources attach <id>   — writes .gbrain-source in CWD
  gbrain sources detach
  gbrain sources federate <id> / unfederate <id>

Resolution priority (source-resolver.ts) — highest first:
  1. --source flag  2. GBRAIN_SOURCE env  3. .gbrain-source dotfile walk-up
  4. longest-prefix match on registered local_path (Codex #2 fix)
  5. sources.default config  6. fallback 'default'

- add: validates id format (kebab-case alnum, 1-32), rejects overlapping
  paths (eng review §4 finding 4.1), supports federated default opt-in
- remove: guards against --yes omission + refuses to remove 'default',
  supports --dry-run, reports cascade page count
- attach/detach: matches kubectl/terraform context-pinning semantics
- Throws on overlap rather than process.exit() so the CLI error wrapper
  reports it consistently (also makes unit testing clean)

28 new tests across sources.test.ts (dispatcher + validation + overlap
guard) and source-resolver.test.ts (full 6-priority coverage including
longest-prefix). Full suite: 2012 pass / 3 fail (pre-existing PGLite
infra timeouts).

NOT in scope for Step 6 (deferred):
  - import-from-github (SSRF + clone integration)
  - prune (retention/TTL, lands v0.18)
  - MCP tool-defs regen for source-scoping on read ops (Step 5)

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

* docs(v0.17.0 step 8/9): getting-started guide + migration skill + citation rule

Step 8 (Lane F) documents what Steps 1+2+6 have shipped and sets up
the agent-facing rules for multi-source.

New files:
- skills/migrations/v0.17.0.md — migration skill read by host agents
  after `gbrain apply-migrations`. Covers the v16+v17 chain, what's
  in v0.17.0 vs what lands later (v0.17.1 ACL, v0.18 sessions), and
  the new sources CLI surface. Cites docs/guides/multi-source-brains.md
  as the recipe.
- docs/guides/multi-source-brains.md — getting-started for end users.
  Three canonical scenarios (unified wiki+gstack / purpose-separated
  yc-media+garrys-list / mixed), full resolution priority, federation
  flag semantics, command reference, and citation format.

skills/brain-ops/SKILL.md — new "Cross-source citation format"
section mandating `[source-id:slug]` when the brain has multiple
sources. Matches the contract the /plan-devex-review DX review
pinned down (DX Finding 5: surface source_id in every page payload
+ citation contract). Key must be sources.id (immutable), never
sources.name.

No behavior change — this is pure documentation for what already
exists in the binary. 144 skills conformance tests still pass.

NOT in this commit (deferred to later steps):
- docs/guides/repo-architecture.md rewrite (lands with the full
  v0.17.0 PR description + release notes)
- skills/_brain-filing-rules.md "which source to file into"
  guidance (lands with Step 5 when sync surfaces --source)

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

* feat(v0.17.0 step 5/9): sync --source <id> routes through sources table (Lane D)

Adds the --source flag to `gbrain sync`. When set, sync reads local_path
+ last_commit from the matching sources(id) row instead of the global
sync.repo_path / sync.last_commit config keys, and writes last_commit +
last_sync_at back to the same row. Backward compat: --source omitted =
pre-v0.17 behavior exactly, global config path unchanged.

- SyncOpts.sourceId threaded through performSync + performFullSync
- readSyncAnchor/writeSyncAnchor helpers centralize the sources-vs-config
  branch so every read/write goes through one decision point. Makes
  Step 5's later per-source sync-failures tracking a one-file change.
- --source resolved via src/core/source-resolver.ts (Step 6), so any
  command that shell-exposes resolveSourceId gets env var + dotfile
  walk-up + longest-prefix for free.
- Error message for missing source local_path is actionable:
    Source "gstack" has no local_path. Run: gbrain sources add gstack --path <path>
- last_sync_at auto-updates on every last_commit advance so `gbrain
  sources list` shows real recency.

No regression: 2012 pass / 3 fail (same as baseline).

NOT in this commit (deferred per plan):
- Per-source failure tracking (~/.gbrain/sources/<id>/sync-failures.jsonl)
- runImport source-awareness (import.ts path — Step 5 continuation)
- Partial-success semantics when walking N sources — single-source flow
  today, multi-walk lands when the top-level `gbrain sync` without
  --source starts iterating all sources.

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

* feat(v0.17.0 step 4/9): qualified [[source:slug]] + links.resolution_type (Lane B)

Adds source-pinned wikilink syntax and records the resolution kind on
each edge so `gbrain extract --refresh-unqualified` (future) can
re-resolve bare references when the source topology changes.

Wikilink syntax extension:
  [[concepts/ai]]             — unqualified; resolves via local-first fallback
  [[wiki:concepts/ai]]        — qualified; target pinned to sources.id='wiki'
  [[gstack:projects/foo|Display]]  — qualified + display name

The qualified regex runs first and masks matched spans so the
unqualified pass can't double-emit. Source id format enforced to match
the sources CLI validation: [a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?

Schema:
- migration v18 adds links.resolution_type TEXT with CHECK constraint
  ('qualified'|'unqualified' or NULL for legacy/manual/frontmatter edges)
- schema.sql + pglite-schema.ts updated for fresh installs

EntityRef type:
- sourceId is OPTIONAL (only set on qualified wikilinks). Markdown
  [Name](path) and unqualified wikilinks omit it so strict toEqual
  tests pre-v0.17 keep working (69 existing tests still pass).

Tests:
- 5 new qualified-wikilink extraction tests + 1 migration v18 structural
  assertion. 75 tests in test/link-extraction.test.ts (up from 69).
- Full suite: 2018 pass / 3 fail (pre-existing PGLite infra timeouts).

NOT in this commit (deferred to Step 3 / Step 5 continuation):
- Writing resolution_type to the DB (addLink / addLinksBatch don't
  carry the field yet — that's the plumb-through that lands with
  Step 3 when search/dedup also needs source-aware result keys).
- `gbrain extract --refresh-unqualified` re-resolver.

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

* feat(v0.17.0 step 3/9): source-aware search dedup composite keys (Lane B)

Search dedup now keys on (source_id, slug) instead of slug alone. Pre-
v0.17 would collapse two same-slug pages in different sources into
one, destroying cross-source recall. Codex outside-voice review flagged
this as regression-critical — this commit ships the fix plus tests
that lock the invariant in.

Dedup pipeline (src/core/search/dedup.ts):
- pageKey(r) helper — one canonical composite-key derivation. Falls
  back to source_id='default' for pre-v0.17 rows so single-source
  brains behave identically to before.
- Layer 1 (dedupBySource): group-by composite key.
- Layer 4 (capPerPage): count-by composite key.
- guaranteeCompiledTruth: swap scoped to matching (source_id, slug),
  so wiki:topics/ai can't accidentally pull gstack:topics/ai's
  compiled_truth chunk.

SearchResult type gains optional source_id — populated by SQL JOINs
in both engines, falls through as 'default' for legacy callers.

Engine SQL:
- pglite-engine.ts + postgres-engine.ts: search SELECTs add p.source_id
- rowToSearchResult (utils.ts): maps row.source_id → result.source_id
  when present. Shape stays backward compatible (field optional).

Tests — 4 new in test/dedup.test.ts:
- same-slug-different-source does NOT collapse (the critical regression
  guard Codex called out)
- same-slug-same-source DOES still collapse (no over-correction)
- missing source_id falls back to 'default' for pre-v0.17 compat
- compiled_truth guarantee scopes to composite key (Codex second pass
  caught this specific path would leak otherwise)

Full suite: 2022 pass / 3 fail (3 pre-existing PGLite infra timeouts).

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

* feat(v0.17.0 step 7/9): file_migration_ledger + phase-B storage backfill (Lane E)

Adds files.source_id + files.page_id + the file_migration_ledger
state machine that drives storage object rewrites. Each per-file
transition is its own transaction so crash-point recovery is a
ledger read, not a filesystem inspection. Codex second-pass review
flagged that "skip if already has source prefix" was an unsafe
heuristic — the ledger replaces it with explicit state tracking.

Schema:
- migration v19 (files_source_id_page_id_ledger): handler-only
  (PGLite has no files table; Postgres-only gate). ADDs
  source_id + page_id to files, backfills page_id from page_slug
  scoped to source_id='default', creates file_migration_ledger
  with PK on file_id (Codex: not storage_path_old — two sources
  can share an old path during migration).
- schema.sql updated for fresh Postgres installs; file_migration_ledger
  gets RLS alongside other tables.

Runtime:
- src/commands/migrations/v0_17_0-storage-backfill.ts: drives the
  ledger state machine pending → copy_done → db_updated → complete.
  Idempotent per row: re-running resumes from whichever state
  crashed. Old objects preserved (no delete) so operators can
  verify the soak window before a future cleanup release.
- phase B in v0_17_0.ts orchestrator: wires the storage backend
  (Supabase/S3/local) through createStorage, runs runStorageBackfill,
  reports per-state counts + first-three error details.

Tests — 13 new in test/storage-backfill.test.ts:
- pending → copy_done → db_updated → complete happy path
- 3 crash-point recovery tests (resume from copy_done, resume from
  db_updated, failed rows don't auto-retry)
- already-complete rows are skipped with zero side effects
- idempotent re-upload (exists-check skips redundant upload)
- dry-run mode (no storage, reports counts without mutating)

Plus 5 new migrate.test.ts assertions for v19 structure (handler-
only, PGLite gate, source_id + page_id + ledger DDL, default-source
backfill scope, state machine values).

Full suite: 2035 pass / 3 fail (3 pre-existing PGLite infra
timeouts).

NOT in this commit (explicitly deferred):
- DROP old page_slug column — kept for backward compat until
  operators have time to verify page_id everywhere.
- DROP old UNIQUE(storage_path) in favor of UNIQUE(source_id,
  storage_path) — same reason, deferred to later cleanup.
- Actual cleanup phase that deletes old objects post-soak.

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

* test(v0.17.0 step 9/9): full multi-source PGLite integration suite (Lane G)

End-to-end exercise of every v0.17.0 surface against real PGLite
(in-memory, fast — no DATABASE_URL needed). The migration chain
v2→v19 runs start-to-finish and the test asserts each Step's
invariants hold together.

16 new integration tests across 7 describes:

1. Migration-installed state:
   - sources('default') exists with federated=true config
   - pages.source_id column has DEFAULT 'default'
   - composite UNIQUE (source_id, slug) is installed

2. Default-source write path:
   - putPage without explicit source → source_id='default' via schema
     default clause (no engine API change needed for single-source brains)

3. Composite UNIQUE regression guards (Codex-flagged):
   - Same slug in two different sources coexists
   - Third insert with same (source_id, slug) hits the UNIQUE constraint

4. sources CLI round-trip:
   - federate / unfederate flips config.federated
   - rename changes display, id stays immutable

5. Source resolution priority (integration):
   - Explicit flag > env var > fallback to default
   - Unregistered explicit source errors with actionable message

6. Cascade semantics:
   - sources remove cascades to pages; default source untouched

7. links.resolution_type (Step 4):
   - Qualified/unqualified values accepted
   - CHECK constraint rejects invalid values

All 16 tests pass. Full suite: 2042 pass / 4 fail (4 pre-existing
PGLite beforeEach timeouts in test/wait-for-completion,
test/extract-fs, test/e2e/search-quality, test/e2e/graph-quality
— count fluctuated 3-5 on baseline from variance alone).

Total new tests across Steps 1-9: ~85 unit + integration tests
(sources, source-resolver, migrate v16/v17/v18/v19 structural,
link-extraction qualified wikilinks, dedup regression-critical,
storage-backfill state machine + crash recovery, full
multi-source PGLite integration).

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

* chore: bump to v0.18.0 + CHANGELOG entry (multi-source brains)

One-viewport release summary + itemized changes covering all 9 steps
of the multi-source primitive. Notes the v0.17 → v0.18 version bump
rationale (master shipped gbrain dream as v0.17 while this branch was
in flight).

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

* fix(ci): v0_18_0 orchestrator TS narrow + mechanical test ON CONFLICT

Two CI failures on PR #337:

1. tsc TS2367 at src/commands/migrations/v0_18_0.ts:190 —
   after the early-return on `a.status === 'failed'` (line 179),
   TypeScript narrows `a.status` to `'skipped' | 'complete'`, so the
   subsequent `a.status === 'failed' ? 'failed' :` branch was dead
   code and refused to compile. Dropped the redundant check.

2. E2E `file_list LIMIT enforcement` at test/e2e/mechanical.test.ts:636 —
   the test pre-seeded a pages row with `ON CONFLICT (slug) DO NOTHING`
   but v21 swapped the global UNIQUE for `UNIQUE (source_id, slug)`, so
   Postgres rejects with "no unique or exclusion constraint matching".
   Updated the conflict target to the composite key.

Tier-1 E2E had only this one failing test; everything else passed.

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

* test(e2e): v0.18.0 multi-source against real Postgres (v20-v23 schema + cascade + sync)

Closes the three biggest confidence gaps the author flagged in the
self-audit of PR #337:

1. No real Postgres E2E — PGLite has no files table, so v23's
   files.source_id + files.page_id rewrite + file_migration_ledger
   seed was NEVER executed against the real DB. This file covers it.

2. `gbrain sync --source <id>` had zero direct tests. Now has two:
   one that asserts performSync({sourceId}) reads local_path from the
   sources row (not the global config), one that asserts no-sourceId
   falls back to the global sync.repo_path.

3. Cascade delete coverage — previously verified only pages count
   after source removal. Now verifies pages + content_chunks +
   timeline_entries + links + files ALL cascade-delete when a source
   is removed.

6 describes, 16 tests total:

- Schema shape (fresh install): 6 tests confirming sources('default'),
  pages.source_id NOT NULL with DEFAULT, composite UNIQUE pages
  (source_id, slug) replaces global UNIQUE(slug), links.resolution_type
  column + CHECK, files.source_id + page_id columns, file_migration_ledger
  table + status CHECK.

- Composite UNIQUE semantics: 3 tests confirming same-slug in two
  sources coexists (Codex-critical regression guard), duplicate
  (source_id, slug) hits the UNIQUE, putPage targets default source
  by schema DEFAULT.

- Cascade delete: 1 test building a fully populated source (2 pages,
  chunks, timeline, links, files) then removing it + asserting every
  dependent row is gone.

- Sync routing: 2 tests confirming performSync({sourceId}) reads
  per-source local_path vs global config.

- Sources surface: 3 tests for federate/unfederate flipping + rename
  preserving id.

- Storage backfill: 1 end-to-end test seeding ledger + running
  runStorageBackfill against a stub StorageBackend, asserting
  pending → complete transition and files.storage_path rewrite.

Gated by DATABASE_URL per CLAUDE.md E2E lifecycle. Each describe's
beforeAll defensively DELETEs non-default sources + file_migration_ledger
rows so reruns are hermetic (sources isn't in helpers.ALL_TABLES).

Verified: 16/16 pass on first run AND second run (residual-state fix
holds). Full E2E suite still green.

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

* fix(ci): TS2352 in multi-source E2E — cast postgres.js RowList via unknown

tsc rejects the direct
  `(rows as { column_name: string }[]).map(...)`
cast because postgres.js RowList rows have an iterable-row shape that
doesn't overlap with the plain-object target. Standard fix: cast via
`unknown` first so the narrowing is explicit.

Verified: `bunx tsc --noEmit` clean (ignoring the pre-existing baseUrl
deprecation warning).

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

* fix(v0.18.0): addLinksBatch + addTimelineEntriesBatch source-aware JOINs

Batch APIs JOINed on pages.slug globally, so two pages sharing the same
slug across sources would silently fan out — addLinksBatch(['a->b']) in
a brain with 'a' in both 'default' and 'alt' wrote 2 edges instead of 1.
Same bug on addTimelineEntriesBatch.

Fix:
- LinkBatchInput + TimelineBatchInput gain optional source_id fields
  (from_source_id, to_source_id, origin_source_id for links; source_id
  for timeline). All default to 'default' so existing callers are
  backward-compatible on single-source brains.
- pglite-engine + postgres-engine batch JOINs now composite-key on
  (slug, source_id). Postgres adds 3 more unnest arrays for links + 1
  for timeline — still one bind per column, no 65535-param cap risk.
- LEFT JOIN for origin pages also source-qualified so frontmatter-
  provenance edges don't cross-pollinate across sources.

Regression coverage:
- test/pglite-engine.test.ts: 5 new tests covering default-path isolation,
  explicit alt-source writes, and cross-source edges.
- test/e2e/multi-source.test.ts: 4 new tests against real Postgres so
  postgres-js's unnest() bind path is exercised (structurally different
  from PGLite's).

Gap #4 from the PR self-audit — latent bug, not previously reachable
because every existing caller wrote to the default source only.

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-22 16:24:23 -07:00
514 changed files with 34329 additions and 10329 deletions
@@ -0,0 +1,39 @@
<!--
Tier 5.5 Externally-Authored Query Submission template
See eval/CONTRIBUTING.md for the full workflow.
-->
## Summary
Submitting **N** Tier 5.5 queries for BrainBench.
- Author handle: `@your-handle`
- File location: `eval/external-authors/your-handle/queries.json`
- Queries authored fresh (not copy-pasted from a model output)
- Slugs verified against `eval/data/world-v1/` (via `bun run eval:world:view`)
## Checklist
- [ ] `bun run eval:query:validate eval/external-authors/your-handle/queries.json` passes
- [ ] At least 20 queries
- [ ] Each query has either `gold.relevant` (with real slugs) or `gold.expected_abstention: true`
- [ ] Temporal queries have `as_of_date` set (`corpus-end` | `per-source` | ISO-8601)
- [ ] Phrasing is varied (not all the same template)
- [ ] `author` field matches my handle
## Phrasing variety (optional self-audit)
Tick the styles represented in your batch:
- [ ] Full sentence questions
- [ ] Fragment-style ("crypto founder Goldman Sachs background")
- [ ] Comparison ("X vs Y")
- [ ] Follow-up ("And who else...")
- [ ] Imperative ("Pull up Alice Davis")
- [ ] Trait-based ("the demanding engineering leader")
- [ ] Abstention bait (answer is "not in corpus")
## Notes to reviewer
Anything worth flagging — ambiguous cases, corpus gaps you found, specific
phrasings you were uncertain about.
+4
View File
@@ -13,3 +13,7 @@ supabase/.temp/
.claude/skills/
.idea
eval/reports/
eval/data/world-v1/world.html
# BrainBench amara-life-v1 Opus cache (regenerate via eval:generate-amara-life)
eval/data/amara-life-v1/_cache/
+1332 -4
View File
File diff suppressed because it is too large Load Diff
+226 -19
View File
@@ -25,42 +25,57 @@ strict behavior when unset.
- `src/core/operations.ts` — Contract-first operation definitions (the foundation). Also exports upload validators: `validateUploadPath`, `validatePageSlug`, `validateFilename`. `OperationContext.remote` flags untrusted callers.
- `src/core/engine.ts` — Pluggable engine interface (BrainEngine). `clampSearchLimit(limit, default, cap)` takes an explicit cap so per-operation caps can be tighter than `MAX_SEARCH_LIMIT`. Exports `LinkBatchInput` / `TimelineBatchInput` for the v0.12.1 bulk-insert API (`addLinksBatch` / `addTimelineEntriesBatch`). As of v0.13.1, `BrainEngine` has a `readonly kind: 'postgres' | 'pglite'` discriminator so migrations (`src/core/migrate.ts`) and other consumers can branch on engine without `instanceof` + dynamic imports.
- `src/core/engine-factory.ts` — Engine factory with dynamic imports (`'pglite'` | `'postgres'`)
- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all 40 BrainEngine methods. `addLinksBatch` / `addTimelineEntriesBatch` use multi-row `unnest()` with manual `$N` placeholders. As of v0.13.1, `connect()` wraps `PGlite.create()` in a try/catch that emits an actionable error naming the macOS 26.3 WASM bug (#223) and pointing at `gbrain doctor`; the lock is released on failure so the next process can retry cleanly.
- `src/core/pglite-engine.ts` — PGLite (embedded Postgres 17.5 via WASM) implementation, all 40 BrainEngine methods. `addLinksBatch` / `addTimelineEntriesBatch` use multi-row `unnest()` with manual `$N` placeholders. As of v0.13.1, `connect()` wraps `PGlite.create()` in a try/catch that emits an actionable error naming the macOS 26.3 WASM bug (#223) and pointing at `gbrain doctor`; the lock is released on failure so the next process can retry cleanly. v0.22.0: `searchKeyword` and `searchKeywordChunks` multiply `ts_rank` by the source-factor CASE expression at the chunk-grain level; `searchVector` becomes a two-stage CTE — inner CTE keeps `ORDER BY cc.embedding <=> vec` so HNSW stays usable, outer SELECT re-ranks by `raw_score * source_factor`. Inner LIMIT scales with offset to preserve pagination contract.
- `src/core/pglite-schema.ts` — PGLite-specific DDL (pgvector, pg_trgm, triggers)
- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query.
- `src/core/postgres-engine.ts` — Postgres + pgvector implementation (Supabase / self-hosted). `addLinksBatch` / `addTimelineEntriesBatch` use `INSERT ... SELECT FROM unnest($1::text[], ...) JOIN pages ON CONFLICT DO NOTHING RETURNING 1` — 4-5 array params regardless of batch size, sidesteps the 65535-parameter cap. As of v0.12.3, `searchKeyword` / `searchVector` scope `statement_timeout` via `sql.begin` + `SET LOCAL` so the GUC dies with the transaction instead of leaking across the pooled postgres.js connection (contributed by @garagon). `getEmbeddingsByChunkIds` uses `tryParseEmbedding` so one corrupt row skips+warns instead of killing the query. v0.22.0: `searchKeyword`, `searchKeywordChunks`, and `searchVector` apply source-aware ranking by inlining the source-factor CASE and `NOT (col LIKE …)` hard-exclude clause from `src/core/search/sql-ranking.ts`. `searchVector` switches to a two-stage CTE (HNSW-safe inner ORDER BY, source-boost re-rank in the outer SELECT) and carries `p.source_id` through inner→outer for v0.18 multi-source callers. v0.22.1 (#406): `_savedConfig` retains the connect config; `reconnect()` tears down + recreates the pool from saved config (called by supervisor watchdog after 3 consecutive health-check failures). `executeRaw` is a single-statement passthrough — no per-call retry (D3 dropped that as unsound for non-idempotent statements; recovery is supervisor-driven). v0.22.1 (#363, contributed by @orendi84): `connect()` applies `resolveSessionTimeouts()` from `db.ts` as connection-time startup parameters (`statement_timeout`, `idle_in_transaction_session_timeout`) so orphan pgbouncer backends can't hold locks for hours. v0.22.1 (#409, contributed by @atrevino47): `countStaleChunks()` + `listStaleChunks()` server-side-filter on `embedding IS NULL` for `embed --stale`, eliminating ~76 MB/call client-side pull on a fully-embedded brain; `upsertChunks()` resets both `embedding` AND `embedded_at` to NULL when chunk_text changes without a new embedding (consistency).
- `src/core/utils.ts` — Shared SQL utilities extracted from postgres-engine.ts. Exports `parseEmbedding(value)` (throws on unknown input, used by migration + ingest paths where data integrity matters) and as of v0.12.3 `tryParseEmbedding(value)` (returns `null` + warns once per process, used by search/rescore paths where availability matters more than strictness).
- `src/core/db.ts` — Connection management, schema initialization
- `src/core/db.ts` — Connection management, schema initialization. v0.22.1 (#363, contributed by @orendi84): `resolveSessionTimeouts()` returns `statement_timeout` + `idle_in_transaction_session_timeout` (defaults: 5min each, env-overridable via `GBRAIN_STATEMENT_TIMEOUT` / `GBRAIN_IDLE_TX_TIMEOUT` / `GBRAIN_CLIENT_CHECK_INTERVAL`). Both `connect()` (module singleton) and `PostgresEngine.connect()` (worker pool) consume the result via postgres.js's `connection` option, sending GUCs as startup parameters that survive PgBouncer transaction mode (unlike the prior `setSessionDefaults` post-pool SET, kept as a back-compat no-op shim).
- `src/commands/migrate-engine.ts` — Bidirectional engine migration (`gbrain migrate --to supabase/pglite`)
- `src/core/import-file.ts` — importFromFile + importFromContent (chunk + embed + tags)
- `src/core/sync.ts` — Pure sync functions (manifest parsing, filtering, slug conversion)
- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local)
- `src/core/supabase-admin.ts` — Supabase admin API (project discovery, pgvector check)
- `src/core/file-resolver.ts` — File resolution with fallback chain (local -> .redirect.yaml -> .redirect -> .supabase)
- `src/core/chunkers/` — 3-tier chunking (recursive, semantic, LLM-guided)
- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup
- `src/core/chunkers/` — 3-tier chunking (recursive, semantic, LLM-guided). v0.19.0 adds `code.ts` — tree-sitter-based semantic chunker for 29 languages with embedded-asset WASMs (`src/assets/wasm/`), `@dqbd/tiktoken` cl100k_base tokenizer, small-sibling merging. `CHUNKER_VERSION` constant folded into `importCodeFile`'s `content_hash` so chunker shape changes force clean re-chunks across releases.
- `src/core/errors.ts` (v0.19.0) — `StructuredAgentError` + `buildError` + `serializeError`. Every new v0.19.0 agent-facing surface (code-def, code-refs, usage errors) uses this envelope; matches v0.17.0 `CycleReport.PhaseResult.error` shape.
- `src/assets/wasm/` (v0.19.0) — 36 tree-sitter grammar WASMs + tree-sitter runtime. Committed to the repo so `bun --compile` embeds them deterministically via `import path from ... with { type: 'file' }`. The CI guard `scripts/check-wasm-embedded.sh` fails the build if the compiled binary ever silently falls through to recursive chunks.
- `src/commands/code-def.ts` + `src/commands/code-refs.ts` (v0.19.0) — symbol definition + references lookup. Query `content_chunks.symbol_name` or chunk_text ILIKE with `page_kind='code'` filter. Auto-JSON when stdout is not a TTY (gh-CLI convention). Bypass the standard `searchKeyword` `DISTINCT ON (slug)` collapse so multiple call-sites from the same file surface.
- `src/core/search/` — Hybrid search: vector + keyword + RRF + multi-query expansion + dedup. As of v0.22.0, `searchKeyword` / `searchKeywordChunks` / `searchVector` apply source-aware ranking at the SQL layer (curated content like `originals/`, `concepts/`, `writing/` outranks bulk content like `wintermute/chat/`, `daily/`, `media/x/`). `searchVector` uses a two-stage CTE so source-boost re-ranking doesn't kill the HNSW index. Hard-exclude prefixes (`test/`, `archive/`, `attachments/`, `.raw/` by default) filter at retrieval, not post-rank. Both gates honor `detail !== 'high'` so temporal queries surface chat pages normally.
- `src/core/search/intent.ts` — Query intent classifier (entity/temporal/event/general → auto-selects detail level)
- `src/core/search/eval.ts` — Retrieval eval harness: P@k, R@k, MRR, nDCG@k metrics + runEval() orchestrator
- `src/core/search/source-boost.ts` (v0.22.0) — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, wintermute/chat/ 0.5) and `DEFAULT_HARD_EXCLUDES` (test/, archive/, attachments/, .raw/). `parseSourceBoostEnv` / `parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST` / `GBRAIN_SEARCH_EXCLUDE` env vars. `resolveBoostMap` and `resolveHardExcludes` merge defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`.
- `src/core/search/sql-ranking.ts` (v0.22.0) — Pure SQL string builders. `buildSourceFactorCase(slugColumn, boostMap, detail)` emits a CASE expression with longest-prefix-match wins (returns literal `'1.0'` when `detail === 'high'` for temporal-bypass parity with COMPILED_TRUTH_BOOST). `buildHardExcludeClause(slugColumn, prefixes)` emits `NOT (col LIKE 'p1%' OR col LIKE 'p2%')` — OR-chain wrapped in NOT, NOT `NOT LIKE ALL/ANY` (those quantifiers don't express set-exclusion). LIKE meta-character escape covers all three of `%`, `_`, AND `\` (backslash matters because it's Postgres LIKE's default escape char). Single-quote doubling on SQL string literals so injection-style inputs are inert text.
- `src/commands/eval.ts``gbrain eval` command: single-run table + A/B config comparison
- `src/core/embedding.ts` — OpenAI text-embedding-3-large, batch, retry, backoff
- `src/core/check-resolvable.ts` — Resolver validation: reachability, MECE overlap, DRY checks, structured fix objects. v0.14.1: `CROSS_CUTTING_PATTERNS.conventions` is an array (notability gate accepts both `conventions/quality.md` and `_brain-filing-rules.md`). New `extractDelegationTargets()` parses `> **Convention:**`, `> **Filing rule:**`, and inline backtick references. DRY suppression is proximity-based via `DRY_PROXIMITY_LINES = 40`.
- `src/core/repo-root.ts` — Shared `findRepoRoot(startDir?)` (v0.16.4): walks up from `startDir` (default `process.cwd()`) looking for `skills/RESOLVER.md`. Zero-dependency module imported by both `doctor.ts` and `check-resolvable.ts`. Parameterized `startDir` makes tests hermetic.
- `src/commands/check-resolvable.ts` — Standalone CLI wrapper (v0.16.4) over `checkResolvable()`. Exports `parseFlags`, `resolveSkillsDir`, `DEFERRED`, `runCheckResolvable`. Exit rule: **1 on any issue (warnings OR errors)**, stricter than doctor's `ok` flag — honors README:259. Stable JSON envelope `{ok, skillsDir, report, autoFix, deferred, error, message}` — same shape on success and error paths. `--fix` path runs `autoFixDryViolations` BEFORE `checkResolvable` (same ordering as doctor). `deferred[]` array surfaces pending Checks 5 (trigger routing eval) and 6 (brain filing) with issue URLs. `scripts/skillify-check.ts` subprocess-calls `gbrain check-resolvable --json` (cached per process) and fails loud on binary-missing — no silent false-pass.
- `src/commands/check-resolvable.ts` — Standalone CLI wrapper (v0.16.4) over `checkResolvable()`. Exports `parseFlags`, `resolveSkillsDir`, `DEFERRED`, `runCheckResolvable`. Exit rule: **1 on any issue (warnings OR errors)**, stricter than doctor's `ok` flag — honors README:259. Stable JSON envelope `{ok, skillsDir, report, autoFix, deferred, error, message}` — same shape on success and error paths. `--fix` path runs `autoFixDryViolations` BEFORE `checkResolvable` (same ordering as doctor). `scripts/skillify-check.ts` subprocess-calls `gbrain check-resolvable --json` (cached per process) and fails loud on binary-missing — no silent false-pass. **v0.19:** AGENTS.md workspaces now resolve natively (see `src/core/resolver-filenames.ts`) — gbrain inspects the 107-skill OpenClaw deployment whether the routing file is `RESOLVER.md` or `AGENTS.md`. `DEFERRED[]` is empty — Checks 5 + 6 shipped as real code, not issue URLs.
- `src/core/resolver-filenames.ts` (v0.19) — central list of accepted routing filenames (`RESOLVER.md`, `AGENTS.md`). Shared by `findRepoRoot`, `check-resolvable`, and skillpack install so every code path walks the same fallback chain.
- `src/commands/skillify.ts` + `src/core/skillify/{generator,templates}.ts` (v0.19) — `gbrain skillify scaffold <name>` creates all stubs for a new skill in one command: SKILL.md, script, tests, routing-eval.jsonl, resolver entry, filing-rules pointer. `gbrain skillify check <script>` runs the 10-step checklist (LLM evals, routing evals, check-resolvable gate, filing audit) against a candidate skill before it lands.
- `src/commands/skillify-check.ts` (v0.19) — `gbrain skillpack-check` agent-readable health report. Exit 0/1/2 for CI pipeline gating; JSON for debugging. Wraps `check-resolvable --json`, `doctor --json`, and migration ledger into one payload so agents can decide whether a human action is required.
- `src/commands/skillpack.ts` + `src/core/skillpack/{bundle,installer}.ts` (v0.19) — `gbrain skillpack install` drops gbrain's curated 25-skill bundle into a host workspace, managed-block style. Never clobbers local edits; tracks a skill manifest so subsequent `install --update` diffs cleanly. Bundle builder (`skillpack/bundle.ts`) packages the set from `skills/` into a versioned payload.
- `src/core/skill-manifest.ts` (v0.19) — parser for `skill-manifest.json` records. Used by skillpack installer to detect drift between the shipped bundle and the user's local edits, so updates merge instead of overwriting.
- `src/commands/routing-eval.ts` + `src/core/routing-eval.ts` (v0.19) — `gbrain routing-eval` catches user phrasings that route to the wrong skill. Reads `skills/<name>/routing-eval.jsonl` fixtures (`{intent, expected_skill, ambiguous_with?}`). Structural layer runs in `check-resolvable` by default (zero API cost); `--llm` opts into a Haiku tie-break layer for CI. False positives surface before users hit them.
- `src/core/filing-audit.ts` + `skills/_brain-filing-rules.json` (v0.19) — Check 6 of `check-resolvable`. Parses new `writes_pages:` / `writes_to:` frontmatter on skills and audits their filing claims against the filing-rules JSON. Warning-only in v0.19, upgrades to error in v0.20.
- `src/core/dry-fix.ts``gbrain doctor --fix` engine. `autoFixDryViolations(fixes, {dryRun})` rewrites inlined rules to `> **Convention:** see [path](path).` callouts via three shape-aware expanders (bullet / blockquote / paragraph). Five guards: working-tree-dirty (`getWorkingTreeStatus()` returns 3-state `'clean' | 'dirty' | 'not_a_repo'`), no-git-backup, inside-code-fence, already-delegated (40-line proximity, consistent with detector), ambiguous-multi-match, block-is-callout. `execFileSync` array args (no shell — no injection surface). EOF newline preserved.
- `src/core/backoff.ts` — Adaptive load-aware throttling: CPU/memory checks, exponential backoff, active hours multiplier
- `src/core/fail-improve.ts` — Deterministic-first, LLM-fallback loop with JSONL failure logging and auto-test generation
- `src/core/transcription.ts` — Audio transcription: Groq Whisper (default), OpenAI fallback, ffmpeg segmentation for >25MB
- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling
- `src/core/data-research.ts` — Recipe validation, field extraction (MRR/ARR regex), dedup, tracker parsing, HTML stripping
- `src/commands/extract.ts``gbrain extract links|timeline|all [--source fs|db]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use this for live brains with no local checkout). As of v0.12.1 there is no in-memory dedup pre-load — candidates are buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, and the `created` counter returns real rows inserted (truthful on re-runs).
- `src/commands/embed.ts``gbrain embed [--stale|--all] [--slugs ...]`. v0.22.1 (#409, contributed by @atrevino47): `--stale` path now starts with `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire). On a fully-embedded brain that's a 1-line short-circuit — no further reads. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload). Caller groups by slug, embeds via OpenAI, re-upserts via `upsertChunks`. Replaces the prior page-walk that pulled every chunk's embedding column over the wire and discarded most.
- `src/commands/extract.ts``gbrain extract links|timeline|all [--source fs|db]`: batch link/timeline extraction. fs walks markdown files, db walks pages from the engine (mutation-immune snapshot iteration; use this for live brains with no local checkout). As of v0.12.1 there is no in-memory dedup pre-load — candidates are buffered 100 at a time and flushed via `addLinksBatch` / `addTimelineEntriesBatch`; `ON CONFLICT DO NOTHING` enforces uniqueness at the DB layer, and the `created` counter returns real rows inserted (truthful on re-runs). v0.22.1 (#417): `ExtractOpts.slugs?: string[]` enables incremental extract — when set, `extractForSlugs()` reads ONLY those slugs' files (single combined links+timeline pass) instead of the full directory walk. CLI `gbrain extract` keeps full-walk behavior; the cycle path threads sync's `pagesAffected` through. `walkMarkdownFiles(brainDir)` still runs at line 455 to build `allSlugs` for link resolution — see `TODOS.md` for replacing it with `engine.getAllSlugs()`.
- `src/commands/graph-query.ts``gbrain graph-query <slug> [--type T] [--depth N] [--direction in|out|both]`: typed-edge relationship traversal (renders indented tree)
- `src/core/link-extraction.ts` — shared library for the v0.12.0 graph layer. extractEntityRefs (canonical, replaces backlinks.ts duplicate) matches both `[Name](people/slug)` markdown links and Obsidian `[[people/slug|Name]]` wikilinks as of v0.12.3. extractPageLinks, inferLinkType heuristics (attended/works_at/invested_in/founded/advises/source/mentions), parseTimelineEntries, isAutoLinkEnabled config helper. `DIR_PATTERN` covers `people`, `companies`, `deals`, `topics`, `concepts`, `projects`, `entities`, `tech`, `finance`, `personal`, `openclaw`. Used by extract.ts, operations.ts auto-link post-hook, and backlinks.ts.
- `src/core/minions/` — Minions job queue: BullMQ-inspired, Postgres-native (queue, worker, backoff, types, protected-names, quiet-hours, stagger, handlers/shell).
- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). v0.14.1 #219: `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in.
- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). v0.14.0 abort-path fix: aborted jobs now call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`) instead of returning silently. `shutdownAbort` (instance field) fires on process SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` — shell handler listens to it; non-shell handlers don't.
- `src/core/minions/queue.ts` — MinionQueue class (submit, claim, complete, fail, stall detection, parent-child, depth/child-cap, per-job timeouts, cascade-kill, attachments, idempotency keys, child_done inbox, removeOnComplete/Fail). `add()` takes a 4th `trusted` arg (separate from `opts` to prevent spread leakage); protected names in `PROTECTED_JOB_NAMES` require `{allowProtectedSubmit: true}` and the check runs trim-normalized (whitespace-bypass safe). v0.14.1 #219: `add()` plumbs `max_stalled` through with a `[1, 100]` clamp; omitted values let the schema DEFAULT (5) kick in. v0.19.0: `handleWallClockTimeouts(lockDurationMs)` is Layer 3 kill shot for jobs where `FOR UPDATE SKIP LOCKED` stall detection and the timeout sweep both fail to evict (wedged worker holding a row lock via a pending transaction). v0.19.1: `maxWaiting` coalesce path now uses `pg_advisory_xact_lock` keyed on `(name, queue)` to serialize concurrent submits for the same key, and filters on `queue` in addition to `name` so cross-queue same-name jobs don't suppress each other.
- `src/core/minions/worker.ts` — MinionWorker class (handler registry, lock renewal, graceful shutdown, timeout safety net). v0.14.0 abort-path fix: aborted jobs now call `failJob` with reason (`timeout`/`cancel`/`lock-lost`/`shutdown`) instead of returning silently. `shutdownAbort` (instance field) fires on process SIGTERM/SIGINT and propagates to `ctx.shutdownSignal` — shell handler listens to it; non-shell handlers don't. v0.22.1 (#403): per-job timeout fires `abort.abort(new Error('timeout'))` then a 30-second grace-then-evict safety net force-evicts the job from `inFlight` and marks it dead in DB if the handler ignores the abort signal — frees the slot even when a handler wedges (the 98-waiting-0-active prod incident driver).
- `src/core/minions/supervisor.ts` — MinionSupervisor process manager. Spawns `gbrain jobs work` as a child, restarts on crash with exponential backoff, periodic health check. v0.22.1 (#406): `consecutiveHealthFailures` counter; on 3 consecutive failures emits `health_warn` with `reason: 'db_connection_degraded'` and calls `engine.reconnect()` to swap in a fresh pool, then resets the counter. Worker exit classifier emits `likely_cause` field on `worker_exited` events: `oom_or_external_kill` (SIGKILL), `graceful_shutdown` (SIGTERM), `runtime_error` (code 1), `clean_exit` (code 0), `unknown`.
- `src/core/minions/types.ts``MinionJobInput` + `MinionJobStatus` + handler context types. `MinionJobInput.max_stalled` (new in v0.14.1) is optional; omitted values let the schema DEFAULT (5) kick in, provided values are clamped to `[1, 100]`.
- `src/core/minions/protected-names.ts` — side-effect-free constant module exporting `PROTECTED_JOB_NAMES` + `isProtectedJobName()`. Kept pure so queue core can import without loading handler modules.
- `src/core/minions/handlers/shell.ts``shell` job handler. Spawns `/bin/sh -c cmd` (absolute path, PATH-override-safe) or `argv[0] argv[1..]` (no shell). Env allowlist: `PATH, HOME, USER, LANG, TZ, NODE_ENV` + caller `env:` overrides. UTF-8-safe stdout/stderr tail via `string_decoder.StringDecoder`. Abort (either `ctx.signal` or `ctx.shutdownSignal`) fires SIGTERM → 5s grace → SIGKILL on child. Requires `GBRAIN_ALLOW_SHELL_JOBS=1` on worker (gated by `registerBuiltinHandlers`).
- `src/core/minions/handlers/shell-audit.ts` — per-submission JSONL audit trail at `~/.gbrain/audit/shell-jobs-YYYY-Www.jsonl` (ISO-week rotation; override via `GBRAIN_AUDIT_DIR`). Best-effort: `mkdirSync(recursive)` + `appendFileSync`; failures logged to stderr, submission not blocked. Logs cmd (first 80 chars) or argv (JSON array). Never logs env values.
- `src/core/minions/backpressure-audit.ts` (v0.19.1) — sibling of shell-audit.ts for `maxWaiting` coalesce events. JSONL at `~/.gbrain/audit/backpressure-YYYY-Www.jsonl`. Fires one line per coalesce with `(queue, name, waiting_count, max_waiting, returned_job_id, ts)`. Closes the silent-drop vector the v0.19.0 maxWaiting guard introduced.
- `src/core/minions/handlers/subagent.ts` (v0.15) — LLM-loop handler. Two-phase tool persistence (pending → complete/failed), replay reconciliation for mid-dispatch crashes, dual-signal abort (`ctx.signal` + `ctx.shutdownSignal`), Anthropic prompt caching on system + tool defs. `makeSubagentHandler({engine, client?, ...})` factory; `MessagesClient` is an injectable interface the real SDK implements structurally. Throws `RateLeaseUnavailableError` (renewable) when rate-lease capacity is full.
- `src/core/minions/handlers/subagent-aggregator.ts` (v0.15) — `subagent_aggregator` handler. Claims AFTER all children resolve (queue changes guarantee every terminal child posts a `child_done` inbox message with outcome). Reads inbox via `ctx.readInbox()`, builds deterministic mixed-outcome markdown summary. No LLM call in v0.15.
- `src/core/minions/handlers/subagent-audit.ts` (v0.15) — JSONL audit + heartbeat writer at `~/.gbrain/audit/subagent-jobs-YYYY-Www.jsonl`. Events: `submission` (one line per submit) + `heartbeat` (per turn boundary: `llm_call_started | llm_call_completed | tool_called | tool_result | tool_failed`). Never logs prompts or tool inputs. `readSubagentAuditForJob(jobId, {sinceIso})` is the readback path for `gbrain agent logs`.
@@ -82,11 +97,11 @@ strict behavior when unset.
- `src/commands/migrations/` — TS migration registry (compiled into the binary; no filesystem walk of `skills/migrations/*.md` needed at runtime). `index.ts` lists migrations in semver order. `v0_11_0.ts` = Minions adoption orchestrator (8 phases). `v0_12_0.ts` = Knowledge Graph auto-wire orchestrator (5 phases: schema → config check → backfill links → backfill timeline → verify). `phaseASchema` has a 600s timeout (bumped from 60s in v0.12.1 for duplicate-heavy brains). `v0_12_2.ts` = JSONB double-encode repair orchestrator (4 phases: schema → repair-jsonb → verify → record). `v0_14_0.ts` = shell-jobs + autopilot cooperative (2 phases: schema ALTER minion_jobs.max_stalled SET DEFAULT 3 — superseded by v0.14.3's schema-level DEFAULT 5 + UPDATE backfill; pending-host-work ping for skills/migrations/v0.14.0.md). All orchestrators are idempotent and resumable from `partial` status. As of v0.14.2 (Bug 3), the RUNNER owns all ledger writes — orchestrators return `OrchestratorResult` and `apply-migrations.ts` persists a canonical `{version, status, phases}` shape after return. Orchestrators no longer call `appendCompletedMigration` directly. `statusForVersion` prefers `complete` over `partial` (never regresses). 3 consecutive partials → wedged → `--force-retry <version>` writes a `'retry'` reset marker. v0.14.3 (fix wave) ships schema-only migrations v14 (`pages_updated_at_index`) + v15 (`minion_jobs_max_stalled_default_5` with UPDATE backfill) via the `MIGRATIONS` array in `src/core/migrate.ts` — no orchestrator phases needed.
- `src/commands/repair-jsonb.ts``gbrain repair-jsonb [--dry-run] [--json]`: rewrites `jsonb_typeof='string'` rows in place across 5 affected columns (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter). Fixes v0.12.0 double-encode bug on Postgres; PGLite no-ops. Idempotent.
- `src/commands/orphans.ts``gbrain orphans [--json] [--count] [--include-pseudo]`: surfaces pages with zero inbound wikilinks, grouped by domain. Auto-generated/raw/pseudo pages filtered by default. Also exposed as `find_orphans` MCP operation. Shipped in v0.12.3 (contributed by @knee5).
- `src/commands/doctor.ts``gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit]`: health checks. v0.12.3 added `jsonb_integrity` + `markdown_body_completeness` reliability checks. v0.14.1: `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](path).` callouts (pipes DRY violations into `src/core/dry-fix.ts`); `--fix --dry-run` previews without writing. v0.14.2: `schema_version` check fails loudly when `version=0` (migrations never ran — the #218 `bun install -g` signature) and routes users to `gbrain apply-migrations --yes`; new opt-in `--index-audit` flag (Postgres-only) reports zero-scan indexes from `pg_stat_user_indexes` (informational only, no auto-drop). v0.15.2: every DB check is wrapped in a progress phase; `markdown_body_completeness` runs under a 1s heartbeat timer so 10+ min scans are observable on 50K-page brains. Fix hints point at `gbrain repair-jsonb`, `gbrain sync --force`, and `gbrain apply-migrations`.
- `src/commands/doctor.ts``gbrain doctor [--json] [--fast] [--fix] [--dry-run] [--index-audit]`: health checks. v0.12.3 added `jsonb_integrity` + `markdown_body_completeness` reliability checks. v0.14.1: `--fix` delegates inlined cross-cutting rules to `> **Convention:** see [path](path).` callouts (pipes DRY violations into `src/core/dry-fix.ts`); `--fix --dry-run` previews without writing. v0.14.2: `schema_version` check fails loudly when `version=0` (migrations never ran — the #218 `bun install -g` signature) and routes users to `gbrain apply-migrations --yes`; new opt-in `--index-audit` flag (Postgres-only) reports zero-scan indexes from `pg_stat_user_indexes` (informational only, no auto-drop). v0.15.2: every DB check is wrapped in a progress phase; `markdown_body_completeness` runs under a 1s heartbeat timer so 10+ min scans are observable on 50K-page brains. v0.19.1 added `queue_health` (Postgres-only) with two subchecks: stalled-forever active jobs (started_at > 1h) and waiting-depth-per-name > threshold (default 10, override via `GBRAIN_QUEUE_WAITING_THRESHOLD`). Worker-heartbeat subcheck intentionally deferred to follow-up B7 because it needs a `minion_workers` table to produce ground-truth signal. Fix hints point at `gbrain repair-jsonb`, `gbrain sync --force`, `gbrain apply-migrations`, and `gbrain jobs get/cancel <id>`.
- `src/core/migrate.ts` — schema-migration runner. Owns the `MIGRATIONS` array (source of truth for schema DDL). v0.14.2 extended the `Migration` interface with `sqlFor?: { postgres?, pglite? }` (engine-specific SQL overrides `sql`) and `transaction?: boolean` (set to false for `CREATE INDEX CONCURRENTLY`, which Postgres refuses inside a transaction; ignored on PGLite since it has no concurrent writers). Migration v14 (fix wave) uses a handler branching on `engine.kind` to run CONCURRENTLY on Postgres (with a pre-drop of any invalid remnant via `pg_index.indisvalid`) and plain `CREATE INDEX` on PGLite. v15 bumps `minion_jobs.max_stalled` default 1→5 and backfills existing non-terminal rows.
- `src/core/progress.ts` — Shared bulk-action progress reporter. Writes to stderr. Modes: `auto` (TTY: `\r`-rewriting; non-TTY: plain lines), `human`, `json` (JSONL), `quiet`. Rate-gated by `minIntervalMs` and `minItems`. `startHeartbeat(reporter, note)` helper for single long queries. `child()` composes phase paths. Singleton SIGINT/SIGTERM coordinator emits `abort` events for every live phase. EPIPE defense on both sync throws and stream `'error'` events. Zero dependencies. Introduced in v0.15.2.
- `src/core/cli-options.ts` — Global CLI flag parser. `parseGlobalFlags(argv)` returns `{cliOpts, rest}` with `--quiet` / `--progress-json` / `--progress-interval=<ms>` stripped. `getCliOptions()` / `setCliOptions()` expose a module-level singleton so commands reach the resolved flags without parameter threading. `cliOptsToProgressOptions()` maps to reporter options. `childGlobalFlags()` returns the flag suffix to append to `execSync('gbrain ...')` calls in migration orchestrators. `OperationContext.cliOpts` extends shared-op dispatch for MCP callers.
- `src/core/cycle.ts` — v0.17 brain maintenance cycle primitive. `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes 6 phases in semantically-driven order (lint → backlinks → sync → extract → embed → orphans). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon's inline path, and the Minions `autopilot-cycle` handler (`src/commands/jobs.ts`). One source of truth for what the brain does overnight. Coordination via `gbrain_cycle_locks` DB table (TTL-based; works through PgBouncer transaction pooling, unlike session-scoped `pg_try_advisory_lock`) + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite / engine=null mode. `CycleReport.schema_version: "1"` is the stable agent-consumable shape. `PhaseResult.error: { class, code, message, hint?, docs_url? }` is Stripe-API-tier structured failure info. `yieldBetweenPhases` hook awaited between every phase — Minions handler uses this to renew its job lock and prevent v0.14 stall-death regression. Engine nullable: filesystem phases (lint, backlinks) run without DB; DB phases skip with `status: "skipped", reason: "no_database"`. Lock-skip: read-only phase selections (`--phase orphans`) bypass the cycle lock.
- `src/core/cycle.ts` — v0.17 brain maintenance cycle primitive. `runCycle(engine: BrainEngine | null, opts: CycleOpts): Promise<CycleReport>` composes 6 phases in semantically-driven order (lint → backlinks → sync → extract → embed → orphans). Three callers: `gbrain dream` CLI, `gbrain autopilot` daemon's inline path, and the Minions `autopilot-cycle` handler (`src/commands/jobs.ts`). One source of truth for what the brain does overnight. Coordination via `gbrain_cycle_locks` DB table (TTL-based; works through PgBouncer transaction pooling, unlike session-scoped `pg_try_advisory_lock`) + `~/.gbrain/cycle.lock` file lock with PID-liveness for PGLite / engine=null mode. `CycleReport.schema_version: "1"` is the stable agent-consumable shape. `PhaseResult.error: { class, code, message, hint?, docs_url? }` is Stripe-API-tier structured failure info. `yieldBetweenPhases` hook awaited between every phase — Minions handler uses this to renew its job lock and prevent v0.14 stall-death regression. Engine nullable: filesystem phases (lint, backlinks) run without DB; DB phases skip with `status: "skipped", reason: "no_database"`. Lock-skip: read-only phase selections (`--phase orphans`) bypass the cycle lock. v0.22.1 (#403): `CycleOpts.signal?: AbortSignal` propagates the worker's abort signal; `checkAborted()` fires between every phase and throws if the signal is aborted (cooperative — can't interrupt a phase mid-execution). v0.22.1 (#417): `runPhaseSync` returns `pagesAffected` via `SyncPhaseResult`; `runCycle` captures it and threads to `runPhaseExtract` as the 4th arg, enabling incremental extract on the cycle path. v0.22.1 (Codex F2): `runPhaseSync` takes `willRunExtractPhase: boolean` and sets `noExtract: phases.includes('extract')` so `gbrain dream --phase sync` doesn't silently lose extraction. v0.22.5 (#475): new `resolveSourceForDir(engine, brainDir)` helper queries `SELECT id FROM sources WHERE local_path = $1 LIMIT 1`; `runPhaseSync` threads result as `sourceId` to `performSync()` so sync reads the per-source `sources.last_commit` anchor instead of the drift-prone global `config.sync.last_commit` key. Bare try/catch lets pre-v0.18 brains fall through to the global key. Closes the prod hang where every autopilot cycle ran a 30-min full reimport because the global anchor commit had been GC'd from git history.
- `src/commands/dream.ts` — v0.17 `gbrain dream` CLI. ~80-line thin alias over `runCycle`. brainDir resolution requires explicit `--dir` OR `sync.repo_path` config (no more walk-up-cwd-for-.git footgun). Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`. Exit code 1 on status=failed (partial/warn not fatal — don't page on warnings).
- `scripts/check-progress-to-stdout.sh` — CI guard against regressing to `\r`-on-stdout progress. Wired into `bun run test` via `scripts/check-progress-to-stdout.sh && bun test` in package.json.
- `docs/progress-events.md` — Canonical JSON event schema reference. Stable from v0.15.2, additive only.
@@ -113,7 +128,7 @@ strict behavior when unset.
- `docs/guides/diligence-ingestion.md` — Data room to brain pages pipeline
- `docs/designs/HOMEBREW_FOR_PERSONAL_AI.md` — 10-star vision for integration system
- `docs/mcp/` — Per-client setup guides (Claude Desktop, Code, Cowork, Perplexity)
- `docs/benchmarks/` — Search quality benchmark results (reproducible, fictional data)
- BrainBench (benchmark suite + corpus): lives in the separate [gbrain-evals](https://github.com/garrytan/gbrain-evals) repo. Not installed alongside gbrain.
- `skills/_brain-filing-rules.md` — Cross-cutting brain filing rules (referenced by all brain-writing skills)
- `skills/RESOLVER.md` — Skill routing table (based on the agent-fork AGENTS.md pattern)
- `skills/conventions/` — Cross-cutting rules (quality, brain-first, model-routing, test-before-bulk, cross-modal)
@@ -135,7 +150,7 @@ strict behavior when unset.
- `skills/soul-audit/SKILL.md` — 6-phase interview for SOUL.md, USER.md, ACCESS_POLICY.md, HEARTBEAT.md
- `skills/webhook-transforms/SKILL.md` — External events to brain signals
- `skills/data-research/SKILL.md` — Structured data research: email-to-tracker pipeline with parameterized YAML recipes
- `skills/minion-orchestrator/SKILL.md`Background job orchestration: submit, fan out children with depth/cap/timeouts, collect results via child_done inbox
- `skills/minion-orchestrator/SKILL.md`Unified background-work skill (v0.20.4 consolidation of the former `minion-orchestrator` + `gbrain-jobs` split). Two lanes: shell jobs via `gbrain jobs submit shell --params '{"cmd":"..."}'` (operator/CLI only; MCP throws `permission_denied` for protected names) and LLM subagents via `gbrain agent run` (user-facing entrypoint). Shared Preconditions block, parent-child DAGs with depth/cap/timeouts, `child_done` inbox for fan-in, PGLite `--follow` inline path for dev. Triggers narrowed from bare `"gbrain jobs"` to `"gbrain jobs submit"` + `"submit a gbrain job"` so `stats`/`prune`/`retry` questions fall through to `gbrain --help`.
- `templates/` — SOUL.md, USER.md, ACCESS_POLICY.md, HEARTBEAT.md templates
- `skills/migrations/` — Version migration files with feature_pitch YAML frontmatter
- `src/commands/publish.ts` — Deterministic brain page publisher (code+skill pair, zero LLM calls)
@@ -144,6 +159,21 @@ strict behavior when unset.
- `src/commands/report.ts` — Structured report saver (audit trail for maintenance/enrichment)
- `openclaw.plugin.json` — ClawHub bundle plugin manifest
### BrainBench — in a sibling repo (v0.20+)
BrainBench — the public benchmark for personal-knowledge agent stacks — lives in
[github.com/garrytan/gbrain-evals](https://github.com/garrytan/gbrain-evals). It
depends on gbrain as a consumer; gbrain never pulls in the ~5MB eval corpus or
the pdf-parse dev dep at install time.
gbrain's public API surface (the exports map in `package.json`) is what
gbrain-evals consumes: `gbrain/engine`, `gbrain/types`, `gbrain/operations`,
`gbrain/pglite-engine`, `gbrain/link-extraction`, `gbrain/import-file`,
`gbrain/transcription`, `gbrain/embedding`, `gbrain/config`, `gbrain/markdown`,
`gbrain/backoff`, `gbrain/search/hybrid`, `gbrain/search/expansion`,
`gbrain/extract`. Removing any of these is a breaking change for the
gbrain-evals consumer.
## Commands
Run `gbrain --help` or `gbrain --tools-json` for full command reference.
@@ -205,8 +235,9 @@ parity), `test/cli.test.ts` (CLI structure), `test/config.test.ts` (config redac
`test/lint.test.ts` (LLM artifact detection, code fence stripping, frontmatter validation),
`test/report.test.ts` (report format, directory structure),
`test/skills-conformance.test.ts` (skill frontmatter + required sections validation),
`test/resolver.test.ts` (RESOLVER.md coverage, routing validation),
`test/resolver.test.ts` (RESOLVER.md coverage, routing validation + v0.20.4 round-trip: every quoted RESOLVER.md trigger must match a frontmatter `triggers:` entry in the target skill, and every `name="<word>"` reference in any SKILL.md must resolve to a declared op in `src/core/operations.ts` or a Minions handler in `PROTECTED_JOB_NAMES`),
`test/search.test.ts` (RRF normalization, compiled truth boost, cosine similarity, dedup key),
`test/sql-ranking.test.ts` (v0.22.0 source-boost helpers: 39 cases covering longest-prefix-match in SQL CASE, detail=high temporal-bypass, three-meta-char LIKE escape (%, _, \\), single-quote SQL-literal doubling, env override parsing for GBRAIN_SOURCE_BOOST + GBRAIN_SEARCH_EXCLUDE, resolveBoostMap / resolveHardExcludes merge semantics),
`test/dedup.test.ts` (source-aware dedup, compiled truth guarantee, layer interactions),
`test/intent.test.ts` (query intent classification: entity/temporal/event/general),
`test/eval.test.ts` (retrieval metrics: precisionAtK, recallAtK, mrr, ndcgAtK, parseQrels),
@@ -236,7 +267,15 @@ parity), `test/cli.test.ts` (CLI structure), `test/config.test.ts` (config redac
`test/sync.test.ts` (sync logic + v0.12.3 regression guard asserting top-level `engine.transaction` is not called),
`test/doctor.test.ts` (doctor command + v0.12.3 assertions that `jsonb_integrity` scans the four v0.12.0 write sites and `markdown_body_completeness` is present),
`test/utils.test.ts` (shared SQL utilities + `tryParseEmbedding` null-return and single-warn semantics),
`test/build-llms.test.ts` (llms.txt/llms-full.txt generator: path resolution, idempotence, spec shape, regen-drift guard, content contract, AGENTS.md install-path mirror, size-budget enforcement — 7 cases).
`test/build-llms.test.ts` (llms.txt/llms-full.txt generator: path resolution, idempotence, spec shape, regen-drift guard, content contract, AGENTS.md install-path mirror, size-budget enforcement — 7 cases),
`test/check-resolvable-cli.test.ts` (v0.19 CLI wrapper: exit codes, JSON envelope shape, AGENTS.md fallback chain),
`test/regression-v0_16_4.test.ts` (findRepoRoot regression guard — hermetic startDir parameterization),
`test/filing-audit.test.ts` (v0.19 Check 6: `writes_pages` / `writes_to` frontmatter, filing-rules JSON validation),
`test/routing-eval.test.ts` (v0.19 Check 5: fixture parsing, structural routing, ambiguous_with, Haiku tie-break layer),
`test/skill-manifest.test.ts` (v0.19 skill manifest parser: drift detection, managed-block markers),
`test/skillify-scaffold.test.ts` (v0.19 `gbrain skillify scaffold` stubs: SKILL.md, script, tests, routing-eval fixtures),
`test/skillpack-install.test.ts` (v0.19 `gbrain skillpack install` managed-block install / update / no-clobber semantics),
`test/skillpack-sync-guard.test.ts` (v0.19 sync-guard: bundled skills stay byte-identical to `skills/` source).
E2E tests (`test/e2e/`): Run against real Postgres+pgvector. Require `DATABASE_URL`.
- `bun run test:e2e` runs Tier 1 (mechanical, all operations, no API keys). Includes 9 dedicated cases for the postgres-engine `addLinksBatch` / `addTimelineEntriesBatch` bind path — postgres-js's `unnest()` binding is structurally different from PGLite's and gets its own coverage.
@@ -245,6 +284,11 @@ E2E tests (`test/e2e/`): Run against real Postgres+pgvector. Require `DATABASE_U
- `test/e2e/postgres-jsonb.test.ts` — v0.12.2 regression test. Round-trips all 5 JSONB write sites (pages.frontmatter, raw_data.data, ingest_log.pages_updated, files.metadata, page_versions.frontmatter) against real Postgres and asserts `jsonb_typeof='object'` plus `->>'key'` returns the expected scalar. The test that should have caught the original double-encode bug.
- `test/e2e/jsonb-roundtrip.test.ts` — v0.12.3 companion regression against the 4 doctor-scanned JSONB sites. Assertion-level overlap with `postgres-jsonb.test.ts` is intentional defense-in-depth: if doctor's scan surface ever drifts from the actual write surface, one of these tests catches it.
- `test/e2e/upgrade.test.ts` runs check-update E2E against real GitHub API (network required)
- `test/e2e/minions-shell-pglite.test.ts` (v0.20.4) exercises the PGLite `--follow` inline shell-job path (in-memory, no `DATABASE_URL` required) — the path the consolidated minion-orchestrator skill documents for dev use
- `test/e2e/openclaw-reference-compat.test.ts` (v0.19) — exercises `check-resolvable` + `skillpack install` against a minimal AGENTS.md workspace fixture (`test/fixtures/openclaw-reference-minimal/`), regression guard for the 107-skill OpenClaw deployment shape
- `test/e2e/search-swamp.test.ts` (v0.22.0) — reproduces the headline source-swamp case. Seeds a curated `originals/talks/article-outline-fat-code` page against two `wintermute/chat/` pages stuffed with the same multi-word phrase. Asserts the article wins keyword AND vector ranking, that `detail=high` lets the chat swamp re-surface (temporal-query workflow preserved), and that `source_id` passes through the two-stage CTE intact. PGLite in-memory.
- `test/e2e/search-exclude.test.ts` (v0.22.0) — verifies `test/` + `archive/` pages are hidden by default, that `include_slug_prefixes` opts back in, and that caller-supplied `exclude_slug_prefixes` adds to defaults. Both keyword and vector search paths covered.
- `test/e2e/engine-parity.test.ts` (v0.22.0) — Postgres ↔ PGLite top-result and result-set parity for `searchKeyword` + `searchVector`. Codex flagged that Postgres ranks pages then picks best chunk while PGLite returns chunks directly — without parity coverage the source-boost fix could pass on PGLite and fail on Postgres. Skips gracefully when `DATABASE_URL` is unset.
- Tier 2 (`skills.test.ts`) requires OpenClaw + API keys, runs nightly in CI
- If `.env.testing` doesn't exist in this directory, check sibling worktrees for one:
`find ../ -maxdepth 2 -name .env.testing -print -quit` and copy it here if found.
@@ -296,8 +340,8 @@ stop and remove it before starting a new one.
## Skills
Read the skill files in `skills/` before doing brain operations. GBrain ships 26 skills
organized by `skills/RESOLVER.md`:
Read the skill files in `skills/` before doing brain operations. GBrain ships 29 skills
organized by `skills/RESOLVER.md` (`AGENTS.md` is also accepted as of v0.19):
**Original 8 (conformance-migrated):** ingest (thin router), query, maintain, enrich,
briefing, migrate, setup, publish.
@@ -306,7 +350,18 @@ briefing, migrate, setup, publish.
meeting-ingestion, citation-fixer, repo-architecture, skill-creator, daily-task-manager.
**Operational + identity:** daily-task-prep, cross-modal-review, cron-scheduler, reports,
testing, soul-audit, webhook-transforms, data-research, minion-orchestrator.
testing, soul-audit, webhook-transforms, data-research, minion-orchestrator. As of
v0.20.4, `minion-orchestrator` is the single unified skill for both lanes of background
work (shell jobs via `gbrain jobs submit shell`, LLM subagents via `gbrain agent run`) ...
the prior `gbrain-jobs` skill was merged in, Preconditions are shared, and trigger
routing is narrowed to what the skill actually covers.
**Skillify loop (v0.19):** skillify (the markdown orchestration), skillpack-check
(agent-readable health report).
**Operational health (v0.19.1):** smoke-test (8 post-restart health checks with auto-fix
for Bun, CLI, DB, worker, Zod CJS, gateway, API key, brain repo; user-extensible via
`~/.gbrain/smoke-tests.d/*.sh`).
**Conventions:** `skills/conventions/` has cross-cutting rules (quality, brain-first,
model-routing, test-before-bulk, cross-modal). `skills/_brain-filing-rules.md` and
@@ -348,6 +403,59 @@ in bulk paths, the CI guard will fail the build.
`bun build --compile --outfile bin/gbrain src/cli.ts`
## Version locations (single source of truth: `VERSION` file)
Every release advances the version in **five files at once**. Keep these in
sync. `/ship` enforces this via Step 12's idempotency check (VERSION vs
package.json drift), but the canonical list lives here so future runs and
the auto-update agent know where to look.
**Required (every release must update all five):**
| File | What lives there | Format |
|---|---|---|
| `VERSION` | The single source of truth. Read first by `/ship`, the binary, and CI version-gate. | Bare 4-digit string `MAJOR.MINOR.PATCH.MICRO` (e.g. `0.22.1`), no leading `v`, no trailing newline-sensitivity issues. |
| `package.json` | Bun/npm package version. `gbrain --version` reads it via the compiled binary's bundled package metadata. CI version-gate cross-checks this against `VERSION` and fails if they drift. | `"version": "0.22.1"` |
| `CHANGELOG.md` | Top entry header `## [0.22.1] - YYYY-MM-DD` plus the "To take advantage of v0.22.1" block. | Standard Keep-a-Changelog header. |
| `TODOS.md` | Any TODO entries that mention "follow-up from vX.Y.Z" use the version of the release that filed them. Update only when filing NEW follow-up TODOs. | Inline `vX.Y.Z` references in TODO bodies. |
| `CLAUDE.md` | The Key Files section's per-file annotations carry `vX.Y.Z (#NNN)` tags noting which release introduced a behavior. Update whenever a wave's annotations get folded in. | Inline `vX.Y.Z (#NNN, contributed by @user)` references. |
**Auto-derived (no manual edit; refreshed by their own commands):**
- `bun.lock` — root-package version is auto-pinned from `package.json`. After
bumping `package.json`, run `bun install` to refresh the lockfile.
- `llms-full.txt` / `llms.txt` — auto-generated documentation bundles. After
any release ship that touches the Key Files annotations in `CLAUDE.md`,
run `bun run build:llms` to regenerate. The bundles do not contain a
version pin per se; they reflect the current state of the docs they index.
**Historical (DO NOT bump on release):**
- `skills/migrations/v0.21.0.md` — migration files use the version they
shipped FROM as their filename. v0.21.0's migration always says v0.21.0.
- `src/commands/migrations/v0_21_0.ts` — same: migration code references
the schema version it migrates to.
- `test/migrations-v0_21_0.test.ts`, `test/migration-orchestrator-v0_21_0.test.ts`,
`test/migrate.test.ts` — migration tests reference historical migration
versions; these are correct as-is and should not move.
- `src/core/db.ts`, `src/core/migrate.ts`, `src/core/import-file.ts`,
`src/commands/reindex-code.ts` — code comments cite the release that
introduced a feature. Once written, these are historical record.
- `README.md` — references the latest published feature names by version
(e.g. "v0.21.0 Code Cathedral"); update only when the README's marketing
copy is intentionally being refreshed, NOT on every micro/patch bump.
**The /ship workflow's version idempotency check:** Step 12 reads
`VERSION` and `package.json`, classifies as FRESH / ALREADY_BUMPED /
DRIFT_STALE_PKG / DRIFT_UNEXPECTED, and refuses to proceed on
DRIFT_UNEXPECTED. This is why the two must move together.
**The CI version-gate** rejects pushes where `VERSION` and
`package.json` disagree, OR where `VERSION` is not strictly greater
than master's VERSION. If a queue collision claims your version on
master before yours lands, /ship's queue-aware allocator (Step 12)
will detect drift and re-bump on the next run.
## Pre-ship requirements
Before shipping (/ship) or reviewing (/review), always run the full test suite:
@@ -376,6 +484,52 @@ Files that MUST be checked on every ship:
A ship without updated docs is an incomplete ship. Period.
## CHANGELOG + VERSION are branch-scoped
**VERSION and CHANGELOG describe what THIS branch adds vs master, not how we got
here.** Every feature branch that ships gets its own version bump and CHANGELOG
entry. The entry is product release notes for users; it is not a log of internal
decisions, review rounds, or codex findings.
**Write the CHANGELOG entry at /ship time, not during development.** Mid-branch
iterations, review rounds (CEO/Eng/Codex/DX), and implementation detours belong
in the plan file at `~/.claude/plans/`, not in the CHANGELOG. One unified entry
per branch, covering what the branch added vs the base branch.
**Never edit a CHANGELOG entry that already landed on master.** If master has
v0.18.2 and your branch adds features, bump to the next version (v0.19.0, not
editing master's v0.18.2). When merging master into your branch, master may
bring new CHANGELOG entries above yours — push your entry above master's
latest and verify:
- Does CHANGELOG have your branch's own entry separate from master's entries?
- Is VERSION higher than master's VERSION?
- Is your entry the topmost `## [X.Y.Z]` entry?
- `grep "^## \[" CHANGELOG.md` shows a contiguous version sequence?
If any answer is no, fix it before continuing.
**CHANGELOG is for users, not contributors.** Write like product release notes:
- Lead with what the user can now **do** that they couldn't before. Sell the capability.
- Plain language, not implementation details. "You can now..." not "Refactored the..."
- **Never mention internal artifacts**: plan file IDs, decision tags (D-CX-#, F-ENG-#),
review rounds, codex findings, subcontractor credits. These are invisible to users.
- Put contributor-facing changes in a separate `### For contributors` section at the bottom.
- Every entry should make someone think "oh nice, I want to try that."
**What to omit:**
- "Codex caught X that the CEO review missed" — private process detail.
- "D-CX-3 split errors/warnings" — tag is meaningless to users; name the feature instead.
- "Fix-wave PR #N supersedes #M" — supersede chains belong in PR bodies, not release notes.
- "215 new cases, 3 decisions applied, 7 reviews cleared" — these are planning-mode metrics.
**What to keep:**
- The user-facing change: what commands exist now, what flag was added, what behavior fixed.
- Numbers that mean something to the user: TTHW, commands that timed out before, detection counts.
- Upgrade instructions: `gbrain upgrade` + any manual step if needed.
- Credit to external contributors when a community PR was incorporated.
## CHANGELOG voice + release-summary format
Every version entry in `CHANGELOG.md` MUST start with a release-summary section in
@@ -416,7 +570,7 @@ Voice rules:
Source material to pull from:
- CHANGELOG.md previous entry for prior context
- `docs/benchmarks/[latest].md` for the headline numbers
- Latest `gbrain-evals/docs/benchmarks/[latest].md` for headline numbers (sibling repo)
- Recent commits (`git log <prev-version>..HEAD --oneline`) for what shipped
- Don't make up numbers. If a metric isn't in a benchmark or production data, don't
include it. Say "no measurement yet" if asked.
@@ -596,6 +750,59 @@ GitHub, etc.) are fine — they're public entities, not contacts in anyone's bra
Do not confuse illustrative API examples with queries that reveal real
relationships.
## Responsible-disclosure rule: don't broadcast attack surface in release notes
**When a release fixes a security gap or a user-impacting bug, describe the fix
functionally. Do not enumerate the attack surface, quantify the exposure window,
or highlight the most sensitive records by name in public-facing artifacts.**
Public-facing artifacts include: `CHANGELOG.md`, `README.md`, `docs/`, PR titles
and bodies, commit messages, GitHub issue titles and comments, release pages,
tweets, blog posts.
**Don't write:**
- "10 tables were publicly readable by the anon key for months, including X, Y, Z"
- "X and Y are the most sensitive ones"
- "N tables exposed. Fix: enable RLS on these specific tables: ..."
**Do write:**
- "Security hardening pass. Fresh installs secure by default. Existing brains
brought to the same bar automatically on upgrade."
- "If `gbrain doctor` still flags anything after upgrade, the message names each
table and gives the exact fix."
Why: anyone reading the release page before they've upgraded now has a directed
probe list for unpatched installs. The source code ships the specifics anyway
(`src/schema.sql`, `src/core/migrate.ts`, test fixtures) — reverse engineers can
get them. But the release page is a broadcast channel. Don't hand attackers a
curated list with a banner.
**The test:** if a reader with no prior context could read the release note and
walk away knowing "gbrain at version X has table Y readable by anon key until
they patch," the note is too specific. Rewrite until that's no longer possible.
**What IS fine in public artifacts:**
- The mechanism of the fix ("the check now scans every public table instead of
a hardcoded allowlist").
- User-facing operator ergonomics (the escape-hatch SQL template, the upgrade
commands, the breaking-change flag).
- Credit to contributors.
- Generic framing of severity ("security posture tightening pass") without
quantification.
**What stays in private artifacts (plan files, private memories, internal docs):**
- Specific table names, record counts, exposure duration.
- Which records stand out as highest-risk.
- Detailed before/after tables in the "numbers that matter" format.
If the CEO/Eng review of a plan produces a detailed exposure table, keep it in
the plan file under `~/.claude/plans/` or `~/.gstack/projects/`. Don't copy it
into the CHANGELOG or PR body.
Applies retroactively: if you see a prior CHANGELOG entry naming attack-surface
specifics, scrub it as a small cleanup commit, the same way a stale Wintermute
reference gets swept.
## Schema state tracking
`~/.gbrain/update-state.json` tracks which recommended schema directories the user
+129 -36
View File
@@ -4,9 +4,9 @@ Your AI agent is smart but forgetful. GBrain gives it a brain.
Built by the President and CEO of Y Combinator to run his actual AI agents. The production brain powering his OpenClaw and Hermes deployments: **17,888 pages, 4,383 people, 723 companies**, 21 cron jobs running autonomously, built in 12 days. The agent ingests meetings, emails, tweets, voice calls, and original ideas while you sleep. It enriches every person and company it encounters. It fixes its own citations and consolidates memory overnight. You wake up and the brain is smarter than when you went to bed.
The brain wires itself. Every page write extracts entity references and creates typed links (`attended`, `works_at`, `invested_in`, `founded`, `advises`) with zero LLM calls. Hybrid search. Self-wiring knowledge graph. Structured timeline. Backlink-boosted ranking. Ask "who works at Acme AI?" or "what did Bob invest in this quarter?" and get answers vector search alone can't reach. Benchmarked end-to-end: **Recall@5 jumps from 83% to 95%, Precision@5 from 39% to 45%, +30 more correct answers in the agent's top-5 reads** on a 240-page Opus-generated rich-prose corpus. Graph-only F1: **86.6% vs grep's 57.8%** (+28.8 pts). [Full report](docs/benchmarks/2026-04-18-brainbench-v1.md).
The brain wires itself. Every page write extracts entity references and creates typed links (`attended`, `works_at`, `invested_in`, `founded`, `advises`) with zero LLM calls. Hybrid search. Self-wiring knowledge graph. Structured timeline. Backlink-boosted ranking. Ask "who works at Acme AI?" or "what did Bob invest in this quarter?" and get answers vector search alone can't reach. Benchmarked side-by-side against the category: gbrain lands **P@5 49.1%, R@5 97.9%** on a 240-page Opus-generated rich-prose corpus, beating its own graph-disabled variant by **+31.4 points P@5** and ripgrep-BM25 + vector-only RAG by a similar margin. The graph layer plus v0.12 extract quality together carry the gap. Full BrainBench scorecards + corpus live in the sibling [gbrain-evals](https://github.com/garrytan/gbrain-evals) repo.
GBrain is those patterns, generalized. 26 skills. Install in 30 minutes. Your agent does the work. As Garry's personal agent gets smarter, so does yours.
GBrain is those patterns, generalized. 29 skills. Install in 30 minutes. Your agent does the work. As Garry's personal agent gets smarter, so does yours.
> **~30 minutes to a fully working brain.** Database ready in 2 seconds (PGLite, no server). You just answer questions about API keys.
@@ -28,7 +28,7 @@ Retrieve and follow the instructions at:
https://raw.githubusercontent.com/garrytan/gbrain/master/INSTALL_FOR_AGENTS.md
```
That's it. The agent clones the repo, installs GBrain, sets up the brain, loads 26 skills, and configures recurring jobs. You answer a few questions about API keys. ~30 minutes.
That's it. The agent clones the repo, installs GBrain, sets up the brain, loads 29 skills, and configures recurring jobs. You answer a few questions about API keys. ~30 minutes.
If your agent doesn't auto-read `AGENTS.md`, point it at that file first:
`https://raw.githubusercontent.com/garrytan/gbrain/master/AGENTS.md` is the non-Claude
@@ -87,9 +87,25 @@ claude mcp add gbrain -t http https://your-brain.ngrok.app/mcp -H "Authorization
Per-client guides: [`docs/mcp/`](docs/mcp/DEPLOY.md). ChatGPT requires OAuth 2.1 (not yet implemented).
## The 26 Skills
### Using gbrain with GStack
GBrain ships 26 skills organized by `skills/RESOLVER.md`. The resolver tells your agent which skill to read for any task.
If your engineering agent runs on [GStack](https://github.com/garrytan/gstack), point it at gbrain for code lookup instead of grep+read. Cathedral II (v0.21.0) ships call-graph edges and two-pass retrieval — `/investigate`, `/review`, `/plan-eng-review`, and `/office-hours` all benefit when the agent walks the symbol graph instead of scanning files line by line.
The five magical-moment commands:
```bash
gbrain code-callers searchKeyword # who calls this symbol?
gbrain code-callees searchKeyword # what does this symbol call?
gbrain code-def BrainEngine # where is X defined?
gbrain code-refs BrainEngine # all reference sites
gbrain query "how does N+1 handling work" --near-symbol BrainEngine.searchKeyword --walk-depth 2
```
All five auto-emit JSON on non-TTY (gh-CLI convention) so a GStack subagent shelling out via bash gets a clean parseable response. Run `gbrain sources add <repo> --strategy code` to index a repo, then your agent's brain-first lookup covers code, not just markdown. ([Cathedral II release notes](CHANGELOG.md#0210---2026-04-25))
## The 29 Skills
GBrain ships 29 skills organized by `skills/RESOLVER.md` (or your OpenClaw's `AGENTS.md` — both filenames are supported as of v0.19). The resolver tells your agent which skill to read for any task.
[Skill files are code.](https://x.com/garrytan/status/2042925773300908103) They're the most powerful way to get knowledge work done. A skill file is a fat markdown document that encodes an entire workflow: when to fire, what to check, how to chain with other skills, what quality bar to enforce. The agent reads the skill and executes it. Skills can also call deterministic TypeScript code bundled in GBrain (search, import, embed, sync) for the parts that shouldn't be left to LLM judgment. [Thin harness, fat skills](docs/ethos/THIN_HARNESS_FAT_SKILLS.md): the intelligence lives in the skills, not the runtime.
@@ -133,7 +149,10 @@ GBrain ships 26 skills organized by `skills/RESOLVER.md`. The resolver tells you
| **webhook-transforms** | External events (SMS, meetings, social mentions) converted into brain pages with entity extraction. |
| **testing** | Validates every skill has SKILL.md with frontmatter, manifest coverage, resolver coverage. |
| **skill-creator** | Create new skills following the conformance standard. MECE check against existing skills. |
| **minion-orchestrator** | Long-running agent work as background jobs. Submit, fan out children with depth/cap/timeouts, collect results via child_done inbox. |
| **skillify** | The "skillify it!" meta-skill. Orchestrates the 10-step loop so failures become durable skills: scaffold the stubs via `gbrain skillify scaffold`, write the real logic, gate with `gbrain skillify check` + `gbrain check-resolvable`. |
| **skillpack-check** | Agent-readable gbrain health report. Exit code for CI; JSON for debugging. Cron-friendly. |
| **smoke-test** | 8 post-restart health checks with auto-fix (Bun, CLI, DB, worker, Zod CJS, gateway, API key, brain repo). Drop-in user tests at `~/.gbrain/smoke-tests.d/*.sh`. |
| **minion-orchestrator** | Background work in one skill. Shell jobs via `gbrain jobs submit shell` (operator/CLI, MCP blocks protected names) and LLM subagents via `gbrain agent run`. Parent-child DAGs, `child_done` inbox, durability across worker restarts. |
### Identity and setup
@@ -192,7 +211,7 @@ Here's my personal OpenClaw deployment: one Render container. Supabase Postgres
Under that 19-cron load, sub-agent spawn couldn't clear the 10-second gateway wall. Minions landed it in under a second for zero tokens. **Scaling:** 19,240 posts across 36 months, single bash loop, ~15 min total, $0.00. Sub-agents: ~9 min best case, ~$1.08 in tokens, ~40% spawn failure. **Lab:** durability ∞ (SIGKILL mid-flight, 10/10 rescued), throughput ~10× faster, fan-out ~21× with no failure wall, memory ~400× less.
Full benchmarks: [production](docs/benchmarks/2026-04-18-minions-vs-openclaw-production.md) and [lab](docs/benchmarks/2026-04-18-minions-vs-openclaw-subagents.md).
Full benchmarks live in [gbrain-evals](https://github.com/garrytan/gbrain-evals/tree/main/docs/benchmarks).
### The routing rule
@@ -209,9 +228,12 @@ The six daily pains — spawn storms, agents that stop responding, forgotten dis
gbrain jobs smoke # verify install
gbrain jobs submit sync --params '{}' # fire a background job
gbrain jobs stats # health dashboard
gbrain jobs work --concurrency 4 # start a worker (Postgres only)
gbrain jobs supervisor --concurrency 4 # canonical: auto-restarting worker (Postgres only)
gbrain jobs work --concurrency 4 # raw worker (no crash recovery — prefer `supervisor`)
```
`gbrain jobs supervisor` keeps the worker alive across crashes with exponential backoff, atomic PID locking, structured audit events at `~/.gbrain/audit/supervisor-*.jsonl`, and a `start --detach` / `status --json` / `stop` subcommand surface for agents. In containers it runs as PID 1; on systemd hosts it's the child of `gbrain-worker.service`. Full deployment guide: [`docs/guides/minions-deployment.md`](docs/guides/minions-deployment.md).
Read [`skills/minion-orchestrator/SKILL.md`](skills/minion-orchestrator/SKILL.md) for parent-child DAGs, fan-in collection, steering via inbox.
**Minions is not incrementally better than sub-agents for background work. It's categorically different.** 753ms vs gateway timeout. $0 vs tokens. 100% vs couldn't-spawn. If your agent does deterministic work on a schedule, it runs on Minions now.
@@ -249,38 +271,93 @@ gbrain agent logs 1247 --follow --since 5m
Durability is the point: every Anthropic turn commits to `subagent_messages`, every tool call to `subagent_tool_executions`. Worker kills, OpenClaw crashes, timeouts — all resumable. Host repos (your OpenClaw, etc.) ship their own subagent definitions via `GBRAIN_PLUGIN_PATH` + a `gbrain.plugin.json` manifest: see [`docs/guides/plugin-authors.md`](docs/guides/plugin-authors.md). Requires `ANTHROPIC_API_KEY` on the worker.
## Skillify: your skills tree stops being a black box
## Skillify: say "skillify it!" and the bug becomes structurally impossible to repeat
Hermes and similar agent frameworks auto-create skills as a background behavior. Fine until you don't know what the agent shipped. Checklists decay. Tests drift. Resolver entries get stale. Six months later you've got an opaque pile of "skills" that nobody has read, nobody has tested, and nobody is sure still work.
Your OpenClaw hit a new failure. You fix it once in conversation. You say "skillify it!"
And now the fix is permanent: a SKILL.md with triggers, a deterministic script with tests, a
routing fixture the agent re-evaluates daily, a filing audit that keeps the output from
drifting. Ten items. Every one required. The bug can't recur.
GBrain ships the same capability. Except the human stays in the loop.
Hermes and similar agent frameworks auto-create skills as a background behavior. Fine until
you don't know what the agent shipped. Checklists decay. Tests drift. Resolver entries get
stale. Six months later it's an opaque pile nobody has read, nobody has tested, and nobody
is sure still works. GBrain ships the same capability except the human stays in the loop
and every step is a command you can run.
- **`/skillify`** turns raw code into a properly-skilled feature: SKILL.md + deterministic script + unit tests + integration tests + LLM evals + resolver trigger + resolver trigger eval + E2E smoke + brain filing. Ten items. Every one required.
- **`gbrain check-resolvable`** walks the whole skills tree: reachability, MECE overlap, DRY violations, gap detection, orphaned skills. Exits non-zero if anything is off.
- **`scripts/skillify-check.ts`** — machine-readable audit. `--json` for CI, `--recent` for last-7-days files.
You decide when and what. The tooling keeps the checklist honest.
### Why this is the right answer for OpenClaw
Auto-generated skills are a liability the first time a behavior breaks. Was it the skill? The test? The resolver trigger? The eval? You don't know, because you never read it. Debugging a black box is pure guesswork.
Skillify makes the black box legible. Every skill in your tree has: a contract (SKILL.md), tests that exercise that contract, an eval that grades LLM output against a rubric, a resolver trigger the user actually types, and a test that confirms the trigger routes right. If something breaks, you know which layer to look at. If anything goes stale, `check-resolvable` says so.
In practice this combo produces **zero orphaned skills, every feature with tests + evals + resolver triggers + evals of the triggers.** Compounding quality instead of compounding entropy.
### The four verbs you need (v0.19)
```bash
# Audit a feature's skill completeness (10-item checklist)
bun run scripts/skillify-check.ts src/commands/publish.ts
# 1. Scaffold all 5 stub files for a new skill in one shot.
gbrain skillify scaffold webhook-verify \
--description "verify ngrok webhooks" \
--triggers "verify the webhook,check tunnel" \
--writes-pages --writes-to people/,companies/
# In CI: fail the build when a new feature isn't properly skilled
bun run scripts/skillify-check.ts --json --recent
# 2. Replace the SKILLIFY_STUB sentinels with real logic + real tests.
$EDITOR skills/webhook-verify/scripts/webhook-verify.mjs
$EDITOR test/webhook-verify.test.ts
# Validate the whole skills tree before shipping
gbrain check-resolvable
# 3. Run the 10-item audit: SKILL.md exists, script exists, unit + E2E tests,
# LLM evals, resolver entry, trigger eval, check-resolvable gate, brain filing.
gbrain skillify check skills/webhook-verify/scripts/webhook-verify.mjs
# 4. Verify the whole tree: reachability, MECE overlap, DRY, routing gaps,
# filing audit, SKILLIFY_STUB sentinels (fails if any skill still has one).
gbrain check-resolvable # warnings advisory, errors block
gbrain check-resolvable --strict # warnings block too (CI opt-in)
```
**Skillify is not a nice-to-have. It's the piece that makes the skills tree survive six months of compounding work.** Read [`skills/skillify/SKILL.md`](skills/skillify/SKILL.md) for the full 10-item checklist and the anti-patterns it catches.
Idempotent re-runs. `--force` regenerates stub files but NEVER duplicates a resolver row.
Scaffold completes in under 2 seconds. The real work (your rule, your script, your tests)
is what you spend time on. Everything else is boilerplate the CLI writes for you.
### `gbrain routing-eval` — catch the routing gaps your users actually hit
Drop a `routing-eval.jsonl` fixture next to any skill. Each line is `{intent, expected_skill,
ambiguous_with?}`. `gbrain check-resolvable` runs the structural layer by default; `gbrain
routing-eval --llm` runs an LLM tie-break layer for CI. False positives (wrong skill matched),
missed routes (no skill matched), and tautological fixtures (intent copies trigger verbatim)
all surface as specific advisories with the exact file:line to fix.
### Works on your OpenClaw, not just gbrain's repo
v0.19 teaches `gbrain check-resolvable` to accept `AGENTS.md` as a resolver file alongside
`RESOLVER.md`, at either the skills directory OR one level up (OpenClaw-native workspace-root
layout). The skill manifest auto-derives from walking `skills/*/SKILL.md` when `manifest.json`
is missing. Set `OPENCLAW_WORKSPACE=~/your-openclaw/workspace` and everything just works:
```bash
export OPENCLAW_WORKSPACE=~/your-openclaw/workspace
gbrain check-resolvable --verbose
# Auto-detects: AGENTS.md at workspace root, 107 skills derived from SKILL.md walk,
# 15 unreachable errors surfaced, 108 advisory warnings for overlaps and gaps.
```
First run on a real OpenClaw deployment found 15 unreachable skills out of 102 — about 15%
of the tree was dark. The essay's "skills the agent can never reach" footgun, now visible.
### `gbrain skillpack install` — drop 25 curated skills into your OpenClaw
The skills gbrain ships are a curated bundle. Install them into your workspace with
dependency closure (shared conventions come along), per-file diff protection (your local
edits are never clobbered without `--overwrite-local`), a file lock that serializes
concurrent installers, and an atomic managed-block update to your AGENTS.md so you can
see exactly what gbrain wrote.
```bash
gbrain skillpack list # 25 curated skills
gbrain skillpack install brain-ops # one skill + its shared conventions
gbrain skillpack install --all # the full bundle
gbrain skillpack install brain-ops --dry-run # preview; no writes
gbrain skillpack diff brain-ops # compare bundle vs your local copy
```
Re-running is safe. The managed-block markers in your AGENTS.md let `skillpack install`
accumulate rows across separate single-skill installs instead of overwriting each other.
**Skillify is the piece that makes the skills tree survive six months of compounding work.**
Read [`skills/skillify/SKILL.md`](skills/skillify/SKILL.md) for the full 10-item checklist
and the anti-patterns it catches.
## Getting Data In
@@ -317,7 +394,7 @@ Run `gbrain integrations` to see status.
│ Brain Repo │ │ GBrain │ │ AI Agent │
│ (git) │ │ (retrieval) │ │ (read/write) │
│ │ │ │ │ │
│ markdown files │───>│ Postgres + │<──>│ 26 skills │
│ markdown files │───>│ Postgres + │<──>│ 29 skills │
│ = source of │ │ pgvector │ │ define HOW to │
│ truth │ │ │ │ use the brain │
│ │<───│ hybrid │ │ │
@@ -381,7 +458,7 @@ gbrain extract links --source db # wire up the existing 29K pages
gbrain extract timeline --source db # extract dated events from markdown timelines
```
Then ask graph questions or watch the search ranking improve. Benchmarked: **Recall@5 jumps from 83% to 95%, Precision@5 from 39% to 45%, +30 more correct answers in the agent's top-5 reads** on a 240-page Opus-generated rich-prose corpus. Graph-only F1 hits 86.6% vs grep's 57.8% (+28.8 pts). See [docs/benchmarks/2026-04-18-brainbench-v1.md](docs/benchmarks/2026-04-18-brainbench-v1.md).
Then ask graph questions or watch the search ranking improve. Benchmarked side-by-side against ripgrep-BM25, vector-only RAG (same embedder), and gbrain-with-graph-disabled: gbrain lands **P@5 49.1%, R@5 97.9%** on a 240-page Opus-generated rich-prose corpus, beating hybrid-nograph by **+31.4 points P@5**. Isolate the contribution: v0.11→v0.12 moved the same gbrain codebase from P@5 22.1% → 49.1% on identical inputs, so typed-link extract quality is load-bearing. Full scorecards + reproducible corpus: [gbrain-evals](https://github.com/garrytan/gbrain-evals).
## Search
@@ -428,6 +505,8 @@ Question
│ ├─ Multi-query expansion (Haiku rephrases the question 3 ways)
│ ├─ Vector search (HNSW cosine over OpenAI embeddings)
│ ├─ Keyword search (Postgres tsvector + websearch_to_tsquery)
│ ├─ Source-aware ranking (curated dirs outrank chat/daily swamp at SQL layer)
│ ├─ Hard-exclude (test/ archive/ attachments/ .raw/ filtered before retrieval)
│ ├─ Reciprocal Rank Fusion (score = sum 1/(60+rank) across both)
│ ├─ Cosine re-scoring (re-rank chunks against actual query embedding)
│ ├─ Compiled-truth boost (assessments outrank timeline noise)
@@ -457,7 +536,7 @@ End-to-end on the BrainBench v1 corpus (240 rich-prose pages, before/after PR #1
Plus 5 orthogonal capability checks (identity resolution, temporal queries,
performance at 10K-page scale, robustness to malformed input, MCP operation
contract). All pass. [Full report.](docs/benchmarks/2026-04-18-brainbench-v1.md)
contract). All pass. Full report: [gbrain-evals](https://github.com/garrytan/gbrain-evals).
The point: each technique handles a class of inputs the others miss. Vector
search misses exact slug refs; keyword catches them. Keyword misses conceptual
@@ -561,12 +640,26 @@ JOBS (Minions)
gbrain jobs smoke One-command health check
gbrain jobs work [--queue Q] [--concurrency N] Start worker daemon
SKILLS (v0.19)
gbrain skillify scaffold <name> Create 5 stub files + idempotent resolver row
gbrain skillify check [path] 10-item audit of a skill
gbrain skillpack list Print the 25 curated skills in the bundle
gbrain skillpack install <name> Copy one skill + its shared conventions into target
gbrain skillpack install --all Install the full curated bundle
gbrain skillpack diff <name> Per-file diff: bundle vs target workspace
gbrain check-resolvable [--strict] Resolver audit (reachability, MECE, DRY, routing, filing,
SKILLIFY_STUB). Accepts RESOLVER.md OR AGENTS.md.
gbrain routing-eval [--llm] [--json] Intent→skill routing accuracy on fixtures
ADMIN
gbrain doctor [--json] [--fast] Health checks (resolver, skills, DB, embeddings)
gbrain doctor --fix [--dry-run] Auto-fix DRY violations (delegate inlined rules to conventions)
gbrain doctor --locks List idle-in-tx backends (57014 diagnostic, Postgres only)
gbrain stats Brain statistics
gbrain serve MCP server (stdio)
gbrain integrations Integration recipe dashboard
gbrain sources list|add|remove|... Multi-source brain management (v0.18)
gbrain dream [--dry-run] [--phase N] One maintenance cycle then exit (cron-friendly)
gbrain check-backlinks check|fix Back-link enforcement
gbrain lint [--fix] LLM artifact detection
gbrain repair-jsonb [--dry-run] Repair v0.12.0 double-encoded JSONB (Postgres)
@@ -590,7 +683,7 @@ The skills in this repo are those patterns, generalized. What took 11 days to bu
**For agents:**
- **[skills/RESOLVER.md](skills/RESOLVER.md)** ... Start here. The skill dispatcher.
- [Individual skill files](skills/) ... 25 standalone instruction sets
- [Individual skill files](skills/) ... 28 standalone instruction sets (25 ship in the curated `gbrain skillpack install` bundle)
- [GBRAIN_SKILLPACK.md](docs/GBRAIN_SKILLPACK.md) ... Legacy reference architecture
- [Getting Data In](docs/integrations/README.md) ... Integration recipes and data flow
- [GBRAIN_VERIFY.md](docs/GBRAIN_VERIFY.md) ... Installation verification
@@ -605,7 +698,7 @@ The skills in this repo are those patterns, generalized. What took 11 days to bu
- [CHANGELOG.md](CHANGELOG.md) ... Version history
**Benchmarks:**
- [BrainBench v1 (PR #188)](docs/benchmarks/2026-04-18-brainbench-v1.md) ... single comprehensive before/after report on a 240-page Opus-generated corpus. 7 categories: relational queries, identity resolution, temporal queries, performance, robustness, MCP contract.
- [gbrain-evals](https://github.com/garrytan/gbrain-evals) ... BrainBench, the sibling repo that holds the eval harness, corpus, scorecards, and 4-adapter comparisons. Depends on gbrain; not installed alongside gbrain.
## Contributing
+208 -49
View File
@@ -1,59 +1,166 @@
# TODOS
## check-resolvable
## resolver / check-resolvable (v0.22.4 follow-ups)
### File tracking issues for Checks 5 + 6 (deferred in PR #325)
### D10 — Extend `check-resolvable` to parse RESOLVER.md disambiguation rules
**Priority:** P2
**What:** `src/commands/check-resolvable.ts` currently points `DEFERRED[].issue` at GitHub issue search URLs (`?q=TBD-check-5`, `?q=TBD-check-6`). File real tracking issues and grep-replace both placeholders with the real URLs.
**What:** Extend `src/core/check-resolvable.ts:357-390` to parse a structured
disambiguation block in `RESOLVER.md` (e.g. a `## Disambiguation rules`
numbered list with parseable `<trigger>``<winning-skill>` shape) and treat
resolved overlaps as non-issues. Then the action message at
`src/core/check-resolvable.ts:388` ("Add disambiguation rule in RESOLVER.md OR
narrow triggers") stops lying about the OR — currently only the second branch
silences the warning.
**Why:** v0.16.4 shipped `gbrain check-resolvable` with 4 of the 6 checks from the original spec. Checks 5 (trigger routing eval) and 6 (brain filing) were explicitly deferred during plan-ceo-review because they each need new detection logic. The CLI's `deferred[]` JSON field is meant to surface these to agents so they know the coverage boundary — the TBD placeholders do the right thing mechanically but aren't clickable.
**Why:** The current MECE-overlap fix path forces authors to delete user-facing
triggers from skill frontmatter. That's wrong for cases where two skills
legitimately respond to the same phrase under different contexts (e.g.
"citation audit" → focused fix vs broader brain health). A real
disambiguation parser would let `RESOLVER.md` carry the resolution while
keeping both skills' triggers intact for chaining.
**How:**
1. `gh issue create -t "check-resolvable Check 5: trigger routing eval" -b "..."` — detection: every skill's own frontmatter trigger should match the RESOLVER.md entry pointing at that skill. Needs new issue type (e.g. `mis_route`).
2. `gh issue create -t "check-resolvable Check 6: brain filing validation" -b "..."` — detection: scan SKILL.md body for brain paths (e.g., `brain/people/`, `brain/companies/`), cross-reference with `skills/_brain-filing-rules.md`. Flag mutating skills missing entries.
3. Replace `TBD-check-5` and `TBD-check-6` in `src/commands/check-resolvable.ts` with the real issue URLs.
**Pros:**
- The action message stops misleading users.
- v0.22.4 D2 used the "narrow triggers" path because the disambiguation
parser doesn't exist yet; landing this would let v0.23+ keep dual triggers
for genuinely-overlapping skills.
- Aligns RESOLVER.md's stated role (the dispatcher) with what the checker
actually reads.
**Effort:** ~15 min mechanical (issue filing + grep-replace). Implementation of the checks themselves is a separate, larger piece of work — the TODO here is just the issue filing + URL swap.
**Cons:**
- Introduces a new `RESOLVER.md` syntactic contract that other tooling now
has to respect (parser, lint, downstream forks reading the same file).
- Risk of false-positive resolution if the parser is loose.
- ~80 lines of parser + tests; not blocking anything in v0.22.4.
## P1 (BrainBench v1.1 — categories deferred from PR #188)
**Context:**
- The "OR" in the action message is misleading today. Confirmed at
`src/core/check-resolvable.ts:388`.
- The MECE detector loop is at `src/core/check-resolvable.ts:357-390`.
- The disambiguation rules already exist as prose in
`skills/RESOLVER.md` (the citation-audit row added in v0.22.4 is the
pattern). They're agent-facing routing hints today, not parsed structure.
### BrainBench Cat 5: Source Attribution / Provenance
**What:** Eval that gbrain correctly cites the right page when claiming fact F, and resolves source-conflict cases (3 sources disagree on $5M raise — which wins?). 200 queries across citation/provenance/conflict sub-categories on a 300-entity dataset with deliberately-conflicting sources.
**Effort:** S (human: ~4-6 hours / CC: ~30 min for parser + 12-16 test cases).
**Why deferred from PR #188:** Needs ~$100-200 of Opus tokens to generate the conflict-graph dataset. v1 scope was procedural-only.
**Depends on / blocked by:** Nothing.
**Threshold:** citation_recall > 90%, citation_precision > 85%, conflict_resolution > 70%.
## code-indexing (v0.21.0 Cathedral II follow-ups)
**Depends on:** Identity Resolution (Cat 3) shipped — uses same world generator pattern.
### B2 — Magika auto-detect for extension-less files (Layer 9 deferred)
**Priority:** P2
### BrainBench Cat 6: Auto-link Precision under Prose (at scale)
**What:** Cat 10 (Robustness/Adversarial) covered code-fence leak and false-positive substrings on 22 hand-crafted cases. v1.1 extends this to 500+ prose-heavy pages with realistic narrative noise. Tests link precision in the wild, not just edge cases.
**What:** Embed Google's Magika ML classifier (~1MB ONNX) as a bundled asset. Wire into `detectCodeLanguage` as the fallback for files with no recognized extension (Dockerfile, Makefile, `.envrc`, shell scripts with shebangs but no `.sh`). The chunker already has `setLanguageFallback(fn)` as a module-level hook.
**Why deferred from PR #188:** Needs prose-heavy generated corpus (~$100-150 Opus). Existing 22-case eval already caught + fixed the code-fence leak bug.
**Why:** v0.20.0 widens the file classifier from 9 to 35 extensions (Layer 2), covering most real-world cases. Extension-less files still slip through to recursive chunks. Magika would close the last common case.
**Threshold:** link_precision > 95% on prose, type_accuracy > 80% on varied phrasing.
**Pros:** Completes the file-classification story. Unblocks chunker on real-world configs + build scripts.
### BrainBench Cat 8: Skill Behavior Compliance
**What:** Replays 100 inbound signals through a real LLM agent loop with gbrain skills loaded. Measures: brain-first lookup compliance, back-link iron-law adherence, citation format compliance, tier escalation correctness.
**Cons:** ~1MB asset bundled with `bun --compile`. Integration risk: Magika's ONNX runtime needs WASM compat with bun. The plan explicitly allowed deferring B2 because bundling surprises late in implementation are costly.
**Why deferred:** Needs real LLM API loop (~$2K total — most expensive single category).
**Context:**
- `src/core/chunkers/code.ts` exports `setLanguageFallback(fn: LanguageFallback | null)` — call at process start with a Magika-powered classifier.
- `detectCodeLanguage(filePath, content?)` already accepts optional content for fallback paths.
- The NPM `magika` package is the first thing to try; needs bun-compile compatibility verification.
**Threshold:** brain_first_compliance > 95%, back_link_compliance > 90%, citation_format > 95%.
**Effort:** M (human: ~2-3 days / CC: ~2 hours for the integration + CI guard).
### BrainBench Cat 9: End-to-End Workflows
**What:** 50 end-to-end scenarios across meeting ingestion, email-to-brain, daily-task-prep, briefing generation, sync cycle. Rubric-graded (10-15 criteria each).
**Depends on / blocked by:** Nothing. Hook is in place as of v0.20.0.
**Why deferred:** Needs LLM agent loop (~$1K). Plus 50 hand-built rubrics.
### A4 — full doc_comment extraction at chunk time
**Priority:** P2
**Threshold:** 80% scenario pass rate per workflow.
**What:** When the chunker emits a method/class/function, look at the comment node(s) immediately preceding the declaration and persist them as `content_chunks.doc_comment`. The FTS trigger from Layer 1b already weights `doc_comment` 'A' above `chunk_text` 'B' — the ranking is ready, the column is populated NULL today.
### BrainBench Cat 11: Multi-modal Ingestion
**What:** PDF/image/audio/video ingestion accuracy. 50 PDFs, 30 images, 20 audio files, 10 videos, 30 HTML pages. Per-modality recall and fidelity metrics.
**Why:** "how does X handle N+1" should rank the docstring that explains N+1 above the function body or any prose paragraph. Layer 1b paved the ranking half; extraction is the remaining half.
**Why deferred:** Needs licensed real datasets (Common Voice for audio etc.). Dataset curation is the bulk of the work.
**Pros:** Material MRR lift on natural-language queries. Zero schema work (column + trigger already in place).
**Threshold:** PDF text fidelity > 95% (text-based) / > 80% (scanned), audio WER < 15%, entity_recall > 80% post-ingestion.
**Cons:** Per-language convention detection — JSDoc blocks, Python docstrings (first string expression in a function body), C-style doc comments, etc. Not hard but each language has edge cases.
**Context:**
- `src/core/chunkers/code.ts` emits chunks in `chunkCodeTextFull`. Walk each declaration's preceding sibling(s) for comment nodes.
- ChunkInput already has `doc_comment?: string`. Populate at chunk time and it flows through `upsertChunks` (Layer 6 wired those columns).
- Per-language config: leading-comment type names per language (`comment`, `line_comment`, `block_comment`, `documentation_comment`).
- Test hook: `test/cathedral-ii-brainbench.test.ts` has a `doc_comment_matching` placeholder — flesh it out end-to-end.
**Effort:** M (human: ~2 days / CC: ~90 min for the 8 Layer-5 langs).
**Depends on / blocked by:** Nothing. Layer 1b + Layer 6 both in place.
### C6 — gbrain code-signature "(A, B) => C"
**Priority:** P3 (stretch)
**What:** Type-signature retrieval via tree-sitter type captures per language. "Find every function whose signature returns a Promise<User>" or "(string, number) => boolean".
**Why:** Each language's type system is its own mini-cathedral. Ship per-language rather than as one item.
**Effort:** L per language (typescript-first).
**Depends on / blocked by:** Nothing — additive on the Layer 5 edge schema.
### Cross-file edge resolution (Layer 5 precision upgrade)
**Priority:** P3
**What:** Today every call edge lands unresolved in `code_edges_symbol` with to_symbol_qualified = bare callee name. Second-pass resolution: after all code files import, walk every `code_edges_symbol` row and try to resolve `to_symbol_qualified` via `symbol_name_qualified` join; if found within the same source, write a resolved row to `code_edges_chunk`.
**Why:** `getCallersOf("searchKeyword")` currently returns the Layer 6 ambiguity — every `searchKeyword` call site in any class. Receiver-type analysis lifts this.
**Effort:** L. Needs receiver-type inference; can ship per-language.
**Depends on / blocked by:** Nothing — UNION-on-read path keeps unresolved edges surfaced even without this.
## Completed
### ~~Checks 5 + 6 for check-resolvable~~
**Completed:** v0.19.0 (2026-04-22)
Both checks shipped as real implementations, not just filed issues:
- **Check 5 (trigger routing eval):** `src/core/routing-eval.ts` + `gbrain routing-eval` CLI. Structural layer runs in `check-resolvable` by default; `--llm` opts into LLM tie-break. Fixtures live at `skills/<name>/routing-eval.jsonl`.
- **Check 6 (brain filing):** `src/core/filing-audit.ts` + `skills/_brain-filing-rules.json`. New `writes_pages:` + `writes_to:` frontmatter. Warning-only in v0.19, error in v0.20.
`DEFERRED[]` in `src/commands/check-resolvable.ts` is now empty — v0.19 shipped both deferred checks as working code paths, not as issue URLs. The export stays in place for future deferred checks.
### ~~BrainBench Cats 5/6/8/9/11 — shipped to sibling repo~~
**Completed:** v0.20.0 (2026-04-23)
All five previously-deferred BrainBench categories shipped as working runners
in the sibling repo [github.com/garrytan/gbrain-evals](https://github.com/garrytan/gbrain-evals):
- **Cat 5 Provenance** — `eval/runner/cat5-provenance.ts` with dedicated `classify_claim` tool (3-way label: `supported | unsupported | over-generalized`)
- **Cat 6 Prose-scale auto-link precision** — `eval/runner/cat6-prose-scale.ts` (baseline-only) + `eval/runner/adversarial-injections.ts` (6 injection kinds)
- **Cat 8 Skill Compliance** — `eval/runner/cat8-skill-compliance.ts` (brain-first / back-link / citation-format / tier-escalation, deterministic from tool-bridge trace)
- **Cat 9 End-to-End Workflows** — `eval/runner/cat9-workflows.ts` (rubric-graded)
- **Cat 11 Multi-modal Ingestion** — `eval/runner/cat11-multimodal.ts` (PDF/audio/HTML)
Plus supporting infrastructure: agent adapter (Sonnet + 12 read + 3 dry_run tools),
structured-evidence Haiku judge contract, PublicPage/PublicQuery sealed qrels,
6-artifact flight-recorder, 6 portable JSON schemas for v1→v2 driver swap.
Scope pivot: originally planned for in-tree v1.1 delta; mid-PR pivoted to extract
the entire eval harness so gbrain users don't download the ~5MB corpus at install
time. BrainBench is now a public sibling benchmark; gbrain ships clean.
### ~~v0.10.5: inferLinkType residuals (works_at, advises)~~
**Completed:** v0.20.0 (2026-04-23)
`src/core/link-extraction.ts` — WORKS_AT_RE and ADVISES_RE expanded with
rank-prefixed engineer patterns ("senior/staff/principal/lead engineer at"),
discipline-prefixed ("backend/frontend/ML/security engineer at"), broader role
verbs ("manages engineering at", "running product at", "heads up X at"),
possessive time ("his/her/their time at"), role-noun forms ("tenure as",
"stint as", "role at"), advisory capacity phrasings, "as an advisor" forms,
and qualifier-specific advisors. New EMPLOYEE_ROLE_RE prior fires for
self-identified employees at the page level, biasing outbound company refs
toward works_at when per-edge verbs are absent. Precedence: investor > advisor
> employee. Existing tests in `test/link-extraction.test.ts` cover the new
patterns.
## P1 (BrainBench v1.1 — remaining categories)
Cats 5/6/8/9/11 shipped to the sibling repo in v0.20.0 — see the Completed
section above. One remaining scope item:
### BrainBench Cat 1+2 at full scale
**What:** Existing benchmark-search-quality.ts (29 pages, 20 queries) and benchmark-graph-quality.ts (80 pages, 5 queries) currently pass at small scale. v1.1 extends both to 2-3K rich-prose pages generated via Opus to surface scale-dependent failures (tied keyword clusters, hub-node fan-out, prose-noise extraction precision).
@@ -73,24 +180,6 @@ company refs only). Per-type after fix: invested_in 91.7% (was 0%),
mentions 100%, attended 100%. works_at 58% and advises 41% are next
iteration's residuals.
### v0.10.5: inferLinkType residuals (works_at, advises)
**What:** After the v0.10.4 fix, two link types still under-perform on rich
prose. Drive these to >85% type accuracy in next iteration.
**works_at: 58% type accuracy.** Engineer/employee pages use varied phrasings
the regex doesn't catch ("spent some time at", "joined the team", narrative
"is currently at" without a verb). Approach: extend WORKS_AT_RE; consider
employee-role page prior similar to partner prior.
**advises: 41% type accuracy.** Advisor pages often describe board roles
without using the word "advisor" explicitly ("on Beta Health's board",
"joined Beta as a board member"). The v0.10.4 fix tightened ADVISES_RE to
require "advisor" rooting to avoid false positives from investors. Need
a tighter signal that distinguishes "advisor on board" from "investor on
board" — likely an advisor-role page prior plus verb-pattern combinations.
**Threshold:** Cat 2 rich-prose type accuracy > 92% (currently 88.5%).
### v0.10.4: gbrain alias resolution feature (driven by Cat 3)
**What:** Add an alias table to gbrain so "Sarah Chen" / "S. Chen" / "@schen" / "sarah.chen@example.com" resolve to one canonical entity. Schema: `aliases (id, slug, alias_text)` with a unique index. Search blends alias matches into hybrid scoring.
@@ -244,6 +333,31 @@ board" — likely an advisor-role page prior plus verb-pattern combinations.
## P2
### Orchestrator + runner double-write to migrations ledger (deferred from v0.18.2 codex review)
**What:** `src/commands/migrations/v0_18_0.ts:200-208` appends an entry to `~/.gbrain/migrations/completed.jsonl` while `src/commands/apply-migrations.ts:374-386` also appends one for the same orchestrator run. The dedupe guard in `src/core/preferences.ts:120-131` only suppresses duplicate `complete` entries, not `partial` entries. Result: distorted wedge counting (3-consecutive-partials-triggers-wedge logic sees 6 partials when it should see 3).
**Why:** Codex plan-review caught this during PR #356 while verifying the two-migration-systems resume boundary. Not blocking v0.18.2 shipping because it only affects the wedge detection threshold, not correctness of the migration itself.
**Fix:** Pick one writer (prefer `apply-migrations.ts` runner as the single source of truth, remove the orchestrator-side append). Fold into `feat/agent-migration-devex` follow-up PR, which already touches both files for the migrate-command consolidation work.
**Depends on:** v0.18.2 shipped. ✅
### 22K-page resync is 30+ minutes on large brains (deferred from v0.18.2 codex review)
**What:** When a schema migration requires data backfill (e.g., computing `page_id` from `page_slug` across all `files` rows), `src/commands/sync.ts:248-251, 311-337` iterates per-file. None of v0.18.2's hardening work shrinks this path. On a 22K-page brain the resync takes 30+ minutes; at 500K pages it would be several hours.
**Why:** Codex explicitly called out that none of PR #356 or the two follow-up PRs addresses the resync execution model. This is a separate performance-design problem.
**Options to explore:**
- (a) Parallel page import via worker pool (Minions-based).
- (b) Bulk COPY-based import replacing the per-file INSERT.
- (c) Incremental resync that only rewrites changed rows (needs content hash or updated_at gating).
**Priority:** P2 now, upgrade to P1 if another heavy migration ships that needs backfill at this scale.
**Depends on:** v0.18.2 shipped. ✅
### Minions: `gbrain jobs stats --orphaned` (deferred from v0.13.0)
**What:** New CLI flag / output column surfacing jobs that are waiting with no registered handler on any live worker.
@@ -405,3 +519,48 @@ board" — likely an advisor-role page prior plus verb-pattern combinations.
### Implement AWS Signature V4 for S3 storage backend
**Completed:** v0.6.0 (2026-04-10) — replaced with @aws-sdk/client-s3 for proper SigV4 signing.
### Caller-opt-in retry for `executeRaw` (D3 follow-up from v0.22.1)
**What:** Add `PostgresEngine.executeRawIdempotent(sql, params)` (or a `{retry: true}` parameter flag on `executeRaw`) so callers explicitly opt into auto-retry for statements they know are idempotent. Audit existing call sites and migrate the read-only ones (search, page fetches, etc.) to the new method.
**Why:** Closes the gap left by D3's drop-the-wrapper decision in v0.22.1. The original #406 wrapped `executeRaw` in a regex-gated retry that was unsound for writable CTEs and side-effecting SELECTs. Recovery moved up to the supervisor watchdog, but per-call recovery for reads (the bulk of `executeRaw` traffic from MCP, search, page fetches) is gone. A caller-opt-in flag puts the idempotency decision where it belongs (at the call site, with full statement context).
**Pros:** Restores per-call auto-recovery for reads without the phantom-write risk on mutations. Explicit > clever: each call site declares its own idempotency posture. Future caller-added mutations get safe-by-default behavior.
**Cons:** Touches every existing `executeRaw` call site (~25). Requires careful audit — accidentally tagging a mutation as idempotent re-introduces the phantom-write bug.
**Context:** Codex F3 demonstrated that `READ_ONLY_PREFIX = /^(\s|--.*\n)*(SELECT|WITH)\b/i` is unsound — `WITH x AS (UPDATE … RETURNING …) SELECT …` matches the prefix but updates a row; `SELECT pg_advisory_xact_lock(...)` is a SELECT with side effects. The plan-eng-review wrap-up in `~/.claude/plans/system-instruction-you-are-working-tender-horizon.md` has the full discussion.
**Effort estimate:** M (human: ~1 day / CC: ~30 min including call-site audit).
**Priority:** P2 — current behavior (no retry, supervisor recovers within ~3 min) is acceptable but per-call recovery is a real ergonomic win.
**Depends on:** Nothing.
### Replace `walkMarkdownFiles` with `engine.getAllSlugs()` in `extractForSlugs` (F1 follow-up from v0.22.1)
**What:** The cycle path's `extractForSlugs()` at `src/commands/extract.ts:455` still does a `walkMarkdownFiles(brainDir)` to build the `allSlugs` set for link resolution. On a 54K-page brain that's a single `readdir` traversal (~hundreds of ms — acceptable, dominated by the file-content-read elimination from #417). But `engine.getAllSlugs()` exists at `extract.ts:728` and produces the same set via a single SQL query (~tens of ms).
**Why:** Eliminates the residual directory walk on every cycle. Codex F1 noted that the v0.22.1 plan's "cycle never re-walks the whole tree again" claim was overstated — it stops READING file contents but still walks the directory. This TODO closes that gap honestly.
**Pros:** Cycle becomes O(slugs sync touched), not O(total brain size). No more readdir on a growing brain. ~5 LOC change.
**Cons:** Crosses an FS-vs-DB consistency boundary in the FS-source extract path. Edge case: a file deleted from disk but still in DB. Currently `extractForSlugs` skips with `if (!existsSync(fullPath)) continue` — unchanged. But if a markdown file references a slug whose page exists in DB but file was deleted, the link would resolve via DB but the original extractor caught it. Needs a careful test for this case.
**Context:** Codex plan-review during v0.22.1 wrap, verified at `extract.ts:455-456`. The plan-eng-review session captured the rationale.
**Effort estimate:** S (human: ~2 hr / CC: ~10 min including the consistency-edge-case test).
**Priority:** P3 — pure perf, no correctness gap.
**Depends on:** Nothing.
### `err.code`-based connection-error matching in `postgres-engine.ts` (B1 follow-up from v0.22.1)
**What:** The CONNECTION_ERROR_PATTERNS array (~12 strings: `ECONNREFUSED`, `connection terminated`, `password authentication failed`, etc.) matched against `err.message` and `err.code`. Replace with structured matching against `err.code` only, using postgres.js's typed error classes (`PostgresError` with structured codes).
**Why:** String matching against error messages breaks on library upgrades (postgres.js could change its error message phrasing without bumping major). Code matching is durable. The Layer 1 cleanup follows: gbrain itself doesn't define connection-error codes; it should defer to postgres.js's classification.
**Pros:** More durable across library updates. Less code (drop the 12-string array). Follows the typed-errors pattern v0.21.0 introduced (`src/core/errors.ts`).
**Cons:** Requires verifying which `err.code` values postgres.js actually exposes for each connection-failure mode. May need fallback to message-substring matching for codes that postgres.js doesn't surface.
**Context:** Section 2/B1 from the v0.22.1 plan-eng-review. After D3 dropped the per-call retry, `isConnectionError` is no longer in the hot path — only the supervisor watchdog cares about classifying connection errors, and it currently catches *anything*. This TODO is a cleanup pass when someone next touches that surface.
**Effort estimate:** S (human: ~2 hr / CC: ~10 min).
**Priority:** P3.
**Depends on:** The above caller-opt-in retry (#1) is the natural co-lander since both touch the same error-classification surface.
+1 -1
View File
@@ -1 +1 @@
0.17.0
0.22.5
+9
View File
@@ -7,6 +7,7 @@
"dependencies": {
"@anthropic-ai/sdk": "^0.30.0",
"@aws-sdk/client-s3": "^3.1028.0",
"@dqbd/tiktoken": "^1.0.22",
"@electric-sql/pglite": "0.4.3",
"@modelcontextprotocol/sdk": "^1.0.0",
"gray-matter": "^4.0.3",
@@ -14,6 +15,8 @@
"openai": "^4.0.0",
"pgvector": "^0.2.0",
"postgres": "^3.4.0",
"tree-sitter-wasms": "0.1.13",
"web-tree-sitter": "0.22.6",
},
"devDependencies": {
"@types/bun": "latest",
@@ -107,6 +110,8 @@
"@aws/lambda-invoke-store": ["@aws/lambda-invoke-store@0.2.4", "", {}, "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ=="],
"@dqbd/tiktoken": ["@dqbd/tiktoken@1.0.22", "", {}, "sha512-RYhO8xeHkMNX5Ixqf4M1Ve3siCYJY/dI0yLnlX4M4oIEDOvjMIQ+E+3OUpAaZcWTaMtQJzGcDAghYfllpx3i/w=="],
"@electric-sql/pglite": ["@electric-sql/pglite@0.4.3", "", {}, "sha512-ichuWTgtd4mOM1G4SpyGJa5trT03lWbMypDV0fUXUCXg5hiHqVAz/bZyV68NqmkLB7WcYmj1RMJVSp8HV/v/ZQ=="],
"@hono/node-server": ["@hono/node-server@1.19.12", "", { "peerDependencies": { "hono": "^4" } }, "sha512-txsUW4SQ1iilgE0l9/e9VQWmELXifEFvmdA1j6WFh/aFPj99hIntrSsq/if0UWyGVkmrRPKA1wCeP+UCr1B9Uw=="],
@@ -453,6 +458,8 @@
"tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],
"tree-sitter-wasms": ["tree-sitter-wasms@0.1.13", "", { "dependencies": { "tree-sitter-wasms": "^0.1.11" } }, "sha512-wT+cR6DwaIz80/vho3AvSF0N4txuNx/5bcRKoXouOfClpxh/qqrF4URNLQXbbt8MaAxeksZcZd1j8gcGjc+QxQ=="],
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"type-is": ["type-is@2.0.1", "", { "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw=="],
@@ -467,6 +474,8 @@
"web-streams-polyfill": ["web-streams-polyfill@4.0.0-beta.3", "", {}, "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug=="],
"web-tree-sitter": ["web-tree-sitter@0.22.6", "", {}, "sha512-hS87TH71Zd6mGAmYCvlgxeGDjqd9GTeqXNqTT+u0Gs51uIozNIaaq/kUAbV/Zf56jb2ZOyG8BxZs2GG9wbLi6Q=="],
"webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="],
"whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="],
+6
View File
@@ -3,4 +3,10 @@
# Default 5s is too short when many test files boot PGLite instances at once.
# 60s is the empirical ceiling we observed before the first file's beforeAll
# completed on a loaded machine.
#
# NOTE: this bunfig.toml `timeout` key is read by `bun test` but empirically
# does NOT apply to beforeEach/afterEach hook timeouts under `bun run test`
# chained behind `bun run typecheck`. The test script in package.json passes
# `--timeout=60000` explicitly to cover both per-test and per-hook timeouts.
# Leaving both in place as belt-and-suspenders.
timeout = 60_000
+69
View File
@@ -458,6 +458,75 @@ in depth, not the primary boundary.
---
## v0.22.4 — frontmatter-guard adoption
### 1. Stop hand-rolling frontmatter validators
If your fork has scripts that call `js-yaml` directly to validate brain page
frontmatter, replace them with `gbrain frontmatter validate` calls. The CLI
covers the seven canonical error classes and ships a `--json` envelope that's
stable across releases.
```diff
- # Custom validator script
- node scripts/validate-frontmatter.mjs <path>
+ gbrain frontmatter validate <path> --json
```
For consumers that need the validator inside another script, import from
gbrain's `markdown` export instead of duplicating logic:
```ts
import { parseMarkdown } from 'gbrain/markdown';
const parsed = parseMarkdown(content, filePath, { validate: true, expectedSlug });
for (const err of parsed.errors ?? []) {
// err.code: MISSING_OPEN | MISSING_CLOSE | YAML_PARSE | SLUG_MISMATCH |
// NULL_BYTES | NESTED_QUOTES | EMPTY_FRONTMATTER
}
```
### 2. Drop any references to `lib/brain-writer.mjs`
If your fork's skills or scripts referenced an aspirational
`lib/brain-writer.mjs` (it never shipped — the spec was in PR #392 and never
landed), replace those references with the gbrain CLI. The `frontmatter-guard`
skill lives at `skills/frontmatter-guard/SKILL.md` and points at
`gbrain frontmatter validate` / `audit` / `install-hook`.
### 3. Wire the doctor subcheck into your health pipeline
`gbrain doctor` now reports `frontmatter_integrity` automatically. If your
fork has a custom health pipeline (e.g. a daily Slack post about brain
health), pull from `gbrain doctor --json` and surface the
`frontmatter_integrity` row counts.
### 4. (Optional) Install the pre-commit hook on brain repos
For sources backed by git, the v0.22.4 install-hook helper drops a
pre-commit script that blocks commits with malformed frontmatter:
```bash
gbrain frontmatter install-hook
```
Skip this if your brain isn't a git repo or if your downstream agent already
enforces validation at write time. See `docs/integrations/pre-commit.md` for
the full recipe.
### 5. Migration ergonomics — read pending-host-work.jsonl
After `gbrain apply-migrations --yes` runs the v0.22.4 audit, your agent
should read `~/.gbrain/migrations/pending-host-work.jsonl` (filter to
`migration === "0.22.4"`) and walk each entry's `command` field. Each entry
points to a per-source `gbrain frontmatter validate <source_path> --fix`
command — surface counts to the user, get explicit consent, then run.
The migration is **audit-only**. It never mutates brain content during
`apply-migrations`. Your agent runs the fix command with user consent.
---
## Future versions
When gbrain ships a new version, this doc will be updated with the diffs for that
-286
View File
@@ -1,286 +0,0 @@
# BrainBench v1 — 2026-04-18
**Branch:** `garrytan/link-timeline-extract`
**PR:** #188
**Engine:** PGLite (in-memory)
**Reproducibility:** `bun run eval/runner/all.ts` — no API keys, no network, ~3 min
## TL;DR
PR #188 ships a self-wiring knowledge graph layer for gbrain (auto-link on
every page write, typed extraction, traversal queries, backlink-boosted search).
This benchmark measures the actual end-to-end value vs gbrain pre-PR-#188 on a
240-page rich-prose corpus generated by Claude Opus.
**Every headline metric goes UP. No category goes down.**
| Metric | BEFORE PR #188 | AFTER PR #188 | Δ |
|---------------------|----------------|---------------|--------------|
| **Precision@5** | 39.2% | **44.7%** | **+5.4 pts** |
| **Recall@5** | 83.1% | **94.6%** | **+11.5 pts**|
| Correct in top-5 | 217 | 247 | **+30** |
Plus seven categories of orthogonal capability checks (identity resolution,
temporal queries, performance, robustness, MCP contract) all passing.
## What this benchmark proves
BrainBench v1 evaluates gbrain end-to-end across capability domains the existing
test suite doesn't cover at scale. Headline is a single before/after comparison:
**pre-PR-#188 (no graph layer)** vs **the full v0.10.3 + v0.10.4 stack**, run on
the same 240-page corpus with the same relational queries.
Why before/after instead of just "after numbers": because gbrain pre-PR-#188 was
already a working brain — keyword search, hybrid retrieval, structured timeline
ops. The graph layer is an additive change. The right question is "did it
actually make the brain better at relational questions?" not "is it good in
isolation."
## The corpus
240 rich-prose pages generated by Claude Opus 4.7:
- 80 people (40 founders, 20 partners, 10 engineers, 10 advisors)
- 80 companies (60 startups, 15 VCs, 5 acquirers)
- 50 meetings (15 demo days, 25 1:1s, 10 board meetings)
- 30 concepts (frameworks, theses, hot spaces)
Each page is multi-paragraph narrative prose with realistic noise:
- Varied phrasings (founders described 6 different ways, investors 8 different ways)
- Natural typos ~1-2% of words ("intrest", "comercial", "differnt")
- Cross-references via `[Name](slug)` markdown links AND bare slug references
- Multi-year timelines spanning 2021-2026
- Multiple personas (terse note-taker, prose-heavy journaler, voice-to-text dump)
Generation cost: ~$15 of Opus tokens, one-time, cached to `eval/data/world-v1/`
and committed to the repo. Subsequent runs read the cache.
This is intentionally messier than templated benchmarks. The point is to surface
behavior under realistic load, not to confirm the algorithm works on clean inputs.
## Headline: relational queries on the rich corpus
196 relational queries derived from the world facts:
- "Who attended `Demo Day W30`?" (60 queries)
- "Who works at `Acme`?" (60 queries)
- "Who invested in `Beta Health`?" (45 queries)
- "Who advises `Cipher Labs`?" (31 queries)
Configurations compared:
- **BEFORE PR #188:** vanilla v0.10.0 — no auto-link, no `extract --source db`,
no `traversePaths`. Agent answers relational questions by grepping the corpus
(the realistic fallback for a pre-graph brain).
- **AFTER PR #188:** full graph layer. Agent uses `gbrain graph-query` first
(high-precision typed traversal), grep fallback when graph returns nothing.
### Top-K (what agents actually read)
Agents read ranked top-K results, not full sets. AFTER ranks graph hits FIRST
(high precision), then fills with grep results.
| Metric | BEFORE | AFTER | Δ |
|---------------------|--------|--------|---------------|
| **Precision@5** | 39.2% | 44.7% | **+5.4 pts** |
| **Recall@5** | 83.1% | 94.6% | **+11.5 pts** |
| Correct in top-5 | 217 | 247 | **+30** |
Recall@5 jumps 11.5 points because graph hits are exact-typed answers placed
at the top of results — agents find what they need in their first reads
instead of digging through grep noise.
### Set-based metrics + graph-only ablation
| Metric | BEFORE (grep) | AFTER (hybrid) | Graph-only (ablation) |
|---------------------|---------------|----------------|------------------------|
| **F1 score** | 57.8% | 57.8% | **86.6%** |
| Set precision | 40.8% | 40.8% | **81.0%** |
| Set recall | 98.9% | 98.9% | 93.1% |
| Total returned | 632 | 632 | 300 (-53%) |
| Correct returned | 258 | 258 | 243 |
AFTER (hybrid) matches BEFORE on full-set metrics because graph hits are a
subset of grep hits — taking the union doesn't add or remove anything from the
bag. **What changes is which results appear FIRST.** Top-K captures that;
raw set recall doesn't.
The **graph-only** column is the most important number in the report. It shows
where the graph alone is heading: **86.6% F1 vs grep's 57.8% (+28.8 pts)**.
Almost twice the precision (81% vs 41%) at 94% of the recall, with HALF the
results to read.
### Per-link-type breakdown
| Link type | Expected | Graph found / returned | Recall | Precision |
|-------------|----------|------------------------|--------|-----------|
| attended | 134 | 131 / 134 | 97.8% | 97.8% |
| works_at | 50 | 50 / 79 | 100.0% | 63.3% |
| invested_in | 60 | 50 / 56 | 83.3% | 89.3% |
| advises | 17 | 12 / 31 | 70.6% | 38.7% |
Where the graph wins biggest: **incoming relationship queries on companies**.
"Who works at Acme?" — grep returns every page mentioning Acme (founders,
investors, advisors, concept pages, other companies that mention it). Graph
returns just employees with the typed `works_at` link.
## How we got here: bugs surfaced, fixes shipped
The benchmark wasn't passive — it caught real bugs in the same PR that ships
the graph layer. Each fix landed in a labeled commit:
### Bug 1: Code fence leak in `extractPageLinks`
**Found:** Category 10 (Robustness) — adversarial test cases included pages with
slug-like strings inside ` ``` ` code blocks. Extraction was treating them as
real entity references.
**Fix:** `stripCodeBlocks()` helper preserves byte offsets but blanks out
fenced and inline code before regex matching. Code fence leak rate now 0%.
### Bug 2: `add_timeline_entry` accepted year 99999
**Found:** Category 12 (MCP Contract) — boundary input fuzzing.
**Fix:** Strict YYYY-MM-DD regex with year clamped 1900-2199, round-trip parse
to catch e.g. Feb 30. Rejects with clear error message.
### Bug 3: `inferLinkType` mis-classified investments as `mentions`
**Found:** Rich-prose corpus showed `invested_in` had **0% type accuracy**
60/60 found links classified as `mentions`. Templated tests didn't surface this
because the templated prose used "invested in" verbatim while LLM prose uses
"led the Series A", "early investor", "portfolio includes", etc.
**Fix:** Five-part patch:
1. `INVESTED_RE` extended with narrative verbs LLMs actually use
2. `ADVISES_RE` tightened to require explicit advisor rooting (not generic "board")
3. Context window 80→240 chars (catches verbs at sentence distance)
4. Person-page role prior — partner-bio language → `invested_in` for company refs
5. Cascade reorder — `invested_in` checked before `advises`
Type accuracy: **70.7% → 88.5% (+18 pts)**. invested_in: **0% → 91.7%**.
### Bug 4: Founder bios mis-classified as `invested_in`
**Found:** Diagnostic on rich corpus showed founder pages like "Carol Wilson is
the founder of [Anchor]" were getting `invested_in` (because the role prior
fired and `FOUNDED_RE` only matched the verb form "founded", missing the noun
form "founder of").
**Fix:** Extended `FOUNDED_RE` with "founder of", "founders include", "the
founder", etc. Carol's link now correctly types as `founded`. Combined with
relaxing the "who works at X?" query to accept `works_at` OR `founded` (founders
are employees by definition), this drove the recall jump from 53.8% → 93.1%.
## Other categories (orthogonal capability checks)
Five additional categories run as part of `bun run eval/runner/all.ts`. All pass.
### Category 3: Identity Resolution
Tests whether gbrain can resolve aliases ("Sarah Chen", "S. Chen", "@schen",
"sarah.chen@example.com") to one canonical entity. 100 entities × 8 alias types
= 800 queries.
| Alias category | Recall (top-10) |
|----------------|-----------------|
| Documented (in canonical body) | 100.0% |
| Undocumented (initials, typos) | 31.0% |
Honest baseline: gbrain has no alias table today. Documented aliases work via
keyword search. Undocumented aliases need v0.10.4 alias-table feature
(documented in TODOS.md).
### Category 4: Temporal Queries
50 entities × 10-20 dated events spanning 5 years. Tests point queries, range
queries, recency, and as-of queries.
| Sub-category | Recall | Precision |
|-----------------|--------|-----------|
| Point | 100% | 100% |
| Range | 100% | 100% |
| Recency (top-3) | 100% | — |
| As-of | 100% | — |
Structured `timeline_entries` table answers all four query types correctly via
manual filter+sort logic. Note: there's no native `getStateAtTime` op — the
as-of queries were resolved by the agent in app code. Native op deferred to v0.10.5.
### Category 7: Performance / Latency
Procedural data at 1K and 10K page scales on PGLite (in-memory). All read ops
sub-millisecond. Bulk import at 5,800 pages/sec.
| Op | 1K P50 | 1K P95 | 10K P50 | 10K P95 |
|--------------------|---------|---------|---------|----------|
| get_page | 0.08ms | 0.12ms | 0.08ms | 0.15ms |
| search_keyword | 0.19ms | 0.52ms | 0.20ms | 0.59ms |
| traverse_paths d=2 | 10.1ms | 12.6ms | 91.4ms | 176.4ms |
| putPage_single | 0.12ms | 0.20ms | 0.12ms | 0.42ms |
Bulk throughput: import 5,848 pages/sec, addLink 8,752 links/sec at 10K scale.
P95 search latency well under the 200ms threshold.
### Category 10: Robustness / Adversarial
22 hand-crafted edge cases × 6 ops each = 133 attempts. Tests empty pages,
100K-character pages, CJK/Arabic/Cyrillic/emoji, code fences, false-positive
substrings, malformed timeline, deeply nested markdown, slugs with edge characters.
**Result: 133/133 ops succeeded, 0 crashes, 0 silent corruption.**
### Category 12: MCP Operation Contract
50 contract tests across trust boundary (local vs remote), input validation
(slug format, date format), SQL injection resistance, resource exhaustion,
depth caps. 30 operations × 5 input variants.
**Result: 50/50 pass.** Verifies the v0.10.3 security hardening (depth caps,
remote auto-link disable, file_upload path confinement, parameterized queries).
## Reproducibility
```bash
bun run eval/runner/all.ts
```
In-memory PGLite, no API keys, no network. ~3 minutes wall time. Same numbers
every run (within deterministic-seed tolerance).
To regenerate the rich-prose corpus from scratch (~$15 Opus spend):
```bash
bun eval/generators/gen.ts --max 240 --concurrency 6
```
Generated outputs are cached in `eval/data/world-v1/` and committed to the repo,
so the regen pass is one-time. Subsequent runs use the cache.
## What this benchmark deliberately doesn't test (BrainBench v1.1, see TODOS.md)
- **Cat 5: Source attribution / provenance** — needs ~$200-300 Opus for a
conflict-graph corpus
- **Cat 6: Auto-link precision under prose at scale** — needs 5K+ adversarial
prose pages
- **Cat 8: Skill behavior compliance** — needs LLM agent loop (~$2K to run)
- **Cat 9: End-to-end workflows** — needs LLM agent loop (~$1K)
- **Cat 11: Multi-modal ingestion** — needs licensed real datasets
These five are tracked in `TODOS.md` with budget estimates and depend-on chains.
## Methodology notes
- **Synthetic data, not private brain.** All 240 pages are fictional. Generated
by Opus from procedural skeletons in `eval/generators/world.ts`. Reproducibility
matters more than realism for a benchmark you can publish.
- **Two configurations, one corpus.** BEFORE and AFTER run against identical
data. The only diff is the codepath (whether the agent has the graph layer
available). No corpus tuning per configuration.
- **No cherry-picking.** Queries are derived programmatically from world facts —
every entity that has facts produces queries. No hand-selected "easy wins."
- **Honest about limitations.** The 5.8pt set-recall gap (graph 93.1% vs grep
98.9%) comes from Opus paraphrasing names without markdown links ("Mark Thomas
was there" instead of `[Mark Thomas](slug)`). Closing this needs corpus-aware
NER, deferred to v0.10.5.
- **Single-shot benchmarks are fragile** — but every run is reproducible and
this is a checkpoint, not the final measure. v1.1 will add the LLM-agent-loop
categories that capture more of the realistic agent workflow.
@@ -1,126 +0,0 @@
# Production Benchmark: Minions vs OpenClaw Sub-agents (Real Deployment)
**Date:** 2026-04-18
**Environment:** Garry's OpenClaw on Render (ephemeral container, Supabase Postgres)
**GBrain:** v0.11.0 (minions-jobs branch)
**OpenClaw:** 2026.4.10
**Brain:** 45,798 pages, 98K chunks, 25K links, 79K timeline entries
**Task:** Pull and ingest one month of social posts from an external API into the brain
## Context
This is a **production benchmark**, not a lab test. The existing lab benchmark
([2026-04-18-minions-vs-openclaw-subagents.md](2026-04-18-minions-vs-openclaw-subagents.md))
uses trivial prompts on localhost Postgres. This benchmark uses a real 45K-page
brain on Supabase, pulling real social posts from an external API, and writing
real brain pages.
## The Task
Pull a month (May 2020) of my social posts from an external API, parse them
into a structured brain page with frontmatter, engagement metrics, and
links, commit to the brain repo, and submit a sync job to gbrain.
## Method 1: Minions (deterministic pipeline)
```bash
# 1. Pull posts from the external API (curl → JSON)
curl -s -H "Authorization: Bearer $API_BEARER_TOKEN" \
"$SOCIAL_API_URL?from=my_account&start=2020-05-01&end=2020-06-01" \
> /tmp/bench-posts.json
# 2. Parse + write brain page (python)
python3 parse_and_write.py
# 3. Git commit
cd /data/brain && git add media/social/2020-05.md && git commit -m "archive: 2020-05"
# 4. Submit sync to Minions
gbrain jobs submit sync --params '{"repo":"/data/brain","noPull":true}'
```
**Result: 753ms total.** 99 posts pulled, page written, committed, sync job queued.
Breakdown:
- External API call: ~300ms
- Python parse + write: ~50ms
- Git commit: ~100ms
- gbrain jobs submit: ~300ms
Cost: $0.00 (no LLM tokens)
## Method 2: OpenClaw Sub-agent (sessions_spawn)
```javascript
sessions_spawn({
task: "Pull my social posts for June 2020 and save as a brain page...",
model: "anthropic/claude-sonnet-4-20250514",
mode: "run",
runTimeoutSeconds: 120
})
```
**Result: GATEWAY TIMEOUT (>10,000ms).** The sub-agent could not even spawn
within the 10-second gateway timeout. On a production Render container running
a 45K-page brain with 19 active cron jobs, the gateway is under enough load
that sub-agent spawning is unreliable.
When sub-agents DO successfully spawn (off-peak), the expected path is:
1. Gateway receives spawn request (~500ms)
2. Create session, load context (~2-3s) — AGENTS.md, SOUL.md, skills, memory
3. Model reads task, plans approach (~2-3s)
4. Model calls `exec` tool for curl (~1s)
5. Model calls `exec` tool for python (~1s)
6. Model calls `exec` tool for git (~1s)
7. Model reports result (~1s)
**Estimated: 10-15s + ~$0.03 in tokens per invocation**
## Comparison
| Metric | Minions | Sub-agent |
|--------|---------|-----------|
| **Wall time** | **753ms** | **>10,000ms** (gateway timeout) |
| **Token cost** | $0.00 | ~$0.03 per run |
| **Success rate** | 100% | 0% (timeout on first attempt) |
| **Survives restart** | Yes (Postgres) | No (dies with process) |
| **Progress tracking** | `gbrain jobs get <id>` | poll sessions_list |
| **Auto-retry** | 3 attempts, exponential backoff | manual re-spawn |
| **Concurrency** | FOR UPDATE SKIP LOCKED | hope-based maxConcurrent |
| **Steerable** | inbox messages | fire and forget |
| **Results persisted** | job record | lost on compaction |
| **Memory** | ~2MB per in-flight job | ~80MB per spawned session |
## The Scaling Story
We pulled 19,240 posts across 36 months (2021-2023) using the Minions
approach in a single bash loop. Total time: ~15 minutes. Cost: $0.00 in
LLM tokens.
The same task via sub-agents would require 36 spawns × ~$0.03 = ~$1.08
in tokens, take 36 × 15s = 9 minutes best-case, and fail on ~40% of
spawns under load (per the fan-out benchmark).
At scale (100+ months of backfill, or 1000+ batch enrichment jobs),
Minions is the only viable path. Sub-agents hit the gateway timeout wall,
burn tokens on deterministic work, and provide no durability.
## When Sub-agents Still Win
Sub-agents are correct for **judgment work**:
- Email triage (LLM decides priority, drafts reply)
- Social radar (LLM assesses severity, decides to alert)
- Meeting prep (LLM synthesizes brain pages into briefing)
- Cold email research (LLM decides notability)
These tasks require an LLM to make decisions. Minions can't do that —
its handlers are code, not models. The routing rule:
> **Deterministic** (same input → same steps → same output) → **Minions**
> **Judgment** (input requires assessment/decision) → **Sub-agents**
## One-Line Summary
Minions completed a production post-ingest pipeline in 753ms for $0.
Sub-agents couldn't even spawn. For deterministic brain-write work,
Minions is not incrementally better — it's categorically different.
@@ -1,203 +0,0 @@
# Minions vs OpenClaw Subagents Benchmark
**Date:** 2026-04-18
**Branch:** garrytan/minions-jobs
**Suite:** `test/e2e/bench-vs-openclaw/`
**Minions:** v0.11.0 (PR #130)
**OpenClaw:** 2026.4.10 (44e5b62)
**Model:** anthropic/claude-haiku-4-5
## Why this benchmark exists
Minions is GBrain's new background job queue, pitched as a durable, cheap
substitute for spawning OpenClaw subagents via `openclaw agent --local`.
"Durable" and "cheap" are easy to claim and hard to prove. So we put
numbers on four specific claims a Minions user would actually care about:
1. **Durability** — when the orchestrator crashes mid-dispatch, does the
in-flight work survive?
2. **Throughput** — how much wall-clock overhead does each system add on
top of the underlying LLM call?
3. **Fan-out** — parent dispatches 10 children in parallel. How fast and
how reliable is each side?
4. **Memory** — what does it cost to keep 10 subagents in flight at once?
Methodology: both sides call the **same** LLM
(`anthropic/claude-haiku-4-5`) with the **same** trivial prompt
(`"Reply with just: OK. No other text."`). The delta is the
queue+dispatch+process-cost on top of identical LLM work.
## Honest caveats up front
- **We do NOT benchmark OpenClaw's gateway multi-agent fan-out.** That
requires a custom WebSocket client + an LLM-backed parent agent, ~5×
the complexity of this harness. We benchmark `openclaw agent --local`
(embedded mode) because that's what users actually script against
today when they want "run an agent and get a reply back."
- **All numbers are point measurements on Garry's laptop** (macOS, Apple
Silicon, local Postgres 16 + pgvector in Docker). Not a cluster
benchmark. Not an adversarial load test. Reproducible via the files
in `test/e2e/bench-vs-openclaw/`.
- **OpenClaw `--local` is a fire-and-forget process.** If you SIGKILL
it mid-dispatch, the reply is gone. This isn't a bug, it's the design.
What we're measuring is how much that design choice costs users who
need durability.
- **Small sample sizes** (10 jobs × 3 runs for fan-out, 20 serial for
throughput, 10 in-flight for memory). Enough to show order-of-magnitude
deltas, not enough to prove tight tails.
## Results
### 1. Durability (SIGKILL mid-flight, 10 jobs)
| System | Delivered | Wall time | p50 per job | p95 per job |
|--------|-----------|-----------|-------------|-------------|
| **Minions** | **10 / 10** | 458ms total | 257ms | 410ms |
| OpenClaw `--local` | **0 / 10** | 22989ms (all SIGKILLed at 500ms) | n/a | n/a |
Setup: Minions side seeds 10 jobs in state `active` with an expired
`lock_until` (exactly the state a SIGKILLed worker leaves behind). A
rescue worker starts. It picks up all 10 via `handleStalled` and
completes them.
OpenClaw side spawns 10 `openclaw agent --local` processes in parallel
and SIGKILLs each at 500ms. Zero of them managed to emit any output
before being killed.
**The number that matters: Minions rescued 10 out of 10 stranded
jobs in under half a second.** OpenClaw has no persistence layer, so
anything in flight when the process dies is lost. Users can retry by
re-running the prompt, but the context is gone — they're starting over.
Source: `test/e2e/bench-vs-openclaw/durability.bench.ts`
### 2. Throughput (20 serial dispatches, same LLM call)
| System | p50 | p95 | p99 | Mean | Min | Max | Success |
|--------|-----|-----|-----|------|-----|-----|---------|
| **Minions** | **778ms** | **1931ms** | **1931ms** | **911ms** | 639ms | 1931ms | 20/20 |
| OpenClaw `--local` | 8086ms | 10094ms | 10094ms | 8335ms | 7405ms | 10094ms | 20/20 |
| **Ratio** | **10.4×** | **5.2×** | **5.2×** | **9.2×** | 11.6× | 5.2× | — |
Setup: both sides call claude-haiku-4-5 with the same prompt. Minions
goes through `queue.add` → worker claims → handler calls Anthropic SDK
directly. OpenClaw spawns a fresh `openclaw agent --local` process per
dispatch.
The ~7 seconds of overhead per OC dispatch isn't the LLM. It's the
process boot: loading the agent runtime, auth, plugins, MCP servers.
Every dispatch pays that cost again. The Minions worker stays warm, so
the overhead is `add` + `claim` + returning the result — roughly 100ms
on top of the LLM latency itself.
Source: `test/e2e/bench-vs-openclaw/throughput.bench.ts`
### 3. Fan-out (3 runs × 10 children in parallel)
| System | Completed | Mean wall time | Runs (ok/N) | Wall times (ms) |
|--------|-----------|----------------|-------------|-----------------|
| **Minions** (concurrency=10) | **30 / 30** | **1090ms** | 10/10, 10/10, 10/10 | 890, 1135, 1245 |
| OpenClaw (10 parallel spawns) | 17 / 30 | 22598ms | 6/10, 5/10, 6/10 | 22204, 22505, 23084 |
| **Ratio (wall time)** | — | **~21×** | — | — |
Setup: parent dispatches 10 children concurrently, waits for all.
Minions uses one worker process with `concurrency=10`. OpenClaw scripts
10 parallel `openclaw agent --local` spawns — what a user would do today
without Minions.
Two findings, not one:
1. **Wall time: Minions completes 10 in ~1 second. OC parallel spawn
takes ~22 seconds.** The gap scales with the warmup cost: one warm
worker amortizes, 10 cold processes pay the bill 10 times.
2. **OC parallel spawn fails 43% of the time at 10-wide.** Error
samples show a mix of LLM rate-limit hits and spawn saturation. We
didn't tune this. That's the point — a user who tries to fan out with
`--local` without a queue runs into this with no obvious remediation.
Source: `test/e2e/bench-vs-openclaw/fanout.bench.ts`
### 4. Memory (10 in-flight subagents)
| System | Baseline RSS | Peak with 10 in flight | Delta | Processes |
|--------|--------------|------------------------|-------|-----------|
| **Minions** | 84 MB | **86 MB** | **+2 MB** | 1 |
| OpenClaw | n/a | 814 MB (summed across 10) | — | 10 |
| **Ratio** | — | **~407×** | — | — |
Setup: both sides keep 10 subagents in flight simultaneously. Minions
side uses one worker with concurrency=10 and handlers that park on a
Promise. OpenClaw side spawns 10 parallel `openclaw agent --local`
processes and sums their RSS via `ps -o rss=`.
Handlers are intentionally cheap sleeps — we measure harness memory,
not LLM client state. The LLM client state would be comparable on both
sides.
**Minions costs 2 MB to keep 10 subagents in flight. OpenClaw costs
814 MB. At scale, this difference decides whether you can run 10
subagents or 100 on the same machine.**
Source: `test/e2e/bench-vs-openclaw/memory.bench.ts`
## What this means for a Minions user
If you have a script today that spawns `openclaw agent --local` N times,
every one of these numbers gets better when you move to Minions:
- **Crash and your work doesn't vanish.** Worker dies, PG keeps the
row, another worker picks it up. Zero extra code on your side.
- **Per-dispatch wall time drops ~10×** because the worker stays warm.
Process startup is where your time was going, not the LLM.
- **Fan-out scales past 10-wide without you hand-tuning concurrency.**
Worker does the throttling; the queue does the durability. OC
parallel spawn hits a 40% failure wall around 10-wide on this hardware.
- **Memory stops being the bottleneck.** 2 MB per in-flight job vs
~80 MB per process changes what "10 concurrent subagents" costs you
on a box.
## What this doesn't say
- We didn't test OpenClaw's gateway multi-agent mode. If you run the
gateway, you get persistent agent state across turns, real multi-agent
routing, and different cost characteristics. The gateway is OC's
production mode, and we're not claiming Minions beats it at what it
does. We're saying: if your pattern is "dispatch a subagent, get a
reply, maybe do this 10 times," the `--local` CLI is what you're
reaching for, and Minions beats it by ~10-400× depending on the axis.
- We didn't run under load (100s of concurrent jobs, hours of sustained
work). These are observational point measurements, not a stress test.
- We ran claude-haiku-4-5. For slower/larger models the absolute
numbers shift but the ratios stay roughly the same — the overhead
is process boot and persistence, not model size.
## Reproducing
```bash
# 1. Start a test Postgres
docker run -d --name gbrain-test-pg \
-e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres \
-e POSTGRES_DB=gbrain_test \
-p 5436:5432 pgvector/pgvector:pg16
# 2. Set env
export DATABASE_URL=postgresql://postgres:postgres@localhost:5436/gbrain_test
export ANTHROPIC_API_KEY=sk-ant-...
# 3. Run each bench (durability + memory are free; throughput + fan-out
# cost ~$0.25 in claude-haiku-4-5 tokens total)
bun test ./test/e2e/bench-vs-openclaw/durability.bench.ts
bun test ./test/e2e/bench-vs-openclaw/throughput.bench.ts
bun test ./test/e2e/bench-vs-openclaw/fanout.bench.ts
bun test ./test/e2e/bench-vs-openclaw/memory.bench.ts
# 4. Tear down
docker stop gbrain-test-pg && docker rm gbrain-test-pg
```
## One-line summary
Minions rescues 10/10 jobs from a crash in under half a second while
OpenClaw `--local` loses all of them; it delivers each dispatch ~10×
faster, fans out 10-wide in ~1 second vs ~22 seconds at 43% OC failure
rate, and holds 10 in-flight subagents in 2 MB vs 814 MB.
@@ -1,176 +0,0 @@
# Tweet Ingestion Benchmark: Minions vs OpenClaw Sub-agents
**Date:** 2026-04-18
**Branch:** garrytan/minions-jobs
**Suite:** `test/e2e/bench-vs-openclaw/tweet-ingest.bench.ts`
**Minions:** v0.11.0 (PR #130)
**OpenClaw:** 2026.4.10
**Model:** none (Minions) vs anthropic/claude-sonnet-4 (OpenClaw)
## Why this benchmark exists
The existing throughput/fanout/durability benchmarks use a trivial LLM
prompt ("Reply with just: OK"). They measure queue overhead, not real work.
This benchmark measures a **real production task**: pull a month of tweets
from the X API, parse them into a structured brain page, git commit, and
sync to gbrain. This is work that an agent does every day. It's
deterministic — same input always produces the same steps in the same
order. The question: should deterministic brain-write work go through an
LLM (sub-agent) or through code (Minions)?
## Methodology
**Task:** Pull ~100 my social posts for one month from the X full-archive
search API, write a markdown brain page with frontmatter + engagement
metrics + tweet links, git commit, and submit a `gbrain sync` job.
**Minions side:** A TypeScript function that:
1. `fetch()` the X API (one HTTP call)
2. `JSON.parse()``writeFileSync()` the brain page
3. `execSync('git commit')`
4. `queue.add('sync', { repo, noPull: true })`
No LLM involved. The handler is code. Total overhead on top of I/O:
queue add + git commit.
**OpenClaw side:** Spawn `openclaw agent --local` with a task prompt that
describes the same pipeline in English. The model (claude-sonnet-4):
1. Reads the task, plans approach
2. Calls `exec` tool for curl
3. Calls `exec` tool for python (parse + write)
4. Calls `exec` tool for git commit
5. Reports result
Same work, but the model decides each step.
**Runs:** 5 serial per method. Each run uses a different month (2020-07
through 2020-11) to avoid caching effects. Pages are cleaned up after.
**Environment:** Tested on a production Render container (ephemeral, ARM64)
with Supabase Postgres (us-east-1) and a 45K-page brain. Also
reproducible on localhost with Docker Postgres — see instructions below.
## Honest caveats
- **X API latency varies.** The X full-archive search endpoint takes
200-500ms depending on load. Both sides pay this equally. We're
measuring the PIPELINE overhead, not the API.
- **OpenClaw `--local` is not the gateway.** The gateway has persistent
sessions, tool caching, and context reuse. `--local` is the scripted
dispatch path — what you'd use in a cron job or automation script.
That's the apples-to-apples comparison for deterministic work.
- **The sub-agent has to figure out the same pipeline every time.**
That's the core inefficiency: spending tokens for the model to
rediscover steps that never change. With Minions, the steps are code.
- **N=5 is small.** Enough to see the order-of-magnitude delta, not
enough to prove tight tails. Run N=20 for statistical significance.
## Results
### Minions (5 runs, serial)
| Run | Month | Tweets | Wall time | Status |
|-----|-------|--------|-----------|--------|
| 1 | 2020-07 | 99 | 753ms | ✅ |
| 2 | 2020-08 | 87 | 681ms | ✅ |
| 3 | 2020-09 | 92 | 724ms | ✅ |
| 4 | 2020-10 | 78 | 698ms | ✅ |
| 5 | 2020-11 | 103 | 741ms | ✅ |
**Stats:** mean=719ms p50=724ms p95=753ms min=681ms max=753ms
**Success rate:** 5/5 (100%)
**Token cost:** $0.00
### OpenClaw Sub-agent (5 runs, serial)
| Run | Month | Tweets | Wall time | Status |
|-----|-------|--------|-----------|--------|
| 1 | 2020-07 | — | >10,000ms | ❌ gateway timeout |
| 2 | 2020-08 | — | >10,000ms | ❌ gateway timeout |
| 3 | 2020-09 | 99 | 12,340ms | ✅ |
| 4 | 2020-10 | 87 | 11,890ms | ✅ |
| 5 | 2020-11 | 92 | 13,210ms | ✅ |
**Stats (successful only):** mean=12,480ms p50=12,340ms
**Success rate:** 3/5 (60%) — 2 gateway timeouts under production load
**Token cost:** ~$0.03 per successful run × 3 = $0.09
> **Note:** Gateway timeouts occurred because the production OpenClaw
> instance was running 19 active cron jobs + heartbeats. The gateway's
> session spawn queue was saturated. This is a realistic production
> scenario, not an artificial constraint.
### Comparison
| Metric | Minions | OpenClaw Sub-agent | Ratio |
|--------|---------|-------------------|-------|
| **Mean wall time** | **719ms** | **12,480ms** | **17.3×** |
| **p50** | 724ms | 12,340ms | 17.0× |
| **Success rate** | 100% | 60% | — |
| **Token cost per run** | $0.00 | ~$0.03 | ∞ |
| **Survives restart** | ✅ | ❌ | — |
| **Progress tracking** | ✅ `jobs get` | ❌ | — |
| **Auto-retry** | ✅ 3 attempts | ❌ | — |
### At scale: 36-month backfill
We also measured a real backfill: pull 36 months of tweets (2021-2023,
19,240 tweets total) and ingest each month as a brain page.
| Metric | Minions | OpenClaw Sub-agent (est.) |
|--------|---------|--------------------------|
| **Total time** | ~15 min | ~7.5 min (best case) to ∞ (gateway timeouts) |
| **Total cost** | $0.00 | ~$1.08 (36 × $0.03) |
| **Expected failures** | 0 | ~14 (36 × 40% failure rate) |
| **Manual intervention** | None | Re-spawn failed months |
The Minions path completed all 36 months unattended. The sub-agent path
would require monitoring and re-spawning failures.
## The routing insight
This benchmark measures **deterministic work** — work where the steps
never change regardless of input. Pull → parse → write → commit → sync.
The same pipeline every time. Spending $0.03 and 12 seconds for a model
to rediscover these steps is waste.
The routing rule that falls out of this data:
> **Deterministic** (same input → same steps → same output) → **Minions**
> Zero tokens. Sub-second. Durable. Auto-retry.
>
> **Judgment** (input requires assessment/decision) → **Sub-agents**
> Model decides what to do. Worth the token cost.
Examples:
- Tweet ingestion → Minions (always the same pipeline)
- Calendar sync → Minions (always the same pipeline)
- Email triage → Sub-agent (model decides priority + reply)
- Meeting prep → Sub-agent (model synthesizes briefing)
## Reproducing
```bash
# 1. Set environment
export X_BEARER_TOKEN=... # external API bearer token
export DATABASE_URL=postgresql://... # Postgres with gbrain schema v7+
export BRAIN_PATH=/path/to/brain # Git repo with brain pages
export ANTHROPIC_API_KEY=sk-ant-... # For OpenClaw side only
# 2. Run the benchmark
bun test test/e2e/bench-vs-openclaw/tweet-ingest.bench.ts
# 3. Cost: ~$0.15 total (5 OC runs × ~$0.03 each, Minions = $0)
# 4. On localhost without X API: mock the fetch in the test file
# to return a canned JSON response. The benchmark measures
# pipeline overhead, not API latency.
```
## One-line summary
Minions ingests a month of tweets in 719ms for $0 with 100% reliability.
OpenClaw sub-agents take 12.5 seconds, cost $0.03, and fail 40% of the
time under production load. For deterministic brain-write work, Minions
is 17× faster, infinitely cheaper, and categorically more reliable.
@@ -1,190 +0,0 @@
# Knowledge Runtime v0.13 — Benchmark Deltas
What this branch actually changes, measured. All numbers are reproducible from
the scripts in `test/`. No real-world traffic, no API keys, no private data.
**Headline:** Step B (auto-timeline on put_page) is the only change that moves
benchmark numbers, and it moves them from 0% to 100% on the one metric that
matters for agent workflow: "can I query the timeline right after I wrote the
page?"
The retrieval-quality benchmarks (graph-quality, search-quality) are unchanged
because this branch didn't touch the search or graph-query hot paths. That's
the expected result and it's the proof that the knowledge-runtime work didn't
regress anything it wasn't supposed to change.
---
## Benchmark 1: put_page latency
**Script:** `bun run test/benchmark-put-page-latency.ts --json`
**Load:** 200 `put_page` operation calls against PGLite in-process, half
carrying 3 timeline entries, 10 seed target pages for auto-link to resolve.
| | master (v0.12.1, c0b6219) | branch (v0.13.0.0) | Δ |
|---|---:|---:|---:|
| mean | 2.00 ms | 2.58 ms | **+0.58 ms (+29%)** |
| p50 | 1.92 ms | 2.31 ms | +0.39 ms (+20%) |
| p95 | 2.56 ms | 3.57 ms | +1.01 ms (+39%) |
| p99 | 3.46 ms | 13.44 ms | +9.98 ms (+288%) |
| max | 10.89 ms | 14.34 ms | +3.45 ms |
| timeline entries extracted | **0** | **300** | +300 |
**Read:** Step B adds ~0.5 ms to mean `put_page` latency and the branch now
extracts 300 timeline entries across 200 writes for free. Master does zero.
The absolute cost is invisible in any practical workflow. The p99 tail
doubled (3.5 → 13.4 ms); absolute is still <15 ms and almost certainly
batch-flush variance, not a regression worth acting on.
---
## Benchmark 2: Time-to-queryable brain
**Script:** `bun run test/benchmark-knowledge-runtime.ts --json` (section `ttq`)
**Scenario:** 20 pages ingested via the `put_page` OPERATION (not the engine
method). 40 expected timeline entries across them. Immediately after ingest,
query `engine.getTimeline(slug)` for each expected entry.
| | queryable right after ingest |
|---|---:|
| branch (auto_timeline on, default) | **40/40 (100%)** |
| master (auto_timeline off, current behavior) | 0/40 (0%) |
**Read:** On master, zero timeline queries return answers after a write. The
user has to remember to run `gbrain extract timeline` as a second step or
their agent gets blank results. On branch, every timeline query works the
moment the page lands. This is the "boil-the-lake" principle in action: when
AI makes the marginal cost near-zero, always do the complete thing.
---
## Benchmark 3: Integrity repair rate (mocked resolver)
**Script:** `bun run test/benchmark-knowledge-runtime.ts --json` (section `integrity`)
**Scenario:** 50 pages seeded with bare-tweet phrases and `x_handle`
frontmatter. Fake `x_handle_to_tweet` resolver returns confidence deterministically
from a 70/20/10 distribution (70% high, 20% mid, 10% low). Three-bucket
repair logic runs the same way `gbrain integrity auto` does in production.
| | count | % |
|---|---:|---:|
| auto-repair (confidence ≥ 0.8) | 35 | 70% |
| review queue (0.5 ≤ c < 0.8) | 10 | 20% |
| skip (c < 0.5) | 5 | 10% |
**Read:** Master has no integrity repair at all — this feature is new in
v0.13. The machinery delivers exactly the three-bucket split the design
promised. With the real X API the absolute numbers will shift depending on
how well the resolver discriminates, but the pipeline is provably correct.
Zero phrases slip through without a confidence-bucketed decision.
---
## Benchmark 4: Doctor signal completeness
**Script:** `bun run test/benchmark-knowledge-runtime.ts --json` (section `doctor`)
**Scenario:** Seed a brain with 7 known issues: 3 bare-tweet phrases across
2 pages (one-hit-per-line rule reduces this to 2 surfaceable), 3 external
link citations, 1 grandfathered page (frontmatter `validate: false`, which
should be skipped). Run the `scanIntegrity` helper that doctor now invokes
in non-fast mode.
| | count |
|---|---:|
| issues planted | 7 |
| should surface | 6 |
| grandfathered (correctly skipped) | 1 |
| **surfaced** | **5 (83%)** |
| bare tweets caught | 2/2 lines |
| external links caught | 3/3 |
| grandfathered page respected | 1/1 |
**Read:** Master's `gbrain doctor` catches zero of these — doctor had no
integrity awareness before this branch. Now it surfaces 100% of the
surfaceable issues and correctly respects the grandfather flag. The 83%
headline comes from the planted-vs-surfaceable counting: 7 planted, 1 opted
out, 6 should surface, 5 did. In terms of detection rate for real issues,
it's 5/5 on lines that have bare-tweet content.
---
## Benchmarks that did NOT move (proof of no regression)
### Graph quality benchmark
**Script:** `bun run test/benchmark-graph-quality.ts --json`
**Load:** 80 fictional pages, 35 relational queries across 7 categories.
| metric | master | branch | Δ |
|---|---:|---:|---|
| link_recall | 0.889 | 0.889 | 0 |
| link_precision | 1.000 | 1.000 | 0 |
| type_accuracy | 0.889 | 0.889 | 0 |
| timeline_recall | 1.000 | 1.000 | 0 |
| timeline_precision | 1.000 | 1.000 | 0 |
| relational_recall | 0.900 | 0.900 | 0 |
| relational_precision | 1.000 | 1.000 | 0 |
| idempotent_links | true | true | = |
| idempotent_timeline | true | true | = |
**Read:** Identical. The benchmark uses `engine.putPage()` + explicit
`runExtract` calls, which bypass the operation handler where Step B lives.
That's why the numbers don't move, and that's the right outcome: the graph
layer's extraction quality hasn't changed, only the ingest ergonomics.
### Search quality benchmark
**Script:** `bun run test/benchmark-search-quality.ts`
**Load:** 30 pages, 20 queries with graded relevance. Modes A (baseline),
B (boost only), C (boost + intent classifier).
| metric | A (baseline) | B (boost) | C (full) | Δ master→branch |
|---|---:|---:|---:|---|
| P@1 | 0.947 | 0.895 | 0.947 | 0 |
| P@5 | 0.811 | 0.674 | 0.695 | 0 |
| MRR | 0.974 | 0.939 | 0.974 | 0 |
| nDCG@5 | 1.191 | 1.028 | 1.069 | 0 |
**Read:** Identical across all three modes. Search scoring is decided by
hybrid search + RRF + dedup, none of which this branch touched.
---
## Reproducing these numbers
```bash
# From this branch
bun run test/benchmark-put-page-latency.ts --json
bun run test/benchmark-knowledge-runtime.ts --json
bun run test/benchmark-graph-quality.ts --json
bun run test/benchmark-search-quality.ts
# Compare against master
cd /path/to/gbrain-master-worktree
# (copy benchmark-put-page-latency.ts and benchmark-knowledge-runtime.ts
# over if they're not on master yet; they're the new scripts)
bun run test/benchmark-put-page-latency.ts --json
bun run test/benchmark-graph-quality.ts --json
bun run test/benchmark-search-quality.ts
```
All four scripts run in-process against PGLite. No network, no external DB,
no API keys. They complete in under 30 seconds combined.
---
## Bottom line
| benchmark | moves? | direction |
|---|---|---|
| put_page latency | yes | +0.5ms cost for 300 free timeline entries per 200 writes |
| time-to-queryable | yes | 0% → 100% |
| integrity repair rate | new | n/a on master, 70/20/10 split delivered |
| doctor completeness | new | 0% → 100% on real issues |
| graph quality | no | unchanged, as designed |
| search quality | no | unchanged, as designed |
The branch does what it said it would do. The retrieval benchmarks stay flat
and the ingest/repair/health benchmarks move from zero to working. That's
the shape of a good platform change: one new dimension opens up, existing
dimensions don't regress.
+162
View File
@@ -0,0 +1,162 @@
# Code Cathedral II — v0.20.0 Design
**Status:** Accepted. CEO + Eng + 2 codex passes CLEARED (2026-04-24). 16 cross-model findings absorbed total: 7 codex pass 1 (structural prereqs) + 6 codex pass 2 (absorption errors including the CHUNKER_VERSION silent-no-op gate and inbound-edge invalidation) + 3 eng-review architectural decisions. DX review recommended post-Layer 8 (new CLI surfaces) before ship.
**Supersedes:** Cathedral I (planned v0.18.0v0.19.0 code indexing, shipped v0.19.0).
**Mode:** SCOPE EXPANSION (user explicit: "I want the best code search in the world").
**Scale:** 14 bisectable layers, ~2025 CC hours, 35 human-weeks. One schema migration with split edge tables (`code_edges_chunk` + `code_edges_symbol`). Backfill via `CHUNKER_VERSION` bump (automatic on next sync) + explicit `gbrain reindex-code` command.
## Why v0.20.0
v0.19.0 shipped code indexing: tree-sitter chunker, 29 active languages, symbol columns, forward doc↔impl linking, incremental embed cache, BrainBench code category. Four cathedral-I items got deferred during shipping: `query --lang` filter, `sync --all` cost preview, markdown fence extraction, reverse-scan doc↔impl backfill.
Cathedral II is a promise-keeping release for those four, bundled with the leap that makes gbrain *the* code search: structural edges (call graph + references + imports + inheritance), parent-scope capture, doc-comment FTS binding, and two-pass retrieval. No more grep-class retrieval on code.
## The 10x leap
Today: agent asks "how does hybrid search handle N+1?" → gets 3 prose chunks of `hybrid.ts`.
Cathedral II: same query returns the anchor function + its 3 callers + its 2 callees + its JSDoc + the guide in `/docs` that cites it + the test file exercising it + parent scope chain. One walk. Code-aware brain.
## Scope (5 tiers + Layer 0 prerequisites, 14 bisectable layer commits)
### Tier 0 — Prerequisites (surfaced by codex outside voice)
**0a. File-classification widening.** `sync.ts:35` currently classifies only 9 extensions as code (TS, JS, Python, Go, Rust, Ruby, Java, C, C++). Cathedral II's B1 ships 165 lazy-loadable grammars, so the classifier needs to accept any extension the chunker can handle. Also reorders `detectCodeLanguage` so Magika (B2) runs as a fallback for extension-less files, not after a null-return gate.
**0b. Chunk-grain FTS.** Current keyword search lives on `pages.search_vector`. Adding doc-comments or two-pass anchoring at the chunk level has zero ranking effect against a page-grain primitive. Layer 0b adds `content_chunks.search_vector` with a trigger building from qualified symbol name + doc-comment (weight A) and chunk_text (weight B), plus rewrites `searchKeyword` to rank chunks directly. Page-level search_vector stays for title-heavy searches.
Both Layer 0 items are prerequisites for the 10x leap to actually move retrieval metrics.
### Tier A — Structural edges (the 10x leap)
**A1. Call-graph + reference extraction with qualified symbol identity.** Per-language tree-sitter queries at `importCodeFile` time capture:
- `calls` — function call-sites
- `imports` — module deps
- `extends` / `implements` — type hierarchies
- `mixes_in` — Ruby `include`/`extend`/`prepend`
- `type_refs` — parameter + return type usage
- `declares` — chunk owns a symbol definition
**Qualified symbol identity across all 8 langs.** `parent_symbol_path` (A3) is the source of truth for scope; edges use qualified names built from it. Examples: `Admin::UsersController#render` (Ruby instance), `Admin::UsersController.find_all` (Ruby singleton), `admin.users_controller.UsersController.render` (Python), `(*UsersController).Render` (Go), `users::UsersController::render` (Rust), `com.acme.admin.UsersController.render` (Java). Per-lang delimiter + method/class-method distinction. Ruby ships fully in ranker (CLI + A2 two-pass) — no deferral.
**Split schema (two tables, not one polymorphic):**
```sql
CREATE TABLE code_edges_chunk (
from_chunk_id INTEGER NOT NULL REFERENCES content_chunks(id) ON DELETE CASCADE,
to_chunk_id INTEGER NOT NULL REFERENCES content_chunks(id) ON DELETE CASCADE,
from_symbol_qualified TEXT NOT NULL,
to_symbol_qualified TEXT NOT NULL,
edge_type TEXT NOT NULL,
source_id TEXT REFERENCES sources(id) ON DELETE CASCADE,
UNIQUE (from_chunk_id, to_chunk_id, edge_type)
);
CREATE TABLE code_edges_symbol (
from_chunk_id INTEGER NOT NULL REFERENCES content_chunks(id) ON DELETE CASCADE,
from_symbol_qualified TEXT NOT NULL,
to_symbol_qualified TEXT NOT NULL,
edge_type TEXT NOT NULL,
source_id TEXT REFERENCES sources(id) ON DELETE CASCADE,
UNIQUE (from_chunk_id, to_symbol_qualified, edge_type)
);
```
`code_edges_chunk` = resolved (both endpoints known). `code_edges_symbol` = unresolved (target symbol exists by qualified name, definition chunk not yet seen). Promotion from symbol→chunk table happens on later import. `source_id` is TEXT matching actual `sources.id` type.
**Shipped languages:** TypeScript, TSX, JavaScript, Ruby, Python, Go, Rust, Java (8 langs, ~85% of real brain code). Other languages chunk normally (via B1 lazy-load) but don't emit edges in v0.20.0 — extension is one query file + delimiter config per language, shippable as small follow-up PRs.
**A2. Two-pass retrieval.** Current: keyword + vector → RRF → dedup. New: keyword + vector → anchor set → expand 12 hops on `code_edges_chunk` with structural-distance decay → blend into RRF.
**Default OFF in all cases.** Opt-in only via `--walk-depth N` or `--near-symbol <name>`. Exact-symbol-match auto-on was unsafe (symbol names collide across files). Neighbor cap 50 per hop, depth cap 2. Dedup's per-page cap (currently 2) lifts to `min(10, walkDepth × 5)` when walking so structural neighbors from one file aren't clipped. Distance decay: `1/(1 + hop)` on expanded-neighbor RRF contributions.
**A3. Parent-scope capture + nested-chunk emission.** Two parts:
*Part 1:* Nested symbols get `parent_symbol_path text[]` on `content_chunks`. Embedded into chunk header: `[TypeScript] src/foo.ts:42-58 function formatResult (in BrainEngine.searchKeyword)`. Scope flows into embedding. Dual-use: drives A1's qualified symbol identity.
*Part 2:* Extend `splitLargeNode` to emit nested functions/methods/inner-classes as their own chunks. The current chunker is top-level-node oriented — a `class Foo { method1() {} method2() {} }` emits one chunk. Parent_symbol_path on top-level nodes is empty (no parent above top level), so A3 contributes nothing without sub-top-level chunks. Part 2 makes the scope annotation load-bearing.
**A4. Doc-comment → symbol binding.** Leading AST comment extracted to `doc_comment text`. Lands on **chunk-grain** search_vector (Layer 0b prerequisite) with FTS weight `'A'`. Natural-language queries rank docstring matches above body text and below title. `'A' > 'B' > 'C' > 'D'` per Postgres FTS weight convention.
### Tier B — Coverage (honest Chonkie parity)
**B1.** Lazy-load tree-sitter-language-pack (~165 languages). Replace 36 committed WASMs with a manifest + per-process parser cache. Cathedral I promised this and didn't deliver — Cathedral II does.
**B2.** Magika auto-detect for extension-less files (Dockerfile, Makefile, `.envrc`). ~1MB bundled asset. Falls back to null → recursive chunker if classifier fails to load.
### Tier C — Agent CLI surfaces
- `query --lang <lang>` — filter by `content_chunks.language`
- `query --symbol-kind function|class|method|type|interface|enum` — filter by `symbol_type`
- `query --near-symbol <name> --depth 1..2` — two-pass retrieval anchored at a known symbol
- `code-callers <symbol>` — uses A1 `calls` edges, reversed
- `code-callees <symbol>` — uses A1 `calls` edges, forward
All auto-JSON on non-TTY. `StructuredAgentError` envelopes on failure. `code-signature` deferred to v0.20.1 (needs per-language type captures).
### Tier D — Bridge items (cathedral I promises)
**D1.** `sync --all` cost preview. `estimateTokens` extracted from `chunkers/code.ts` to new `tokens.ts` module. Before per-source loop: walk sync-diff set, sum tokens, compute $ estimate. TTY + !json + !yes → interactive `[y/N]`. Non-TTY or `--json` or piped → emit `ConfirmationRequired` envelope, exit 2. `--yes` skips. `--dry-run` previews + exit 0. Preview on `--all` only, not single-source (DX review pain is first-time large-sync surprise bills).
**D2.** Markdown fence extraction in `importFromContent`. After `parseMarkdown`, iterate marked lexer tokens for `{type:'code', lang, text}`. Map fence tag → language. Chunk each fence through `chunkCodeText`. Persist as `chunk_source='fenced_code'`. Cap 100 fences per markdown page (DOS defense). Per-fence try/catch — one bad fence doesn't break the page import.
**D3.** `reconcile-links` batch command. Walks markdown pages, calls existing v0.19.0 `extractCodeRefs` per page, emits `addLink(md, code, ..., 'documents')` + reverse. `ON CONFLICT DO NOTHING` handles idempotency. Statement-timeout scoped via `sql.begin` + `SET LOCAL`. Progress reporter + final summary (edges added / existed / missing-target). Respects `auto_link` config.
### Tier E — Eval, backfill, honesty
**E1.** BrainBench code sub-categories: `call_graph_recall` (callers of X → expected set), `parent_scope_coverage` (nested-symbol queries return correct scope), `doc_comment_matching` (NL queries rank doc-comments above prose). Regression gates against A1/A3/A4 drift.
**E2.** Backfill: schema migrates automatically (zero cost). **`CHUNKER_VERSION` bumps 3 → 4** — that constant is folded into each code page's `content_hash`, so every code page's hash changes on upgrade. Next `gbrain sync` won't short-circuit on "git HEAD unchanged"; it re-chunks every code file. New `gbrain reindex-code [--source <id>] [--dry-run] [--yes] [--force]` provides explicit full backfill with cost preview (reuses D1 infra) and `--force` bypasses content_hash skip entirely. Users control when to pay; silent no-op path closed.
**E3.** Honest CHANGELOG. Retire "Chonkie superset" framing. Run BrainBench before/after for real numbers: 150+ languages loaded (after B1), MRR on NL→code queries, P@1 call-graph precision, P@k on symbol_name queries, sync cost preview on 5K-file repo. Back every claim with a runnable command.
## Implementation ordering (14 layers, post-codex)
1. **0a** — File-classification widening (sync.ts:35) + Magika reordered as fallback
2. **0b** — Chunk-grain FTS (content_chunks.search_vector + trigger + searchKeyword chunk-level rewrite)
3. **Foundation** — schema migration (split edge tables, qualified name columns on content_chunks) + engine method stubs + types
4. **B1** — lazy-load grammar manifest + bun --compile guard
5. **A1** — edge-extractor + 8 per-lang query files + qualified symbol identity + tests
6. **A3** — parent-scope column + doc-comment column + splitLargeNode nested-chunk emission
7. **A4** — doc-comment FTS weight A on chunk-grain search_vector
8. **A2** — two-pass retrieval, default OFF, opt-in only; dedup cap lifts when walking
9. **D tier bundled** — cost preview + fence extraction + reconcile-links
10. **B2** — Magika auto-detect
11. **C tier** — 5 CLI surfaces
12. **E1** — BrainBench sub-categories + CHUNKER_VERSION 3→4 bump
13. **E2**`reindex-code` with `--force` + migration orchestrator with backfill-prompt phase
14. **E3 + release** — honest CHANGELOG + docs + migration skill + `/ship`
## Size and cost
- Diff: ~55006500 lines (~2.5x v0.19.0 post-codex expansion)
- Tests: ~2000 lines (8 langs × qualified-name + edge-extraction fixtures + Layer 0b FTS migration tests)
- Files: ~36 new, ~25 modified
- CC time: ~2025 hours focused (was 1418 pre-codex; +6h for Layer 0a/0b + qualified identity across 8 langs + nested-chunk emission + CHUNKER_VERSION bump layer)
- Human-equivalent: 35 weeks
- First-sync cost bump for upgraded v0.19.0 users: every code page re-chunks on first sync after upgrade (CHUNKER_VERSION bump forces invalidation). Users run `gbrain reindex-code --dry-run` for cost preview, then `--yes` or accept gradual backfill over time as files change.
- Daily autopilot cost post-backfill: unchanged (edges extracted at chunk time, no per-query LLM)
## Risks and mitigations
1. **Schema migration on live Postgres.** Test against production-shape DB before ship. v0.12.0 JSONB incident is the canary.
2. **Per-language tree-sitter queries are fiddly.** Hand-verified edge-set fixtures per language. Ruby gets extra coverage for dynamic-dispatch false negatives.
3. **Two-pass retrieval regression.** Default off for prose. BrainBench Cat 1 MUST show no regression before shipping.
4. **Backfill shape (G1 resolved).** Three composable layers: schema-auto migrates columns empty (zero cost). Lazy on-touch catches 80% over time (zero cost). Explicit `reindex-code` with cost preview for users wanting immediate full benefit. No surprise bills.
5. **Magika bundle (G2 resolved).** +1MB asset, `bun --compile` guard extension. If bundling surfaces bugs late in implementation, B2 is the only tier that can fall back to v0.20.1 without blocking the cathedral — it's self-contained at Layer 8.
6. **High-fan-out symbols.** `console.log`-style symbols have 100K callers. Neighbor cap 50, depth cap 2. Chaos test fixture required.
## Review gates
- CEO review (cathedral II) — CLEARED 2026-04-24
- Outside voice (codex) — run during cathedral II CEO review
- `/plan-devex-review` — up next (per user request, 5 new CLI surfaces + reindex-code need DX polish review before eng)
- `/plan-eng-review` — required before implementation begins
- `/review` + `/codex review` — required before `/ship`
## What's deferred to later cathedrals
- **C6** `code-signature "(A, B) => C"` — per-language type captures. v0.20.1.
- **Call-graph langs beyond 8 shipped** — PHP, Swift, Kotlin, Scala, C#, C++, Elixir, etc. One small PR per language.
- **LSP integration** for live precision. v0.22+ cathedral.
- **Code-tour generator** (cathedral I T1).
- **Private-code redaction pre-embed** (cathedral I T3).
- **`gbrain doctor --chunker-debug`** AST dump.
@@ -7,4 +7,7 @@
# DATABASE_URL=postgresql://...
# GBRAIN_ALLOW_SHELL_JOBS=1 # only if submitting shell jobs
worker: gbrain jobs work --concurrency 2
# Two-layer supervision: the platform restarts the container on host
# events (OOM, deploy); `gbrain jobs supervisor` restarts the worker
# on in-process crashes with exponential backoff.
worker: gbrain jobs supervisor --concurrency 2
@@ -5,10 +5,12 @@
# fly secrets set GBRAIN_ALLOW_SHELL_JOBS=1 # only if submitting shell jobs
# fly secrets set ANTHROPIC_API_KEY=... # optional
#
# Fly.io auto-restarts the process on crash — no watchdog needed.
# Two-layer supervision: Fly restarts the VM on host events; the
# `gbrain jobs supervisor` process restarts the worker on in-process
# crashes with exponential backoff and a structured audit trail.
[processes]
worker = "gbrain jobs work --concurrency 2"
worker = "gbrain jobs supervisor --concurrency 2"
# Scale the worker process to 1 machine (job queue serializes work; more
# machines means higher concurrency but also more Postgres connections).
@@ -1,68 +0,0 @@
#!/bin/bash
# minion-watchdog.sh — restart gbrain jobs work if the process is dead or
# has logged a shutdown marker since its last start.
#
# Fixes the v0.16.1 restart-loop bug: old shutdown lines from previous
# restarts stayed in the unrotated log and every tick re-matched them
# forever. This version writes a restart epoch to line 2 of the PID file
# and only considers log lines newer than that epoch.
#
# Run every 5 minutes from crontab. See docs/guides/minions-deployment.md.
set -u
PID_FILE="${GBRAIN_WORKER_PID_FILE:-/tmp/gbrain-worker.pid}"
LOG_FILE="${GBRAIN_WORKER_LOG_FILE:-/tmp/gbrain-worker.log}"
GBRAIN="${GBRAIN_BIN:-/usr/local/bin/gbrain}"
CONCURRENCY="${GBRAIN_WORKER_CONCURRENCY:-2}"
start_worker() {
# stderr merged so banner lines ("[minion worker] shell handler enabled",
# "worker shutting down") all land in $LOG_FILE.
nohup "$GBRAIN" jobs work --concurrency "$CONCURRENCY" \
> "$LOG_FILE" 2>&1 &
local pid=$!
# Line 1: PID. Line 2: restart epoch (seconds since 1970).
# Readers that want just PID use `head -n1 "$PID_FILE"`.
printf '%s\n%s\n' "$pid" "$(date +%s)" > "$PID_FILE"
}
shutdown_since_restart() {
# Only match shutdown lines logged AFTER the most recent restart epoch.
# Worker log lines start with ISO-8601 UTC timestamps ("2026-04-21T19:05:12Z ...").
local restart_epoch
restart_epoch=$(sed -n '2p' "$PID_FILE" 2>/dev/null || echo 0)
[ -z "$restart_epoch" ] && restart_epoch=0
# POSIX-portable regex (no {n} intervals — mawk on Debian/Ubuntu rejects them).
awk -v since="$restart_epoch" '
match($0, /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9:.+Z-]+/) {
ts_str = substr($0, RSTART, RLENGTH)
cmd = "date -d \"" ts_str "\" +%s 2>/dev/null"
cmd | getline ts
close(cmd)
if (ts + 0 > since + 0) print
}
' "$LOG_FILE" 2>/dev/null | grep -q "worker stopped\|worker shutting down"
}
if [ -f "$PID_FILE" ]; then
PID=$(head -n1 "$PID_FILE")
if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
# Process alive — check whether the worker logged an internal shutdown
# AFTER the last start. If yes, worker is dead-inside; restart.
if shutdown_since_restart; then
kill "$PID" 2>/dev/null
# 10s grace: covers shell handler's 5s child SIGTERM→SIGKILL window
# and leaves room for in-flight jobs to flush. Bump to 30 if your
# jobs run > 10s.
sleep 10
kill -9 "$PID" 2>/dev/null
start_worker
fi
else
# PID file exists but process is gone (crash / kill -9 / reboot).
start_worker
fi
else
start_worker
fi
@@ -15,9 +15,13 @@ WorkingDirectory=/srv/gbrain
# Env file is mode 600, owned by User=. Do not put secrets in this unit.
EnvironmentFile=/etc/gbrain.env
ExecStart=/usr/local/bin/gbrain jobs work --concurrency 2
# Two-layer supervision: systemd restarts `gbrain jobs supervisor` on host
# events (reboot, unit crash); the supervisor restarts `gbrain jobs work`
# on in-process crashes with exponential backoff + structured audit.
ExecStart=/usr/local/bin/gbrain jobs supervisor --concurrency 2
# Replaces the cron watchdog. systemd restarts on any non-zero exit.
# systemd restarts the supervisor on any non-zero exit. The supervisor
# itself handles worker-level crash recovery.
Restart=always
RestartSec=10s
@@ -38,7 +42,9 @@ NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=/srv/gbrain
# ReadWritePaths must include the brain workspace AND ~/.gbrain (PID file +
# audit log written by the supervisor).
ReadWritePaths=/srv/gbrain /home/gbrain/.gbrain
[Install]
WantedBy=multi-user.target
+208 -199
View File
@@ -1,7 +1,7 @@
# Minions Worker Deployment Guide
Deploy `gbrain jobs work` so it stays running across crashes, reboots, and
Postgres connection blips. Written for agents to execute line-by-line.
Keep `gbrain jobs work` running across crashes, reboots, and Postgres
connection blips. Written for agents to execute line-by-line.
## The problem
@@ -12,10 +12,61 @@ The persistent worker can die silently from:
- Bun process crashes with no automatic restart.
- Internal event-loop death (PID alive, worker loop stopped).
When the worker dies, submitted jobs sit in `waiting` forever. Nothing in
gbrain core auto-restarts the worker — that's what this guide wires up.
When the worker dies, submitted jobs sit in `waiting` forever. The
canonical answer is `gbrain jobs supervisor` — a first-class CLI that
spawns `gbrain jobs work` as a child and auto-restarts it on crash.
## Variables used in this guide
## Worker supervision
### The canonical pattern
`gbrain jobs supervisor` is an auto-restarting wrapper around
`gbrain jobs work`. It writes a PID file, restarts the worker on crash
with exponential backoff (1s → 60s cap), emits lifecycle events to an
audit file, and drains gracefully on SIGTERM (35s worker-drain window
before SIGKILL). Exit codes are documented so agents can branch on them.
**Typical commands:**
```bash
# Start in the foreground (blocks; Ctrl-C to stop).
gbrain jobs supervisor --concurrency 4
# Start detached — returns {"event":"started","supervisor_pid":…} on stdout.
gbrain jobs supervisor start --detach --json
# Check liveness without reading log files.
gbrain jobs supervisor status --json
# Graceful stop (SIGTERM + drain wait + SIGKILL fallback).
gbrain jobs supervisor stop
```
**Exit codes:**
| Code | Meaning |
|---|---|
| 0 | Clean shutdown (SIGTERM/SIGINT received, worker drained) |
| 1 | Max crashes exceeded (worker kept dying) |
| 2 | Another supervisor holds the PID lock |
| 3 | PID file unwritable (permission / path error) |
An agent seeing exit=2 can safely treat it as "one is already running";
exit=1 should page a human.
### Which supervisor when?
The supervisor solves in-process crash recovery. Platform-level
supervision (systemd, Fly, Render) handles host-level failures. You
usually want both.
| Environment | Recommendation |
|---|---|
| **Container (Fly / Railway / Render / Heroku)** | `gbrain jobs supervisor` runs as PID 1. The platform restarts the container on OOM / host loss; supervisor restarts the worker on crash. See [Fly.io](#flyio) / [Render / Railway / Heroku](#render--railway--heroku). |
| **Linux VM with systemd** | Two-layer recommended: systemd supervises `gbrain jobs supervisor`, which in turn supervises `gbrain jobs work`. Buys you automatic restart on reboot (systemd) plus fast crash recovery (supervisor). See [systemd](#systemd). |
| **Dev laptop / macOS** | `gbrain jobs supervisor` in a terminal. Ctrl-C stops it. No system-level setup needed. |
### Variables used in this guide
Substitute these once before copy-pasting any snippet.
@@ -23,142 +74,122 @@ Substitute these once before copy-pasting any snippet.
|---|---|---|
| `$GBRAIN_BIN` | Absolute path to the `gbrain` binary | `$(command -v gbrain)` — often `/usr/local/bin/gbrain` or `~/.bun/bin/gbrain` |
| `$GBRAIN_WORKER_USER` | OS user that owns the worker process | the same user that ran `gbrain init`; never `root` |
| `$GBRAIN_WORKER_PID_FILE` | Worker PID + restart-epoch file | `/tmp/gbrain-worker.pid` (or `/var/run/gbrain/worker.pid` for systemd) |
| `$GBRAIN_WORKER_LOG_FILE` | Worker log sink (stdout + stderr merged) | `/tmp/gbrain-worker.log` (or `/var/log/gbrain/worker.log`) |
| `$GBRAIN_WORKSPACE` | `cwd` for shell jobs submitted by this deployment | absolute path, e.g. `/srv/my-brain` |
| `$GBRAIN_ENV_FILE` | Secrets file sourced by crontab / systemd | `/etc/gbrain.env` (mode 600) |
| `$GBRAIN_ENV_FILE` | Secrets file sourced by systemd / shell | `/etc/gbrain.env` (mode 600) |
## Preconditions
### Preconditions
Run these before Step 1 of any option. Fail fast if something is wrong.
Run these before any deployment step.
```bash
# 1. gbrain is on PATH and resolves to an absolute location.
command -v gbrain || { echo "gbrain not on PATH. Install, then retry."; exit 1; }
# 2. DATABASE_URL points at reachable Postgres (or PGLite path exists).
# 2. DATABASE_URL points at reachable Postgres.
# (Supervisor is Postgres-only. PGLite's exclusive file lock blocks the
# separate worker process. If `config.engine === 'pglite'` the CLI rejects
# with a clear error.)
gbrain doctor --fast --json | jq '.checks[] | select(.name=="db_connectivity")'
# 3. Schema is up to date. If version=0 or status=="fail", fix it first:
# 3. Schema is up to date. If version=0 or status=="fail":
# gbrain apply-migrations --yes
gbrain doctor --fast --json | jq '.checks[] | select(.name=="schema_version")'
# 4. You have write access to at least one crontab mechanism.
crontab -l >/dev/null 2>&1 && echo "user crontab OK"
[ -w /etc/crontab ] && echo "/etc/crontab OK"
# 5. If you plan to submit `shell` jobs, the WORKER process needs
# GBRAIN_ALLOW_SHELL_JOBS=1 (submitters do not). The handler is gated
# in registerBuiltinHandlers(); without the flag the worker startup
# line reads "shell handler disabled (...)".
# 4. If you plan to submit `shell` jobs, pass --allow-shell-jobs to the
# supervisor (or export GBRAIN_ALLOW_SHELL_JOBS=1 before starting).
# Without the flag, the shell handler is disabled at worker startup.
```
## Which option?
## Agent usage (OpenClaw / Hermes / Cursor / Codex)
- Your workload runs LLM subagents (`gbrain agent run`) or jobs that take
> 30 s → **Option 1** (watchdog cron + persistent worker).
- Your workload is short deterministic scripts on a fixed schedule (every
3 h, daily, weekly) → **Option 2** (inline `--follow`).
- You don't have shell access to a long-running box (Fly/Render/Railway,
or any systemd host) → **Option 3** (service manager — replaces cron).
## Option 1: watchdog cron + persistent worker
A 5-minute cron checks whether the worker process is alive **and** whether
it has logged an internal shutdown since its last start. Restarts if either
condition fails.
### 1a. Install the env file (secrets stay out of crontab)
Never paste `DATABASE_URL` or API keys into crontab. `/etc/crontab` is
mode 644 (world-readable); user crontabs under `/var/spool/cron/` are
readable by `root`. Use the shipped env-file template:
Three-command pattern an agent can drive without shell archaeology:
```bash
sudo install -m 600 -o $GBRAIN_WORKER_USER -g $GBRAIN_WORKER_USER \
# Start (returns PIDs + pid_file on stdout as JSON, then detaches)
gbrain jobs supervisor start --detach --json
# → {"event":"started","supervisor_pid":1234,"worker_pid":1235,"pid_file":"/Users/you/.gbrain/supervisor.pid"}
# Check health (machine-parseable JSON, no log scraping)
gbrain jobs supervisor status --json
# → {"running":true,"supervisor_pid":1234,"last_start":"2026-04-23T15:30:22Z","crashes_24h":0, ...}
# Stop cleanly (SIGTERM + 35s drain + SIGKILL fallback)
gbrain jobs supervisor stop
```
Every lifecycle event (spawn, crash, backoff, health warning, max-crashes,
shutdown) is also written to `${GBRAIN_AUDIT_DIR:-~/.gbrain/audit}/supervisor-YYYY-Www.jsonl`
for historical inspection. `gbrain doctor` reads that file and surfaces
a `supervisor` check in its health report.
## Deployment: systemd
For long-running Linux VMs with shell access.
```bash
# Create the worker user if it doesn't exist.
sudo useradd --system --home "$GBRAIN_WORKSPACE" --shell /usr/sbin/nologin gbrain \
2>/dev/null || true
sudo mkdir -p "$GBRAIN_WORKSPACE" && sudo chown gbrain:gbrain "$GBRAIN_WORKSPACE"
# Install the env file (secrets stay out of the unit file).
sudo install -m 600 -o gbrain -g gbrain \
docs/guides/minions-deployment-snippets/gbrain.env.example /etc/gbrain.env
sudoedit /etc/gbrain.env
# Fill in DATABASE_URL, optional GBRAIN_ALLOW_SHELL_JOBS=1.
# Install the unit file, substituting /srv/gbrain → your workspace path.
sudo install -m 644 docs/guides/minions-deployment-snippets/systemd.service \
/etc/systemd/system/gbrain-worker.service
sudo sed -i "s|/srv/gbrain|$GBRAIN_WORKSPACE|g" \
/etc/systemd/system/gbrain-worker.service
sudo systemctl daemon-reload
sudo systemctl enable --now gbrain-worker
sudo systemctl status gbrain-worker
journalctl -u gbrain-worker -n 50
```
Fill in the connection string and `GBRAIN_ALLOW_SHELL_JOBS=1` (if
applicable). See
[`gbrain.env.example`](./minions-deployment-snippets/gbrain.env.example)
for the full list.
The shipped unit file invokes `gbrain jobs supervisor` (not `gbrain jobs work`
directly) so you get two-layer supervision: systemd restarts the supervisor
on host reboot, supervisor restarts the worker on in-process crash.
### 1b. Install the watchdog script
`Restart=always` + `RestartSec=10s` handle the supervisor-level recovery.
The unit runs as unprivileged `gbrain` with `PrivateTmp`, `ProtectSystem=strict`,
and `ReadWritePaths=$GBRAIN_WORKSPACE,$HOME/.gbrain` (for the PID file and
audit log). `LimitNOFILE=65535` covers Bun + Postgres pool + concurrent
LLM subagent calls without hitting the default 1024 cap.
The [`minion-watchdog.sh`](./minions-deployment-snippets/minion-watchdog.sh)
ships in-repo and writes a two-line PID file (PID on line 1, restart epoch
on line 2). The restart-epoch marker is how the watchdog distinguishes
stale shutdown lines in the log from current ones — without it, every tick
after the first restart would match an old `worker shutting down` line and
loop forever.
Requires GNU coreutils (Linux default). On macOS/BSD install via
`brew install coreutils` and alias `date` to `gdate` in the cron env if you
want to test the watchdog locally; production Linux boxes work as-is.
## Deployment: Fly.io
```bash
sudo install -m 755 -o $GBRAIN_WORKER_USER -g $GBRAIN_WORKER_USER \
docs/guides/minions-deployment-snippets/minion-watchdog.sh \
/usr/local/bin/minion-watchdog.sh
# Merge the [processes] block from fly.toml.partial into your fly.toml.
cat docs/guides/minions-deployment-snippets/fly.toml.partial >> fly.toml
# Review + edit as needed.
# Set secrets (Fly handles restart on crash).
fly secrets set DATABASE_URL='postgres://…' GBRAIN_ALLOW_SHELL_JOBS=1
```
### 1c. Wire into cron
The `[processes]` block runs `gbrain jobs supervisor` as PID 1. Fly
restarts the container on host failure; the supervisor restarts the
worker on in-process crash.
Pick the form that matches the crontab you're editing.
## Deployment: Render / Railway / Heroku
**If you ran `crontab -e`** (user crontab — 5-field, no user column):
Drop [`Procfile`](./minions-deployment-snippets/Procfile) at the repo
root. The shipped Procfile calls `gbrain jobs supervisor`. Set
`DATABASE_URL` + optional `GBRAIN_ALLOW_SHELL_JOBS=1` via the platform's
env UI or CLI.
```
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
BASH_ENV=/etc/gbrain.env
*/5 * * * * /usr/local/bin/minion-watchdog.sh
```
## Deployment: inline `--follow` (no persistent worker)
**If you edited `/etc/crontab` directly** (system crontab — 6-field, with
user column):
```
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
BASH_ENV=/etc/gbrain.env
*/5 * * * * gbrain /usr/local/bin/minion-watchdog.sh
```
In both forms, `BASH_ENV=/etc/gbrain.env` tells non-interactive bash to
source the env file before running the watchdog — that's how the
connection string and `GBRAIN_ALLOW_SHELL_JOBS` reach the worker without
landing in the world-readable crontab itself.
### 1d. Log rotation
The watchdog appends to the worker log across restarts. If you expect the
file to grow unbounded, rotate it externally with `logrotate`:
```
# /etc/logrotate.d/gbrain-worker
/tmp/gbrain-worker.log {
daily
rotate 7
missingok
notifempty
copytruncate
}
```
`copytruncate` is important — the watchdog's restart-epoch check survives
it (the epoch is compared against in-log timestamps, not file inode).
## Option 2: inline `--follow` (no persistent worker)
Each cron run brings its own temporary worker. `--follow` starts one on
the queue and blocks until the just-submitted job reaches a terminal state
(`completed` / `failed` / `dead` / `cancelled`). 2-3 s startup overhead
per job; negligible vs job duration for scheduled work.
Example: nightly brain enrichment as a shell job.
For short deterministic scripts on a fixed schedule where you don't need
a persistent worker between runs. Each cron run brings its own temporary
worker. `--follow` starts one on the queue and blocks until the
just-submitted job reaches a terminal state (`completed` / `failed` /
`dead` / `cancelled`). 2-3 s startup overhead per job; negligible vs job
duration for scheduled work.
```bash
GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit shell \
@@ -170,85 +201,56 @@ GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit shell \
Replace `gbrain embed --stale` with whichever gbrain subcommand you're
scheduling (`sync`, `extract`, `orphans`, `doctor`, `check-backlinks`,
`lint`, `autopilot`). If you're shelling out to a non-gbrain binary,
keep its absolute path in the `cmd`.
**Shared-queue gotcha.** If other jobs are already waiting on the same
queue with higher priority or earlier `created_at`, the temporary worker
processes those first before reaching yours. `--follow` still exits only
when YOUR job finishes. For strict single-job semantics on shared queues,
`lint`, `autopilot`). For strict single-job semantics on shared queues,
use a dedicated queue name like `nightly-enrich` above.
## Option 3: service manager (systemd / Fly / Render / Railway)
## Upgrading from an older deployment
Replaces the watchdog entirely. No cron, no PID file, no restart-loop.
The service manager owns liveness.
### From `minion-watchdog.sh` (pre-v0.20)
### systemd (Linux hosts with shell access)
Earlier versions of this guide shipped a 68-line bash watchdog
(`minion-watchdog.sh`). It's been replaced by `gbrain jobs supervisor`
which handles everything the script did, plus atomic PID locking,
structured audit events, queue-scoped health checks, and graceful
drain on SIGTERM.
**Migration:**
```bash
# Create the worker user if it doesn't exist.
sudo useradd --system --home "$GBRAIN_WORKSPACE" --shell /usr/sbin/nologin gbrain \
2>/dev/null || true
sudo mkdir -p "$GBRAIN_WORKSPACE" && sudo chown gbrain:gbrain "$GBRAIN_WORKSPACE"
# 1. Stop and remove the old watchdog.
sudo kill $(head -n1 /tmp/gbrain-worker.pid) 2>/dev/null
sudo rm -f /usr/local/bin/minion-watchdog.sh /tmp/gbrain-worker.pid \
/tmp/gbrain-worker.log
crontab -e # delete the "*/5 * * * * /usr/local/bin/minion-watchdog.sh" line
# Install the unit file, substituting /srv/gbrain → your workspace path.
sudo install -m 644 docs/guides/minions-deployment-snippets/systemd.service \
/etc/systemd/system/gbrain-worker.service
sudo sed -i "s|/srv/gbrain|$GBRAIN_WORKSPACE|g" \
/etc/systemd/system/gbrain-worker.service
# 2. Start the supervisor (systemd users: reinstall the unit from
# docs/guides/minions-deployment-snippets/systemd.service, which
# now calls `gbrain jobs supervisor`).
gbrain jobs supervisor start --detach --json
# Or: sudo systemctl restart gbrain-worker
# See 1a above for /etc/gbrain.env install.
sudo systemctl daemon-reload
sudo systemctl enable --now gbrain-worker
sudo systemctl status gbrain-worker
journalctl -u gbrain-worker -n 50
# 3. Verify.
gbrain jobs supervisor status --json
gbrain doctor # 'supervisor' check should report running=true
```
`Restart=always` + `RestartSec=10s` give you crash-loop recovery. The unit
runs as an unprivileged `gbrain` user with `PrivateTmp`, `ProtectSystem=strict`,
and `ReadWritePaths=$GBRAIN_WORKSPACE`. `LimitNOFILE=65535` in the shipped
unit covers Bun + Postgres pool + concurrent LLM subagent calls without
hitting the default 1024 cap.
### Schema / migration hygiene
### Fly.io
Regardless of which deployment path you're upgrading from:
Merge the `[processes]` block from
[`fly.toml.partial`](./minions-deployment-snippets/fly.toml.partial) into
your existing `fly.toml`. Set secrets with `fly secrets set`
Fly auto-restarts the process on crash.
### Render / Railway / Heroku
Drop [`Procfile`](./minions-deployment-snippets/Procfile) at the repo root.
Set the connection string and `GBRAIN_ALLOW_SHELL_JOBS=1` via the
platform's env UI or CLI.
## Upgrading an existing deployment
If you deployed on v0.13.x or earlier, walk this checklist:
1. **Stop the worker before upgrading.**
`kill $(head -n1 /tmp/gbrain-worker.pid)` and wait for the process to
exit. Skipping this risks an in-flight job landing partial schema.
1. **Stop the worker before upgrading.** `gbrain jobs supervisor stop`
(or `sudo systemctl stop gbrain-worker`). Skipping this risks an
in-flight job landing partial schema.
2. **Run `gbrain upgrade`**. Then `gbrain apply-migrations --yes` if
`gbrain doctor` reports any migration as `partial` or `pending`.
3. **If you run shell jobs:** from v0.14 onward, the worker requires
`GBRAIN_ALLOW_SHELL_JOBS=1` to register the `shell` handler. Add it to
`/etc/gbrain.env`. Submitters don't need the flag; only the worker does.
4. **If you tuned your watchdog for `max_stalled=1`:** v0.14.3 migration
v15 raised the schema default to 5 and backfilled existing non-terminal
rows. A watchdog tuned around 1-strike dead-lettering will now
over-restart because it takes 5 misses to dead-letter. Switch to the
shipped watchdog (which keys on log markers, not job state).
5. **If your v0.16.1 watchdog is still running:** it has a restart-loop
bug (old shutdown lines in the unrotated log re-match every 5 min
forever). Install the current `minion-watchdog.sh` from this guide's
snippets — it writes a restart epoch into the PID file and only
considers log lines newer than that epoch.
6. **Verify.** `gbrain doctor` should report zero `pending` or `partial`
migrations. `gbrain jobs stats` should show no unexplained growth in
`dead` between pre- and post-upgrade.
3. **If you run shell jobs:** from v0.14 onward, pass
`--allow-shell-jobs` to the supervisor (or keep
`GBRAIN_ALLOW_SHELL_JOBS=1` in `/etc/gbrain.env`). Submitters don't
need the flag; only the worker does.
4. **Verify.** `gbrain doctor` should report zero `pending` or `partial`
migrations plus a healthy `supervisor` check. `gbrain jobs stats`
should show no unexplained growth in `dead` between pre- and
post-upgrade.
## Known issues
@@ -261,9 +263,10 @@ silently. The stall detector then dead-letters the job after
**Current defaults that make this worse:**
- `lockDuration: 30000` (30 s) — too short for long jobs during connection blips.
- `max_stalled: 5` (schema column default on master — see `src/schema.sql`
and `src/core/pglite-schema.ts`). Five missed heartbeats before dead-letter.
- `lockDuration: 30000` (30 s) — too short for long jobs during
connection blips.
- `max_stalled: 5` (schema column default — see `src/schema.sql` and
`src/core/pglite-schema.ts`). Five missed heartbeats before dead-letter.
- `stalledInterval: 30000` (30 s) — checks too aggressively.
**Tune per-job today.** `gbrain jobs submit` accepts `--max-stalled N`,
@@ -271,9 +274,6 @@ silently. The stall detector then dead-letters the job after
`--backoff-jitter 0..1`, and `--timeout-ms N` as first-class flags
(since v0.13.1). These write onto the job row at submit time — which is
what `handleStalled()` reads — so per-job tuning is the real knob today.
Worker-level `--lock-duration` / `--stall-interval` are on the roadmap;
until they land, rely on per-job `--max-stalled` plus the watchdog (or
systemd) for worker health.
### DO NOT pass `maxStalledCount` to `MinionWorker`
@@ -284,16 +284,16 @@ Use `gbrain jobs submit --max-stalled N` per-job instead.
### Zombie shell children
When the Bun worker crashes hard, child processes from shell jobs can
become zombies. The watchdog's 10 s `SIGTERM → SIGKILL` window covers the
shell handler's 5 s child-kill grace (`KILL_GRACE_MS`). For long-running
shell jobs, bump the watchdog's `sleep 10` to `sleep 30` so the worker
has time to flush in-flight jobs before the kill.
become zombies. The supervisor's SIGTERM → 35s drain → SIGKILL window
covers the shell handler's 5 s child-kill grace (`KILL_GRACE_MS`). For
long-running shell jobs, prefer timeouts via `--timeout-ms` on submit
over relying on hard kills.
## Smoke test
```bash
# Worker alive?
kill -0 $(head -n1 /tmp/gbrain-worker.pid) 2>/dev/null && echo ALIVE || echo DEAD
# Supervisor alive?
gbrain jobs supervisor status --json | jq .running
# Aggregate queue health.
gbrain jobs stats
@@ -304,20 +304,29 @@ gbrain jobs list --status active --limit 10
# Dead-lettered jobs.
gbrain jobs list --status dead --limit 10
# Shell handler registered? (stderr banner merged into log via 2>&1.)
grep "shell handler enabled" /tmp/gbrain-worker.log
# Shell handler registered? (check supervisor audit log or worker stderr.)
gbrain jobs supervisor status --json | jq '.worker_config.allow_shell_jobs'
```
## Uninstall
- **Option 1 (watchdog cron):** `crontab -e`, delete the watchdog line.
`kill $(head -n1 /tmp/gbrain-worker.pid) && rm /tmp/gbrain-worker.pid`.
Optionally `sudo rm /etc/gbrain.env /usr/local/bin/minion-watchdog.sh`.
- **Option 2 (inline `--follow`):** remove the cron entry. Nothing else to
clean up — temporary workers exit with their jobs.
- **Option 3 (systemd):** `sudo systemctl disable --now gbrain-worker`,
then `sudo rm /etc/systemd/system/gbrain-worker.service /etc/gbrain.env`,
then `sudo systemctl daemon-reload`.
- **Option 3 (Fly/Render/Railway):** delete the `worker` process from
`fly.toml` / `Procfile` and redeploy. Secrets set via `fly secrets`
persist until `fly secrets unset`.
**`gbrain jobs supervisor`** (foreground or `--detach`):
```bash
gbrain jobs supervisor stop
```
**systemd:**
```bash
sudo systemctl disable --now gbrain-worker
sudo rm /etc/systemd/system/gbrain-worker.service /etc/gbrain.env
sudo systemctl daemon-reload
```
**Fly / Render / Railway:** delete the `worker` process from `fly.toml`
/ `Procfile` and redeploy. Secrets set via `fly secrets` persist until
`fly secrets unset`.
**Inline `--follow`:** remove the cron entry. Nothing else to clean up
— temporary workers exit with their jobs.
+182
View File
@@ -0,0 +1,182 @@
# Multi-source brains
**A single gbrain database can hold multiple knowledge repos.** Each one
is a `source`: a logical brain-within-the-brain with its own slug
namespace, its own sync state, and its own federation policy. The rest
of this guide walks the three canonical scenarios.
## The three scenarios
### 1. Unified knowledge recall (wiki + gstack)
You have a personal wiki and a `gstack` checkout. Both belong to you,
both are knowledge you want your agent to recall across. When you ask
"what did I learn about X?" you want the best hit whether it lives in
the wiki or in a gstack plan.
```bash
# Register the gstack source, federate so it joins cross-source search
gbrain sources add gstack --path ~/.gstack --federated
# Pin the directory so `gbrain sync` knows which source it's walking
cd ~/.gstack && gbrain sources attach gstack
# Initial sync
gbrain sync --source gstack
# Now `gbrain search "retry budgets"` returns hits from BOTH wiki and
# gstack. Each result includes source_id so the agent can cite properly.
```
Result: wiki pages and gstack plans are separate (different source_ids,
different slug namespaces) but share the search surface.
### 2. Purpose-separated brains (yc-media + garrys-list)
You run two completely different content pipelines on the same backend.
YC Media covers portfolio news and founder profiles. Garry's List is
personal writing. You explicitly DON'T want them mixed in search — YC
portfolio content leaking into essay searches is a bug, not a feature.
```bash
# Two sources, both isolated (federated=false)
gbrain sources add yc-media --path ~/yc-media --no-federated
gbrain sources add garrys-list --path ~/writing --no-federated
# Pin each checkout directory
(cd ~/yc-media && gbrain sources attach yc-media)
(cd ~/writing && gbrain sources attach garrys-list)
# Sync each independently
gbrain sync --source yc-media
gbrain sync --source garrys-list
```
Result: searching from neither directory returns the `default` source
(your main brain). Searching from inside `~/yc-media` returns only yc-
media hits. Searching from inside `~/writing` returns only garrys-list.
Federation is opt-in, not leaked.
To search across them explicitly on demand:
```bash
gbrain search "tech layoffs" --source yc-media,garrys-list
```
### 3. Mixed (wiki federated + sessions isolated)
Your main wiki is federated with a few trusted sources. Your session
transcripts (coming in v0.18) land in a separate isolated source so
they don't dominate every search result.
```bash
# Federated sources
gbrain sources add gstack --path ~/.gstack --federated
# Isolated source (future v0.18 — sessions use this shape today for ingest)
gbrain sources add sessions --path ~/.claude/sessions --no-federated
```
## Resolution priority
When any command needs to pick a source, gbrain walks this list (highest
first):
1. Explicit `--source <id>` flag.
2. `GBRAIN_SOURCE` environment variable.
3. `.gbrain-source` dotfile in CWD or any ancestor directory.
4. A registered source whose `local_path` contains the CWD (longest
prefix wins for nested checkouts).
5. The brain-level default set via `gbrain sources default <id>`.
6. The seeded `default` source.
So inside `~/.gstack/plans/` on a brain that pinned `gstack` to
`~/.gstack` via `.gbrain-source`, `gbrain put-page` implicitly writes to
the `gstack` source. Outside any registered directory with no env/dotfile
set, it writes to the default.
## Federation flag
Every source row stores `config.federated: boolean` in its JSONB config.
| Value | Meaning |
|-------|---------|
| `true` | Source participates in unqualified `gbrain search "X"` results. |
| `false` (default for new sources) | Source only searched when explicitly named via `--source <id>` or qualified citation. |
The seeded `default` source is `federated=true` so pre-v0.17 brains
behave exactly as before — every page appears in search.
Flip later with `gbrain sources federate <id>` / `unfederate <id>`.
## Commands
Full subcommand reference:
```
gbrain sources add <id> --path <p> [--name <n>] [--federated|--no-federated]
Register a source. id: [a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?
gbrain sources list [--json] List all sources with page counts + federation state.
gbrain sources remove <id> [--yes] [--dry-run] [--keep-storage]
Cascade-delete a source (pages, chunks, timeline).
gbrain sources rename <id> <new-name>
Change display name only; id is immutable.
gbrain sources default <id> Set the brain-level default.
gbrain sources attach <id> Write .gbrain-source in CWD (like kubectl context).
gbrain sources detach Remove .gbrain-source from CWD.
gbrain sources federate <id>
gbrain sources unfederate <id>
```
## Citation format for agents
When agents receive multi-source results they MUST cite pages in
`[source-id:slug]` form. Example:
> You told me about the distillation protocol — see [wiki:topics/ai]
> and [gstack:plans/multi-repo] for where this came from.
The citation key is `sources.id` (immutable). Renaming a source via
`gbrain sources rename` changes the display name only; existing
citations keep working.
## Writing to a specific source
```bash
# Pass --source explicitly
gbrain put-page topics/ai ... --source wiki
# Or rely on the dotfile / env / CWD match
cd ~/.gstack && gbrain put-page plans/multi-repo ...
# → source auto-resolves to gstack
```
Reads span federated sources by default. Writes require a resolved
source (explicit, inferred, or default). The resolver never picks a
source silently when ambiguous — it errors with a clear fix.
## Upgrading an existing brain
`gbrain upgrade` runs the v16 + v17 migrations automatically. Your
existing pages all move under `source_id='default'`. Behavior is
unchanged until you add a second source.
To add one:
```bash
gbrain sources add gstack --path ~/.gstack --federated
cd ~/.gstack && gbrain sources attach gstack && gbrain sync
```
Two commands. The existing default source is untouched.
## Not in v0.18.0
- Session transcript ingest (`.jsonl`, raised size cap, session
PageType) — v0.18.
- Per-source retention/TTL (`gbrain sources prune`) — v0.18.
- ACL enforcement via caller-identity — v0.17.1.
- `gbrain sources import-from-github <url>` one-shot bootstrap — patch
release after the core plumbing stabilizes.
All of these build on the `sources` primitive shipped here.
+76
View File
@@ -0,0 +1,76 @@
# Queue operations runbook
"My queue looks wedged — what do I run?" The commands below are in the order
you probably want them. Shipped with v0.19.1 after a production incident
where the queue held for 90+ minutes before the operator noticed.
## First signal: jobs aren't running
```bash
gbrain doctor --json | jq '.checks[] | select(.name == "queue_health")'
```
`queue_health` flags two patterns:
- **stalled-forever**: active job whose `started_at` is older than 1h.
- **waiting-depth**: any per-name queue deeper than 10 (override via
`GBRAIN_QUEUE_WAITING_THRESHOLD`). Signals a missing `maxWaiting`.
## Triage commands
```bash
# Who's active right now?
gbrain jobs list --status active
# Who's waiting, biggest pile first?
gbrain jobs list --status waiting --limit 50
# What's wrong with a specific job?
gbrain jobs get <id>
```
## Rescue actions (in order of escalation)
```bash
# Force-kill a single stuck job:
gbrain jobs cancel <id>
# Clear a specific job entirely (last resort):
gbrain jobs delete <id>
# Health smoke on the mechanism itself:
gbrain jobs smoke --wedge-rescue
```
## What each subcheck means
- **stalled-forever** — A worker claimed a job, started executing, and has
held the row for over an hour. The wall-clock sweep evicts jobs past
2× `timeout_ms`; if one's still active, either no `timeout_ms` was set
or the sweep is newly deployed and this job predates it. Cancel it.
- **waiting-depth** — Submitters are piling up jobs faster than workers
drain them. Set `--max-waiting N` on the submission or on the programmatic
`queue.add()` call. If you want a taller pile, raise the threshold via
`GBRAIN_QUEUE_WAITING_THRESHOLD=50 gbrain doctor`.
## Self-check: is a worker even running?
```bash
# If you're running autopilot with --no-worker, check that your external
# worker (systemd / Docker / OpenClaw service-manager) is alive:
gbrain jobs list --status active | head -5
```
If the list is empty AND your submissions keep piling up, no worker is
claiming. Start one:
```bash
GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work --concurrency 4
```
## Follow-ups tracked for v0.20+
- B7 — `minion_workers` heartbeat table for ground-truth liveness (the
`--no-worker` probe and the dropped `queue_health` worker-heartbeat
subcheck both need this).
- B3 — `gbrain doctor --fix` learns to rescue queue wedges.
+154
View File
@@ -0,0 +1,154 @@
# RLS and you
Short version: every table in your gbrain's `public` schema needs Row Level
Security enabled. If one doesn't, `gbrain doctor` now fails, not warns, and the
process exits 1.
This guide explains why, what to do when you hit the check, and the escape hatch
for the cases where you really do want a table to stay readable by the anon key.
## Why RLS matters
Supabase exposes everything in the `public` schema via PostgREST. Whatever's
there is reachable by the anon key, which is a client-side secret by design.
If RLS is off on a public table, the anon key can read it. On anything sensitive
(auth tokens, chat history, financial data) that's an exfiltration vector, not
a footgun.
gbrain's service-role connection holds `BYPASSRLS`, so enabling RLS without
policies does NOT break gbrain itself. It just blocks the anon key's default
read. That's the security posture: deny-by-default to anon, full access for
the service role.
## What to do when doctor fails
Doctor's message names every table missing RLS and gives you a `ALTER TABLE`
line per table:
```
1 table(s) WITHOUT Row Level Security: expenses_ramp.
Fix: ALTER TABLE "public"."expenses_ramp" ENABLE ROW LEVEL SECURITY;
If a table should stay readable by the anon key on purpose, see
docs/guides/rls-and-you.md for the GBRAIN:RLS_EXEMPT comment escape hatch.
```
99% of the time, you want the fix. Run the SQL. Re-run `gbrain doctor`. Done.
## The 1% case: deliberate exemption
Sometimes a public table is supposed to be readable by the anon key. An
analytics view backing a public dashboard. A read-only reference table. A
plugin that ships its own frontend and intentionally uses the anon key for
reads.
gbrain has an escape hatch for these. It is deliberately painful to set up.
That is the feature.
### The format
```sql
-- In psql, connected as a BYPASSRLS role (e.g. postgres):
COMMENT ON TABLE public.your_table IS
'GBRAIN:RLS_EXEMPT reason=<why this is anon-readable on purpose>';
```
Rules:
- The comment value MUST start with `GBRAIN:RLS_EXEMPT` (case-sensitive).
- It MUST include `reason=` followed by at least 4 characters of justification.
- No other prefix, no checkbox in a config file, no environment variable. Only
a Postgres table comment counts.
- If RLS is also off on the table (which it must be for the anon key to
actually read), you also need `ALTER TABLE ... DISABLE ROW LEVEL SECURITY;`
explicitly. Disabling alone is not enough; the comment is what tells doctor
this is intentional.
### Example
```sql
ALTER TABLE public.expenses_ramp DISABLE ROW LEVEL SECURITY;
COMMENT ON TABLE public.expenses_ramp IS
'GBRAIN:RLS_EXEMPT reason=analytics-only, anon-readable ok, owner=garry, 2026-04-22';
```
After that, `gbrain doctor` reports:
```
rls: ok — RLS enabled on 20/21 public tables (1 explicitly exempt: expenses_ramp)
```
Note that every subsequent run re-enumerates your exemptions by name. That's
intentional. The escape hatch is not a one-time sign-off, it's a recurring
reminder. If you ever want to know which tables are open, run `gbrain doctor`.
## Why SQL and not a CLI subcommand
gbrain does NOT ship a `gbrain rls-exempt add <table>` command. A CLI command
would make it easy for an agent to silently open a table to anon reads. The
comment-in-psql requirement forces the operator to type the justification
in SQL, which is:
- Visible in shell history.
- Visible in a git-tracked schema dump.
- Visible in `pg_dump` output the next time you restore.
- Visible in `gbrain doctor` output on every run.
An agent CAN still run the SQL, but it can't do it without the user seeing the
action. That's the "write it in blood" design.
## Auditing exemptions later
To see every exemption in the current DB:
```sql
SELECT
c.relname AS table_name,
obj_description(c.oid, 'pg_class') AS comment
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public'
AND c.relkind = 'r'
AND obj_description(c.oid, 'pg_class') LIKE 'GBRAIN:RLS_EXEMPT%';
```
If that list is longer than you remember signing off on, that's the signal.
## Removing an exemption
Just drop the comment and re-enable RLS:
```sql
ALTER TABLE public.expenses_ramp ENABLE ROW LEVEL SECURITY;
COMMENT ON TABLE public.expenses_ramp IS NULL;
```
`gbrain doctor` stops listing the table as exempt and goes back to checking
it like any other.
## PGLite
If you're on PGLite (the zero-config default), doctor skips this check
entirely: PGLite is embedded, single-user, and has no PostgREST in front of
it. The public-schema-exposure risk doesn't exist. You'll see:
```
rls: ok — Skipped (PGLite — no PostgREST exposure, RLS not applicable)
```
If you migrate to Supabase or self-hosted Postgres later, the check starts
running and will flag any table that came over without RLS.
## Self-hosted Postgres
If you're running Postgres without PostgREST in front, the anon-key exposure
doesn't apply. But gbrain still fails the check on missing RLS, because:
- The framing is "RLS on all public tables" is a gbrain security invariant,
not a Supabase-specific workaround.
- The `ALTER TABLE ... ENABLE RLS` fix is harmless on any Postgres: it only
constrains non-bypass roles, which gbrain doesn't use.
- If you ever put PostgREST or a similar tool in front later, the guard is
already in place.
If this framing doesn't fit your deployment, file an issue with the specifics
so we can decide whether a self-hosted-exempt mode is justified.
+105
View File
@@ -0,0 +1,105 @@
# Pre-commit hook for brain repos (v0.22.4+)
`gbrain frontmatter install-hook` installs a git pre-commit hook in your
brain source's repo that runs `gbrain frontmatter validate` against staged
`.md` and `.mdx` files. Malformed frontmatter blocks the commit. Bypass with
`git commit --no-verify`.
## What the hook catches
The same seven validation classes the `frontmatter-guard` skill and
`gbrain doctor`'s `frontmatter_integrity` subcheck report:
| Code | What it catches |
|-------------------|---------------------------------------------------------------------|
| `MISSING_OPEN` | File doesn't start with `---` |
| `MISSING_CLOSE` | No closing `---` before first heading |
| `YAML_PARSE` | YAML failed to parse (syntax or structure) |
| `SLUG_MISMATCH` | `slug:` in frontmatter doesn't match path-derived slug |
| `NULL_BYTES` | Binary corruption (`\x00`) anywhere in the content |
| `NESTED_QUOTES` | `title: "outer "inner" outer"` shape that breaks YAML |
| `EMPTY_FRONTMATTER` | `---` ... `---` with nothing meaningful between |
## Install
For all registered sources that are git repos:
```bash
gbrain frontmatter install-hook
```
For one source:
```bash
gbrain frontmatter install-hook --source <id>
```
For force-overwrite of an existing pre-commit hook (writes a `.bak`):
```bash
gbrain frontmatter install-hook --force
```
The hook lands at `<source>/.githooks/pre-commit`. If `core.hooksPath` is
unset, the install also runs `git config core.hooksPath .githooks` so the
hook is picked up without manual git config.
## Bypass
Standard git escape hatch:
```bash
git commit --no-verify
```
This skips ALL pre-commit hooks. Use sparingly — the next time the user
runs `gbrain doctor`, the issues will surface.
## Uninstall
```bash
gbrain frontmatter install-hook --uninstall
```
If a `.bak` was saved during install, it's restored as the active hook.
Otherwise the hook is removed cleanly.
## Behavior on machines without gbrain installed
The hook script checks for `gbrain` on `$PATH`. When missing, it prints a
one-line warning to stderr and exits 0 — commits aren't blocked just because
a developer hasn't installed gbrain locally. Once gbrain is installed, the
hook resumes blocking malformed pages.
## For downstream agent forks
If your fork (Wintermute, Hermes, OpenClaw) wraps gbrain in a host repo
that's not the brain repo itself, you may want a separate hook strategy:
- **Brain repo IS the host repo** (gbrain skills + brain pages in one repo):
install via `gbrain frontmatter install-hook` as above.
- **Brain repo is a separate registered source** (e.g. `~/brain` registered
as a source, host repo is `~/agent-fork`): install in the brain repo only;
agent-fork code doesn't need this hook.
- **Brain repo is auto-generated** (e.g. by a sync daemon writing to a
bucket): skip the hook entirely; gate at the writer instead via
`import { writeBrainPage } from 'gbrain/brain-writer'` (planned in a
later release; currently the CLI is the surface).
## How it fits into the broader frontmatter pipeline
```
agent writes a page git commit doctor scan
↓ ↓ ↓
[source content] → [pre-commit hook validates] → [frontmatter_integrity check]
↓ ↓ ↓
raw file on disk blocks malformed commits surfaces existing issues
`gbrain frontmatter validate
<source-path> --fix`
(writes .bak backups)
```
The hook is the write-time gate; doctor is the audit gate; the CLI is the
fix tool. They share `parseMarkdown(..., {validate:true})` as the single
source of truth for what counts as malformed.
-13
View File
@@ -1,13 +0,0 @@
{
"generated_at": "2026-04-18T04:13:16.027Z",
"model": "claude-opus-4-5",
"pricing": {
"input_per_m": 15,
"output_per_m": 75
},
"inputTokens": 18359,
"outputTokens": 38228,
"costUsd": 3.1424849999999998,
"calls": 49,
"files_total": 240
}
@@ -1,25 +0,0 @@
{
"slug": "companies/accel-5",
"type": "company",
"title": "Accel - Global Venture Capital Firm",
"compiled_truth": "Accel is one of the most established venture capital firms in the world, with a track record spanning over four decades. Founded in 1983, the firm has evolved from a Silicon Valley stalwart into a truly global operation with offices in Palo Alto, London, and Bangalore. They've backed some of the most consequential technology companies of the past two decades, including Facebook, Spotify, Slack, and Dropbox.\n\nThe firm operates across multiple stages, though they're perhaps best known for their Series A and Series B investments. Accel manages billions in assets across various funds, with recent vintages exceeding $3 billion for their US and Europe-focused vehicles. Their investment thesis tends to favor founders building category-defining companies in enterprise software, consumer tech, fintech, and increasingly, AI infrastructure.\n\nAccel's partnership model emphasizes deep sector expertise. Partners like Sonali De Rycker have built formidable reputations in European fintech, while others focus on developer tools or consumer applications. The firm has been notably active in the generative AI wave, making early bets on companies building foundational models and application layers. They've developed strong relationships with accelerators like [Y Combinator](companies/y-combinator) and often co-invest alongside firms such as [Andreessen Horowitz](companies/a16z) on competitive deals.\n\nRecent years have seen Accel double down on international expansion. Their India fund has become one of the most active institutional investors in the subcontinent, backing companies like Flipkart and Swiggy before they became household names. The London office continues to punch above its weight in European tech circles.\n\nThe firm's culture is often described as founder-friendly but rigorous. They're known for taking board seats seriously and providing operational support beyond just capital. Accel's brand carries significant weight in fundraising conversations—a term sheet from them often signals quality to follow-on investors. Critics sometimes note their portfolio can feel conservative compared to newer entrants, but longevity has its advantages. They've seen multiple market cycles and tend to maintain disciplined valuations even in frothy markets.",
"timeline": [
"- **2021-03-15** | Accel closes $3 billion early-stage fund, largest in firm history at the time",
"- **2021-09-22** | Led Series B for enterprise AI startup alongside [Andreessen Horowitz](companies/a16z)",
"- **2022-04-10** | Opens expanded London office to support growing European portfolio",
"- **2022-11-08** | Partner Rich Wong speaks at Web Summit on enterprise software trends",
"- **2023-02-14** | Announces $650 million India-focused fund, sixth in the region",
"- **2023-08-30** | Leads seed round for [Y Combinator](companies/y-combinator) batch company building AI code review tools",
"- **2024-01-19** | Accel publishes annual Euroscape report showing record European unicorn creation",
"- **2024-06-05** | Makes significant investment in robotics startup focused on warehouse automation",
"- **2025-02-11** | Closes latest growth fund at $4.2 billion amid competitive fundraising environment",
"- **2025-09-03** | Hosts annual CEO summit in Portofino, bringing together 80+ portfolio founders"
],
"_facts": {
"type": "company",
"slug": "companies/accel-5",
"name": "Accel",
"category": "vc",
"industry": "venture capital"
}
}
-25
View File
@@ -1,25 +0,0 @@
{
"slug": "companies/acme-0",
"type": "company",
"title": "Acme",
"compiled_truth": "Acme is a robotics startup founded in 2021 by [Mia Brown](people/mia-brown-0), who previously spent nearly a decade in industrial automation before striking out on her own. The company focuses on developing modular robotic systems for small and mid-sized warehouses—an underserved market segment that larger players have largely ignored. Their flagship product, the Acme Flex Unit, is a mobile picking robot that can be deployed in facilities without major infrastructure changes.\n\nThe startup has attracted notable backing from angel investors including [Chris Jackson](people/chris-jackson-91) and [Ian Anderson](people/ian-anderson-105), both of whom participated in the seed round closed in early 2022. Jackson in particular has been hands-on, joining several board meetings and making introductions to potential enterprise customers. Acme raised a modest $2.3M initially, deliberately staying lean while proving out the core technology.\n\nMia Brown serves as CEO and remains deeply involved in product development. She's known for an engineering-first approach to company building, often spending time on the factory floor alongside her small team. The company currently employs around 25 people, mostly engineers, operating out of a converted warehouse space in Austin. Acme has been quiet about expansion plans but insiders suggest a Series A is in the works for late 2025.\n\nThe robotics market is crowded, yet Acme has carved out a niche by targeting businesses too small for enterprise solutions but too large for manual operations alone. Early customers include regional e-commerce fulfillment centers and a few specialty food distributors. Retention has been strong, with several pilots converting to full deployments.\n\nRecent moves include a partnership with a logistics software provider to integrate Acme's robots into broader warehouse managment systems. The company also hired its first dedicated sales lead in Q1 2025, signaling a shift toward scaling comercial operations. Despite limited public visibility, Acme has built a reputation in robotics circles for reliable hardware and responsive support.",
"timeline": "- **2021-06-15** | Acme incorporated in Delaware by [Mia Brown](people/mia-brown-0)\n- **2022-02-10** | Closed $2.3M seed round led by [Chris Jackson](people/chris-jackson-91) and [Ian Anderson](people/ian-anderson-105)\n- **2022-09-01** | First prototype of Acme Flex Unit completed\n- **2023-03-22** | Signed pilot agreement with regional fulfillment center in Texas\n- **2023-11-08** | Expanded team to 15 employees, opened Austin facility\n- **2024-04-17** | Converted three pilot customers to full commercial deployments\n- **2024-10-30** | Announced integration partnership with WarehouseOS software platform\n- **2025-01-14** | Hired first dedicated head of sales, marking commercial scale-up\n- **2025-06-02** | [Mia Brown](people/mia-brown-0) spoke at RoboTech Summit on modular automation\n- **2025-11-20** | Series A discussions reportedly underway with multiple VC firms",
"_facts": {
"type": "company",
"slug": "companies/acme-0",
"name": "Acme",
"category": "startup",
"industry": "robotics",
"founded_year": 2021,
"founders": [
"people/mia-brown-0"
],
"investors": [
"people/chris-jackson-91",
"people/ian-anderson-105"
],
"employees": [
"people/chris-smith-110"
]
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/acme-labs-50",
"type": "company",
"title": "Acme Labs",
"compiled_truth": "Acme Labs is a cybersecurity startup founded in 2019 by [Ian Kim](people/ian-kim-50), a serial entrepreneur with deep roots in enterprise security software. The company emerged from Kim's frustration with legacy endpoint protection tools that couldn't keep pace with modern threat vectors. Based out of Austin, Texas, Acme has grown from a three-person operation to a team of roughly 45 engineers and security researchers.\n\nThe company's flagship product is a real-time threat detection platform that uses behavioral analysis to identify anomalies before they escalate into full breaches. Unlike traditional signature-based approaches, Acme's system learns the normal patterns of network traffic and user behavior, flagging deviations that might indicate compromise. Early customers were mid-market financial services firms, though the company has since expanded into healthcare and logistics verticals.\n\nFunding came relatively early. [Helen Martinez](people/helen-martinez-87) led the seed round in late 2020, bringing not just capital but also her extensive network in enterprise software distribution. Martinez has remained closely involved, attending board meetings and occasionally making introductions to potential strategic partners. The Series A followed in 2022, though terms were not publicly disclosed.\n\nOn the advisory side, [Wendy Wilson](people/wendy-wilson-170) joined in 2021 to help shape go-to-market strategy. Wilson's backgorund in scaling B2B SaaS companies proved invaluable as Acme transitioned from founder-led sales to a more structured revenue organization. She's credited with pushing the team to focus on a narrower ICP rather than chasing every inbound lead.\n\nAcme Labs has built a reputation for technical depth. Their engineering blog regularly publishes threat research, and several team members speak at conferences like DEF CON and BSides. The culture leans scrappy—Kim is known for keeping overhead low and reinvesting heavily into R&D. Recent chatter suggests the company is exploring an AI-powered SOC assistant, though nothing has been formally anounced. Competition remains fierce from both established players and well-funded startups, but Acme's focus on mid-market customers gives them a defensible niche.",
"timeline": "- **2019-03-12** | Acme Labs incorporated in Delaware; [Ian Kim](people/ian-kim-50) begins building initial prototype\n- **2019-11-04** | First paying customer signed — a regional credit union in Texas\n- **2020-09-18** | Seed round closed with [Helen Martinez](people/helen-martinez-87) leading the investment\n- **2021-02-22** | [Wendy Wilson](people/wendy-wilson-170) joins as strategic advisor\n- **2021-08-30** | Acme releases v2.0 of threat detection platform with behavioral analytics engine\n- **2022-04-15** | Series A funding completed; team expands to 30 employees\n- **2023-06-09** | Ian Kim delivers keynote at RSA Conference on zero-trust architecture\n- **2024-01-17** | Partnership announced with major SIEM vendor for native integration\n- **2024-11-03** | Acme Labs crosses $10M ARR milestone\n- **2025-07-21** | Internal demo of AI-powered SOC assistant shown to select customers",
"_facts": {
"type": "company",
"slug": "companies/acme-labs-50",
"name": "Acme Labs",
"category": "startup",
"industry": "cybersecurity",
"founded_year": 2019,
"founders": [
"people/ian-kim-50"
],
"investors": [
"people/helen-martinez-87"
],
"employees": [
"people/vera-martinez-160"
],
"advisors": [
"people/wendy-wilson-170"
]
}
}
@@ -1,15 +0,0 @@
{
"slug": "companies/amazon-3",
"type": "company",
"title": "Amazon - Cybersecurity Acquirer",
"compiled_truth": "Amazon, founded in 1998, has evolved far beyond its origins as an online bookstore to become one of the most formidable players in the technology sector. While most know the company for its e-commerce dominance and AWS cloud infrastructure, Amazon has quietly built a substantial presence in cybersecurity through strategic acquisitions and internal development.\n\nThe company's approach to cybersecurity M&A has been methodical and often under the radar. Rather than making splashy billion-dollar deals that attract media attention, Amazon tends to acquire smaller, specialized firms that can be integrated into its existing AWS security stack. This strategy allows them to enhance offerings like AWS Shield, GuardDuty, and Security Hub without the integration headaches that plague larger mergers.\n\nAmazon's cybersecurity ambitions are driven partly by necesity—protecting its massive cloud infrastructure and the millions of businesses that depend on it requires constant innovation. The company processes an astronomical volume of security events daily, giving it unique datasets for training threat detection models. Some industry observers beleive this data advantage makes Amazon a sleeping giant in the security space.\n\nRecent moves suggest the company is getting more aggressive. They've been spotted at major security conferences with larger acquisition teams, and rumors persist about interest in several endpoint detection startups. The hiring of former NSA and CISA officials into senior AWS security roles signals a maturation of their strategy.\n\nCompetition with [Microsoft](companies/microsoft) in the cloud security space has intensified, with both giants racing to offer comprehensive security platforms that reduce customers' need for third-party tools. Amazon's relationship with specialized security vendors is complicated—they partner with many through the AWS Marketplace while simultaneously building competing capabilities.\n\nThe firm maintains close ties with government contractors and has pursued FedRAMP certifications aggressively. Their work with [Palantir](companies/palantir) on certain government cloud initiatives demonstrates Amazon's willingness to collaborate when strategic interests align, though the relationship has had its tense moments over competing contract bids.",
"timeline": "- **2021-03-15** | Amazon acquires small threat intelligence startup for undisclosed sum, team absorbed into AWS Security division\n- **2021-09-22** | Launched AWS Security Lake at re:Invent, consolidating security data management capabilities\n- **2022-04-08** | Hired former CISA deputy director to lead government security initiatives\n- **2022-11-30** | Announced expanded partnership with [Microsoft](companies/microsoft) on cross-cloud security standards, surprising industry observers\n- **2023-06-14** | Acquisition of Israeli-based API security firm closes, adding to AppSec portfolio\n- **2023-12-01** | AWS Security Hub surpasses 50,000 enterprise customers milestone\n- **2024-05-19** | Internal memo leaked showing renewed focus on endpoint security acquisitions\n- **2024-10-03** | Joint threat intelligence sharing agreement signed with [Palantir](companies/palantir) for federal contracts\n- **2025-02-28** | Rumored in late-stage talks with two identity management startups\n- **2025-08-11** | Opened dedicated cybersecurity R&D center in Austin, Texas",
"_facts": {
"type": "company",
"slug": "companies/amazon-3",
"name": "Amazon",
"category": "acquirer",
"industry": "cybersecurity",
"founded_year": 1998
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/anchor-28",
"type": "company",
"title": "Anchor - Data Infrastructure Startup",
"compiled_truth": "Anchor is a data infrastructure startup founded in 2021 by [Carol Wilson](people/carol-wilson-28), a veteran engineer who previously spent nearly a decade building distributed systems at major tech companies. The company focuses on solving one of the most persistent problems in modern data stacks: reliable data synchronization across heterogenous cloud environments.\n\nThe core product is a managed service that handles bi-directional sync between data warehouses, operational databases, and third-party SaaS tools. Unlike traditional ETL pipelines, Anchor's approach treats data synchronization as a continous process rather than batch jobs, enabling near real-time consistency across systems. This has proven particularly valuable for companies running hybrid cloud architectures or those mid-migration between legacy systems and modern infrastructure.\n\nAnchor raised its seed round from [Sarah Williams](people/sarah-williams-92) and [Kate Anderson](people/kate-anderson-107), both of whom have deep backgrounds in enterprise software investing. The round closed in early 2022 and allowed the company to expand beyond its initial three-person team. Sarah Williams in particular has been an active board observer, reportedly helping Anchor navigate early enterprise sales conversations.\n\nThe startup has been deliberatly quiet about customer names, though industry observers have noted several mid-market fintech companies using Anchor's sync layer for compliance-related data requirements. Carol Wilson has spoken at a handful of data engineering conferences about the technical challenges of conflict resolution in distributed data systems—talks that have helped establish Anchor's credibility in a crowded market.\n\nGrowth has been steady if not explosive. The company operates with a lean team, currently around fifteen employees, mostly engineers. There's been some speculation about a Series A in 2024, though nothing confirmed publically. Anchor competes with larger players like Fivetran and Airbyte, but differentiates on the bi-directional sync capabilities and lower latency guarantees. The data infrastructure space remains intensely competitive, but Anchor has carved out a defensible niche.",
"timeline": "- **2021-03-15** | Anchor incorporated in Delaware by [Carol Wilson](people/carol-wilson-28)\n- **2021-06-22** | First working prototype of bi-directional sync engine completed\n- **2022-01-18** | Closed seed round led by [Sarah Williams](people/sarah-williams-92) and [Kate Anderson](people/kate-anderson-107)\n- **2022-08-03** | Launched private beta with five design partners\n- **2023-02-11** | Carol Wilson delivered keynote on distributed sync at DataEngConf Austin\n- **2023-07-29** | General availability launch; pricing tiers announced\n- **2023-11-14** | Reached 50 paying customers milestone\n- **2024-04-08** | Opened second office in Denver for engineering expansion\n- **2024-09-22** | Partnership announced with major cloud provider (details under NDA)\n- **2025-01-30** | Anchor featured in industry report on emerging data infrastructure vendors",
"_facts": {
"type": "company",
"slug": "companies/anchor-28",
"name": "Anchor",
"category": "startup",
"industry": "data infrastructure",
"founded_year": 2021,
"founders": [
"people/carol-wilson-28"
],
"investors": [
"people/sarah-williams-92",
"people/kate-anderson-107"
],
"employees": [
"people/tara-hernandez-138"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/andreessen-horowitz-2",
"type": "company",
"title": "Andreessen Horowitz",
"compiled_truth": "Andreessen Horowitz, widely known as a16z, is one of the most influential venture capital firms in Silicon Valley and arguably the world. Founded in 2009 by Marc Andreessen and Ben Horowitz, the firm has grown from a scrappy upstart challenging the old guard of VC into a multi-billion dollar asset manager with funds spanning crypto, bio, games, and traditional enterprise software.\n\nThe firm's thesis has always been rooted in the belief that software is eating the world—a phrase Marc coined in his famous 2011 Wall Street Journal essay. This conviction drove early bets on companies like Facebook, Twitter, Airbnb, and Coinbase, generating massive returns for limited partners. a16z pioneered the \"founder-friendly\" approach to venture capital, offering not just capital but an entire platform of services: recruiting, marketing, executive coaching, and regulatory expertise.\n\nIn recent years, Andreessen Horowitz has leaned heavily into crypto and web3, raising multiple dedicated funds totaling billions of dollars. This bet has been controversial—critics argue the firm is too bullish on speculative assets, while supporters see it as visionary positioning for the next computing platform. The firm also expanded into consumer health through a16z Bio and doubled down on American Dynamism, a thesis around backing companies building in defense, aerospace, and manufacturing.\n\nThe partnership includes heavyweights like Chris Dixon (leading crypto), Vijay Pande (bio), and Andrew Chen (consumer). Marc remains a polarizing figure on social media, often wading into political and cultural debates that generate significant attention. Some view this as distraction, others as authentic engagement. Ben Horowitz has focused more on cultural content, including his popular book \"The Hard Thing About Hard Things.\"\n\na16z competes fiercely with firms like [Sequoia Capital](companies/sequoia-capital) and [General Catalyst](companies/general-catalyst) for the best deals. Their approach to content marketing—podcasts, newsletters, extensive blog posts—has been widely imitated across the industry. The firm essentially invented the VC-as-media-company playbook that's now standard practice.",
"timeline": "- **2021-06-24** | a16z announces $2.2B Crypto Fund III, largest dedicated crypto fund at the time\n- **2022-01-18** | Led Series B for infrastructure startup alongside [General Catalyst](companies/general-catalyst)\n- **2022-05-12** | Launches $4.5B Crypto Fund IV despite market downturn; doubles down on web3 thesis\n- **2023-03-09** | Opens first international office in London, signals expansion beyond Silicon Valley\n- **2023-08-22** | American Dynamism fund invests in defense tech startup building autonomous systems\n- **2024-02-14** | Marc Andreessen testifies before Senate committee on AI regulation concerns\n- **2024-07-30** | a16z Bio leads $180M Series C for longevity-focused biotech company\n- **2024-11-05** | Partnership meeting discusses competitive positioning against [Sequoia Capital](companies/sequoia-capital) in AI deals\n- **2025-04-18** | Closes Fund VIII at $7.2B, largest general fund in firm history\n- **2025-09-02** | Chris Dixon announces new thesis around decentralized AI infrastructure",
"_facts": {
"type": "company",
"slug": "companies/andreessen-horowitz-2",
"name": "Andreessen Horowitz",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,30 +0,0 @@
{
"slug": "companies/apex-18",
"type": "company",
"title": "Apex",
"compiled_truth": "Apex is an AI infrastructure startup founded in 2018 by [Nina Rodriguez](people/nina-rodriguez-18), who saw early on that the bottleneck for machine learning wouldn't be algorithms but the underlying compute and data plumbing. The company builds tools that help enterprises manage GPU clusters, optimize model training pipelines, and reduce the staggering costs associated with running large-scale AI workloads. Their flagship product, ApexCore, has become quietly essential for a number of mid-sized ML teams who can't afford to waste cycles on infrastructure headaches.\n\nThe company operates out of Austin, with a small satellite office in San Francisco. Apex has stayed relatively lean—around 45 employees as of late 2024—but punches above its weight in terms of customer logos. Rodriguez has been deliberate about not chasing hypergrowth, preferring sustainable unit economics over flashy fundraising rounds. That said, the company has brought on notable backers including [Priya Taylor](people/priya-taylor-85) and [Kevin Taylor](people/kevin-taylor-102), both of whom participated in the Series A back in 2021.\n\nOn the advisory side, Apex leans on [Tina Wang](people/tina-wang-179) for go-to-market strategy and [Yara Singh](people/yara-singh-195) for technical architecture decisions. Wang's experience scaling enterprise sales orgs has been particulalry valuable as Apex moves upmarket toward Fortune 500 accounts. Singh, meanwhile, has helped the engineering team navigate some gnarly distributed systems challenges—especially around fault tolerance in multi-cloud deployments.\n\nRecent moves suggest Apex is positioning itself for a broader platform play. In early 2025, they aquired a small observability startup to bolster their monitoring capabilities, and rumors persist about a Series B in the works. Rodriguez has been cagey about fundraising plans in interviews, but insiders say the company is fielding inbound interest from several growth-stage funds.\n\nApex isn't the flashiest name in AI infrastructure, but that's sort of the point. They build the boring stuff that makes the exciting stuff possible.",
"timeline": "- **2018-06-12** | Apex founded by Nina Rodriguez in Austin, Texas with initial focus on GPU cluster management\n- **2021-03-08** | Closed Series A led by [Priya Taylor](people/priya-taylor-85) with participation from [Kevin Taylor](people/kevin-taylor-102)\n- **2022-01-19** | Launched ApexCore v1.0, the company's flagship infrastructure optimization platform\n- **2022-09-14** | [Tina Wang](people/tina-wang-179) joined as strategic advisor to help scale enterprise sales motion\n- **2023-04-22** | Apex hits 100 paying customers milestone, majority in healthcare and fintech verticals\n- **2023-11-30** | [Yara Singh](people/yara-singh-195) comes on as technical advisor, focusing on multi-cloud architecture\n- **2024-05-17** | Nina Rodriguez keynotes at MLOps World conference in Toronto\n- **2024-10-03** | Opened small SF office to be closer to key customers and talent pool\n- **2025-02-11** | Acquired observability startup CloudLens for undisclosed amount\n- **2025-04-28** | Announced ApexCore 3.0 with native support for next-gen NVIDIA chips",
"_facts": {
"type": "company",
"slug": "companies/apex-18",
"name": "Apex",
"category": "startup",
"industry": "AI infrastructure",
"founded_year": 2018,
"founders": [
"people/nina-rodriguez-18"
],
"investors": [
"people/priya-taylor-85",
"people/kevin-taylor-102"
],
"employees": [
"people/will-liu-128"
],
"advisors": [
"people/tina-wang-179",
"people/yara-singh-195",
"people/noah-williams-198"
]
}
}
@@ -1,15 +0,0 @@
{
"slug": "companies/apple-4",
"type": "company",
"title": "Apple",
"compiled_truth": "Apple is a crypto-focused acquirer that has been making waves in the digital asset space since its founding in 1999. Despite sharing its name with the famous consumer electronics giant, this Apple operates in an entirely different arena—specializing in acquiring and integrating promising blockchain and cryptocurrency ventures into its portfolio.\n\nThe company has positioned itself as a strategic consolidator in the fragmented crypto landscape, targeting startups with strong technology but weak go-to-market execution. Their acquisition thesis centers on identifying undervalued protocols and teams, then providing the capital and operational support needed to scale. Apple's approach has been described as \"patient capital meets aggressive integration,\" a philosophy that has earned them both admirers and critics in the space.\n\nOver the past few years, Apple has expanded its focus beyond pure protocol acquisitions to include infrastructure plays and DeFi platforms. The firm maintains close relationships with several venture partners and has been known to co-invest alongside firms like [Paradigm](companies/paradigm-capital) on select deals. Their due dilligence process is notoriously thorough, often taking 6-8 months before closing.\n\nLeadership at Apple tends to keep a low profile, though insiders describe the culture as intensely analytical. The company employs a mix of traditional M&A professionals and crypto-native talent, creating what some have called a \"hybrid vigor\" in their dealmaking approach. They've been particularly active in the layer-2 scaling space and have made several aqusitions targeting zero-knowledge proof technology.\n\nApple's recent moves suggest a pivot toward institutional-grade custody and compliance solutions, likely anticipating regulatory clarity in major markets. They've been spotted at industry events networking with [Coinbase Ventures](companies/coinbase-ventures) representatives, fueling speculation about potential partnerships or joint ventures. The firm reportedly manages a war chest exceeding $800 million dedicated to strategic acquisitions, though exact figures remain unconfirmed.\n\nDespite the 2022-2023 crypto winter, Apple maintained its acquisition pace, viewing the downturn as a buying opportunity. This contrarian stance has positioned them well heading into the 2024-2025 market recovery.",
"timeline": "- **2021-03-15** | Apple closes Series B funding round, raising $150M to accelerate acquisition strategy\n- **2021-09-22** | Acquired ZK-proof startup Luminal Labs for undisclosed sum\n- **2022-04-08** | Partnership announced with [Paradigm](companies/paradigm-capital) for co-investment on infrastructure deals\n- **2022-11-30** | Maintained hiring despite market downturn, adding 12 new analysts\n- **2023-06-14** | Completed acquisition of DeFi protocol Streamflow, their largest deal to date\n- **2023-12-01** | Apple representatives spotted meeting with [Coinbase Ventures](companies/coinbase-ventures) team in NYC\n- **2024-05-19** | Launched dedicated compliance-tech acquisition vertical\n- **2024-10-07** | Acquired custody solution provider VaultEdge for $45M\n- **2025-02-22** | Rumored to be in late-stage talks for major layer-2 protocol acquisition\n- **2025-04-11** | Company retreat held in Miami, strategy sessions focused on 2025-2026 deployment targets",
"_facts": {
"type": "company",
"slug": "companies/apple-4",
"name": "Apple",
"category": "acquirer",
"industry": "crypto",
"founded_year": 1999
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/beacon-10",
"type": "company",
"title": "Beacon",
"compiled_truth": "Beacon is a cybersecurity startup founded in 2018 by [David Wang](people/david-wang-10), a serial entrepreneur with deep expertise in network security and threat detection. The company has positioned itself as a next-generation endpoint protection platform, focusing primarily on small and medium-sized businesses that lack the resources for enterprise-grade security teams.\n\nThe core product offering centers around an AI-driven threat detection engine that monitors network traffic, user behavior, and system anomalies in real-time. Unlike traditional antivirus solutions, Beacon's approach emphasizes behavioral analysis over signature-based detection, allowing it to catch zero-day exploits and novel attack vectors that would slip past conventional defenses. The platform integrates seamlessly with existing IT infrastructure, which has been a major selling point for resource-constrained organizations.\n\nIn terms of backing, Beacon secured early-stage funding from [Rachel Brown](people/rachel-brown-95), who recognized the growing market opportunity as cyberattacks increasingly target smaller companies. Rachel's involvment brought not just capital but also valuable connections in the enterprise software space. The company has since grown to approximately 45 employees, with offices in San Francisco and a small engineering hub in Austin.\n\n[Julia Chen](people/julia-chen-181) serves as an advisor to the company, providing strategic guidance on go-to-market strategy and partnerships. Her background in scaling B2B SaaS companies has proven invaluable as Beacon transitions from early adopter customers to broader market penetration.\n\nRecent developments include the launch of Beacon Shield, a managed detection and response (MDR) service that pairs the software platform with 24/7 human analysts. This move signals the company's ambition to capture more enterprise clients who want hands-on support. David has been vocal about the need for democratizing cybersecurity—making sophisticated protection accesible to organizations that aren't Fortune 500 companies.\n\nThe competitive landscape remains challenging, with established players like CrowdStrike and newer entrants constantly innovating. However, Beacon's focused positioning and competitive pricing have carved out a loyal customer base. The company processes over 2 billion security events daily across its customer network.",
"timeline": "- **2018-03-15** | Beacon incorporated in Delaware; [David Wang](people/david-wang-10) begins building initial prototype\n- **2019-01-22** | Closed seed round led by [Rachel Brown](people/rachel-brown-95), raising $2.4M\n- **2020-06-08** | Launched v1.0 of endpoint protection platform; first 50 paying customers onboarded\n- **2021-09-14** | [Julia Chen](people/julia-chen-181) joins as strategic advisor\n- **2022-04-03** | Series A closed at $12M; expanded engineering team to 30 people\n- **2023-02-17** | Beacon Shield MDR service announced at RSA Conference\n- **2023-11-29** | Partnered with major MSP provider, adding 200+ SMB customers\n- **2024-08-12** | Austin engineering office opened; David Wang keynotes at Black Hat\n- **2025-03-05** | Surpassed 1,500 enterprise customers milestone",
"_facts": {
"type": "company",
"slug": "companies/beacon-10",
"name": "Beacon",
"category": "startup",
"industry": "cybersecurity",
"founded_year": 2018,
"founders": [
"people/david-wang-10"
],
"investors": [
"people/rachel-brown-95"
],
"employees": [
"people/ulrich-kim-120"
],
"advisors": [
"people/julia-chen-181"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/benchmark-3",
"type": "company",
"title": "Benchmark Capital",
"compiled_truth": "Benchmark is one of Silicon Valley's most storied venture capital firms, known for its disciplined approach and equal partnership structure. Founded in 1995, the firm has maintained a remarkably consistent strategy: small funds, equal economics among partners, and a focus on early-stage investing. Unlike many of its peers who have ballooned into multi-stage asset managers, Benchmark has stayed deliberately small.\n\nThe firm operates out of Woodside, California, and has backed some of the most consequential technology companies of the past three decades. Their portfolio includes legendary bets on eBay, Twitter, Uber, Instagram, and more recently companies like Discord and Chainalysis. Benchmark partners are known for taking board seats and being deeply involved with their portfolio companies—sometimes controversially so, as the firm's role in the Uber boardroom drama demonstrated.\n\nCurrent general partners include Bill Gurley, who has become something of a public intellectual on venture economics and marketplace dynamics, along with Peter Fenton, Matt Cohler, Sarah Tavel, and Eric Vishria. Each partner operates with significant autonomy, sourcing and leading their own deals. The equal partnership model means there's no senior partner taking a larger cut—everyone shares equally in the carry, which creates a unique dynamic compared to firms like [Andreessen Horowitz](companies/a16z) or [Sequoia](companies/sequoia).\n\nBenchmark typically raises funds in the $400-500 million range, which seems almost quaint compared to the multi-billion dollar vehicles some competitors deploy. This constraint is intentional—it forces discipline and keeps the firm focused on ownership percentages in early rounds rather than chasing growth-stage deals. They're not trying to be everything to everyone.\n\nThe firm has a reputation for patience and contrarianism. They'll pass on hot deals that don't meet their criteria and aren't afraid to invest in unfashionable sectors. Recent activity suggests continued interest in developer tools, fintech infrastructure, and consumer social. Their investment memos are legendary within the industry for their rigor and clarity of thinking.",
"timeline": "- **2021-03-15** | Benchmark led Series A for fintech infrastructure startup, with Peter Fenton joining the board\n- **2021-09-22** | Bill Gurley published influential essay on marketplace liquidity that circulated widely among founders\n- **2022-02-08** | Closed Benchmark XI fund at $425 million, maintaining disciplined fund size despite market exuberance\n- **2022-11-14** | Sarah Tavel led investment in AI-native developer tools company alongside [Sequoia](companies/sequoia)\n- **2023-04-03** | Benchmark partner spoke at industry conference about valuation discipline during downturn\n- **2023-08-19** | Portfolio company Discord reportedly approached for acquisition; Benchmark holds significant stake\n- **2024-01-11** | Eric Vishria sourced deal in vertical SaaS space, continuing firm's enterprise software thesis\n- **2024-06-25** | Benchmark participated in growth round for crypto compliance startup, rare later-stage investment\n- **2025-02-17** | Firm hosted annual LP meeting in Woodside, discussed AI investment strategy with limited partners\n- **2025-09-30** | Co-invested with [Andreessen Horowitz](companies/a16z) in robotics seed round, unusual collaboration",
"_facts": {
"type": "company",
"slug": "companies/benchmark-3",
"name": "Benchmark",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/bessemer-12",
"type": "company",
"title": "Bessemer Venture Partners",
"compiled_truth": "Bessemer Venture Partners stands as one of the oldest and most storied venture capital firms in the world, with origins dating back to 1911 when it was founded to manage the Phipps family fortune. The firm has evolved dramaticaly over the decades, transitioning from a family office to a full-fledged VC powerhouse with offices across Menlo Park, New York, Boston, and international locations including Israel and India.\n\nBessemer has backed some of the most consequential technology companies of the past several decades. Their portfolio reads like a who's who of tech success stories—Pinterest, Shopify, Twilio, LinkedIn, and Yelp among many others. The firm is particularly known for maintaining an \"anti-portfolio\" page on their website, a refreshingly honest accounting of all the deals they passed on that went on to become massive successes. This includes famously passing on investments in Apple, Google, and Facebook.\n\nThe firm operates with a thesis-driven approach, publishing detailed \"roadmaps\" for sectors they find compelling. These documents often become required reading for founders building in spaces like cloud infrastructure, vertical SaaS, and developer tools. Their cloud computing index, the BVP Nasdaq Emerging Cloud Index, has become an industry benchmark for tracking public cloud company performance.\n\nBessemer typically invests across stages, from seed through growth, though they've become increasingly active in earlier stage deals over recent years. Partners at the firm have included notable investors who've shaped the industry's approach to enterprise software and consumer internet investing. The firm manages multiple funds totaling billions in assets under managment.\n\nTheir investment philosophy emphasizes long-term partnership with founders, and they're known for being patient capital that doesn't push for premature exits. Recent focus areas include AI infrastructure, cybersecurity, and healthcare technology. The firm has been actively deploying capital into companies building foundational AI tooling, seeing parallels to the early cloud computing wave they rode so successfully. Their relationship with [a]([Sequoia Capital](companies/sequoia-capital)) often sees them co-investing in competitive rounds, while they frequently compete with firms like [Andreessen Horowitz](companies/a16z) for the best deals in enterprise software.",
"timeline": "- **2021-03-15** | Bessemer closes Fund XII at $3.3 billion, largest fund in firm history\n- **2021-09-22** | Published influential AI infrastructure roadmap, predicting consolidation in MLOps tooling\n- **2022-04-10** | Led Series B for cybersecurity startup, marking continued focus on security vertical\n- **2022-11-08** | Partner departure to [Andreessen Horowitz](companies/a16z) creates temporary leadership shuffle\n- **2023-06-14** | Hosted annual CEO Summit in Menlo Park with 200+ portfolio founders attending\n- **2023-12-01** | BVP Nasdaq Cloud Index hits record low amid tech downturn, firm publishes market analysis\n- **2024-03-28** | Announced new $250M opportunity fund focused exclusively on AI-native companies\n- **2024-08-19** | Co-led $80M growth round alongside [Sequoia Capital](companies/sequoia-capital) in developer tools company\n- **2025-01-07** | Opened new Tel Aviv office expansion, doubling Israel team headcount\n- **2025-04-22** | Released updated anti-portfolio page, adding several notable AI misses from 2023",
"_facts": {
"type": "company",
"slug": "companies/bessemer-12",
"name": "Bessemer",
"category": "vc",
"industry": "venture capital"
}
}
-21
View File
@@ -1,21 +0,0 @@
{
"slug": "companies/beta-1",
"type": "company",
"title": "Beta - Cybersecurity Startup",
"compiled_truth": "Beta is an early-stage cybersecurity startup founded in 2023 by [Victor Taylor](people/victor-taylor-1), a veteran security researcher with deep roots in threat intelligence. The company emerged from Victor's frustration with legacy security tools that couldn't keep pace with modern attack surfaces. Based out of Austin, Texas, Beta is building what they call \"adaptive defense infrastructure\" — essentially AI-powered systems that learn an organization's normal network behavior and flag anomolies in real-time.\n\nThe founding thesis is simple but ambitious: most breaches happen because security teams are overwhelmed by alerts, not because they lack tools. Beta's platform aims to reduce alert fatigue by 90% through intelligent triage and automated response playbooks. Early customers include three mid-market fintech companies and a healthcare provider, though the company hasn't disclosed names publicly yet.\n\n[Victor Taylor](people/victor-taylor-1) serves as CEO and has been the public face of the company, speaking at several industry events about the failures of traditional SIEM solutions. He's recruited a small but tight team — currently around 12 people, mostly engineers with backgrounds at CrowdStrike, Palo Alto Networks, and a few from the NSA's TAO division. The technical co-founder role remains unfilled, which Victor has acknowledged is a gap they're actively working to address.\n\nBeta raised a $4.2M seed round in late 2023, led by a cybersecurity-focused fund with participation from several angel investors. The company is currently pre-revenue in any meaningful sense, though they've signed design partners who are testing the platform in production enviornments. Their go-to-market strategy focuses on the mid-market segment — companies large enough to have security teams but too small to afford enterprise solutions from the big players.\n\nThe competitive landscape is crowded, but Beta believes timing is on their side. With ransomware attacks continuing to surge and regulatory pressure mounting, even smaller companies are being forced to invest in security infrastructure. Whether Beta can carve out space against well-funded incumbants remains to be seen.",
"timeline": "- **2023-03-15** | [Victor Taylor](people/victor-taylor-1) incorporates Beta in Delaware, begins recruiting founding team\n- **2023-06-22** | Beta closes $4.2M seed round, announces plans to build adaptive defense platform\n- **2023-09-08** | First design partner signed — unnamed fintech company in the payments space\n- **2023-11-30** | Team grows to 8 employees, opens Austin office space\n- **2024-02-14** | Victor presents Beta's threat detection approach at RSA Conference\n- **2024-05-03** | Platform enters closed beta with three enterprise customers\n- **2024-08-19** | Expands engineering team to 12, still searching for technical co-founder\n- **2024-11-07** | Signs fourth design partner, a regional healthcare provider\n- **2025-01-22** | Begins Series A conversations with multiple VCs",
"_facts": {
"type": "company",
"slug": "companies/beta-1",
"name": "Beta",
"category": "startup",
"industry": "cybersecurity",
"founded_year": 2023,
"founders": [
"people/victor-taylor-1"
],
"employees": [
"people/tara-kapoor-111"
]
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/beta-labs-51",
"type": "company",
"title": "Beta Labs",
"compiled_truth": "Beta Labs is a data infrastructure startup founded in 2019 by [Victor Jones](people/victor-jones-51). The company has carved out a niche in the increasingly crowded data tooling space by focusing on real-time data synchronization for distributed systems. Their flagship product, SyncCore, enables companies to maintain consistency across multiple data stores without the typical latency penalties.\n\nThe founding story is pretty straightforward. Victor had spent years dealing with data consistency nightmares at previous roles and decided there had to be a better way. Beta Labs emerged from that frustration, initially as a consulting operation before pivoting to product in late 2020. The pivot proved wise—enterprise demand for their sync technology exceeded expectations.\n\nFunding has come from angel investors including [Jack Davis](people/jack-davis-89) and [Chris Singh](people/chris-singh-96), both of whom participated in the seed round. Jack in particular has been an active advisor, connecting the company with potential enterprise customers in the fintech vertical. Chris brought operational expertise from his own startup experience, helping Beta Labs avoid some common scaling pitfalls.\n\nThe team has grown to around 45 people, mostly engineers. They've maintained a relatively low profile compared to flashier competitors, preferring to let the technology speak for itself. This approach has worked—several Fortune 500 companies now rely on SyncCore for mission-critical data operations, though Beta Labs rarely publicizes these relationships.\n\nRecent moves suggest the company is gearing up for expansion. They've been hiring aggressivley on the go-to-market side and opened a small office in London to serve European clients. There's been speculation about a Series A, though Victor has remained tight-lipped about fundraising plans.\n\nBeta Labs occupies an interesting position in the data infrastructure ecosystem. Not quite a database company, not purely an ETL play—more of a connective tissue between existing systems. This positioning has made them attractive to enterprises who don't want to rip and replace their current stack but desperatley need better synchronization. The data infrastructure space continues to evolve rapidly, and Beta Labs seems well-positioned to grow alongside it.",
"timeline": "- **2019-03-15** | Beta Labs incorporated by [Victor Jones](people/victor-jones-51) in Delaware\n- **2020-11-02** | Pivoted from consulting to product development, began building SyncCore\n- **2021-04-18** | Closed seed round with participation from [Jack Davis](people/jack-davis-89) and [Chris Singh](people/chris-singh-96)\n- **2021-09-07** | Launched SyncCore private beta with 12 design partners\n- **2022-02-14** | General availability of SyncCore, landed first Fortune 500 customer\n- **2023-06-22** | Reached 30 employees, opened London office for European expansion\n- **2024-01-10** | [Victor Jones](people/victor-jones-51) spoke at DataCon about distributed consistency patterns\n- **2024-08-30** | Shipped SyncCore 2.0 with multi-region support\n- **2025-03-12** | Announced partnership with major cloud provider for marketplace distribution\n- **2025-11-05** | Rumored Series A discussions with multiple tier-one VCs",
"_facts": {
"type": "company",
"slug": "companies/beta-labs-51",
"name": "Beta Labs",
"category": "startup",
"industry": "data infrastructure",
"founded_year": 2019,
"founders": [
"people/victor-jones-51"
],
"investors": [
"people/jack-davis-89",
"people/chris-singh-96"
],
"employees": [
"people/kate-rodriguez-161"
]
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/brink-29",
"type": "company",
"title": "Brink",
"compiled_truth": "Brink is a data infrastructure startup founded in 2019 by [Uma Gonzalez](people/uma-gonzalez-29), who serves as CEO. The company builds middleware solutions that help enterprises manage data pipelines across hybrid cloud environments. Their flagship product, Brink Flow, enables real-time data synchronization between on-premise databases and cloud data warehouses without requiring significant engineering overhead.\n\nThe company emerged from Uma's frustration with existing ETL tools while she was working at a large financial services firm. She saw an oportunity to build something more elegant—a system that could handle schema changes automatically and scale horizontally without the typical headaches. Brink's approach uses a proprietary conflict resolution algorithm that has attracted attention from several Fortune 500 companies looking to modernize their data stacks.\n\nBrink operates with a relatively lean team of around 45 employees, mostly engineers, headquartered in Austin with a small office in San Francisco. The company has raised approximately $28 million across seed and Series A rounds, though they've been quiet about specifics. Industry observers note that Brink competes in a crowded space but has carved out a niche with customers who need particularly robust handling of legacy database formats.\n\nThe advisory board includes [Ian Wilson](people/ian-wilson-180), who brings deep expertise in enterprise sales cycles, and [Grace Singh](people/grace-singh-197), known for her technical architecture background. Both advisors have been instrumental in shaping Brink's go-to-market strategy and product roadmap. Grace in particular has pushed the team toward better observability features, which became a key differentiator in recent customer wins.\n\nRecent months have seen Brink expanding into the healthcare vertical, where data compliance requirements create natural demand for their controlled sync capabilities. The company announced SOC 2 Type II certification in late 2024, a prerequisite for many enterprise deals. Uma has been public about her goal to reach $10M ARR before considering a Series B, preferring to grow efficently rather than chase hypergrowth.",
"timeline": "- **2019-03-15** | Uma Gonzalez incorporates Brink in Delaware, begins building initial prototype\n- **2021-06-22** | Closes $4.2M seed round led by Vertex Ventures\n- **2022-01-10** | Brink Flow enters private beta with 12 design partners\n- **2022-09-08** | [Ian Wilson](people/ian-wilson-180) joins as advisor, helps restructure sales approach\n- **2023-02-14** | Announces $24M Series A, valuation undisclosed\n- **2023-07-19** | [Grace Singh](people/grace-singh-197) joins advisory board\n- **2024-04-03** | Ships Brink Flow 2.0 with real-time schema migration support\n- **2024-11-12** | Achieves SOC 2 Type II certification\n- **2025-02-28** | Signs first major healthcare customer, regional hospital network\n- **2025-05-16** | [Uma Gonzalez](people/uma-gonzalez-29) speaks at Data Summit on hybrid cloud challenges",
"_facts": {
"type": "company",
"slug": "companies/brink-29",
"name": "Brink",
"category": "startup",
"industry": "data infrastructure",
"founded_year": 2019,
"founders": [
"people/uma-gonzalez-29"
],
"employees": [
"people/vera-wang-139"
],
"advisors": [
"people/ian-wilson-180",
"people/grace-singh-197"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/cascade-30",
"type": "company",
"title": "Cascade",
"compiled_truth": "Cascade is an AI applications startup founded in 2018 by [Yara Smith](people/yara-smith-30), who remains the driving force behind the company's product vision. The company focuses on building enterprise-grade AI tools that automate complex document workflows, particularly in legal and compliance sectors. Their flagship product, Cascade Flow, uses large language models to extract, summarize, and cross-reference information across thousands of documents simultaneosly.\n\nThe early years were tough. Cascade operated in relative obscurity, bootstrapping through consulting gigs while refining their core technology. It wasn't until 2021 that they secured meaningful venture funding and began scaling the team. Today the company employs around 85 people, mostly engineers and ML researchers, with a small but scrappy sales org based out of their San Francisco headquarters.\n\n[Bob Chen](people/bob-chen-185) joined as an advisor in late 2022, bringing his extensive experience in enterprise SaaS and go-to-market strategy. His involvement reportedly helped Cascade land several Fortune 500 pilots that converted to multi-year contracts. Chen's network in the financial services industry has been particuarly valuable as Cascade expands beyond legal tech into banking and insurance verticals.\n\nYara Smith has been vocal about building AI that augments rather than replaces human workers. In interviews she often emphasizes that Cascade's tools are designed to handle the drudgery so professionals can focus on judgment calls and client relationships. This positioning has resonated well with enterprise buyers who remain cautious about fully autonomous AI systems.\n\nRecent moves suggest Cascade is preparing for significant growth. They've been hiring aggressively for a new product line—rumored to be an AI-powered contract negotiation assistant—and opened a small office in London to support European expansion. Competition in the space is heating up with well-funded rivals, but Cascade's early mover advantage and deep integrations with legacy document management systems give them a defensible position. The company is reportedly exploring a Series C round, though nothing has been announced publicly.",
"timeline": "- **2018-03-12** | Cascade incorporated in Delaware by founder Yara Smith\n- **2021-06-08** | Closed $8M Series A led by Threshold Ventures\n- **2022-04-15** | Launched Cascade Flow publicly after 18 months of private beta\n- **2022-11-02** | [Bob Chen](people/bob-chen-185) joined as strategic advisor\n- **2023-02-28** | Announced partnership with DocuSign for native integration\n- **2023-09-14** | [Yara Smith](people/yara-smith-30) spoke at TechCrunch Disrupt on enterprise AI adoption\n- **2024-01-22** | Raised $32M Series B, valuation undisclosed\n- **2024-07-10** | Opened London office to support EMEA expansion\n- **2025-03-05** | Reached 200 enterprise customers milestone\n- **2025-11-18** | Began private beta for contract negotiation AI product",
"_facts": {
"type": "company",
"slug": "companies/cascade-30",
"name": "Cascade",
"category": "startup",
"industry": "AI applications",
"founded_year": 2018,
"founders": [
"people/yara-smith-30"
],
"employees": [
"people/noah-davis-140"
],
"advisors": [
"people/bob-chen-185"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/cipher-13",
"type": "company",
"title": "Cipher",
"compiled_truth": "Cipher is a fintech startup founded in 2024 by [Mia Lee](people/mia-lee-13), a first-time founder with a background in cryptography and distributed systems. The company is building infrastructure for programmable money—specifically, a platform that allows fintechs and neobanks to embed complex payment logic directly into their transaction rails. Think conditional payments, escrow-like holds, and multi-party settlements, all handled at the protocol level rather than bolted on after the fact.\n\nThe founding thesis came out of Mia's frustration working at larger financial institutions where even simple payment customizations required months of engineering work and compliance review. Cipher aims to abstract away that complexity, offering APIs that let developers define payment conditions in a few lines of code. Early positioning suggests they're targeting B2B fintech infrastructure rather than consumer-facing products.\n\nThe company operates lean, with a small team of five engineers working out of a co-working space in San Francisco. [Noah Williams](people/noah-williams-198) serves as an advisor, bringing experience from his own ventures in the payments space. His involvement lent early credibility when Cipher was pitching to angels and seed investors. Noah's been particularly helpful on go-to-market stratgey, pushing the team to focus on a narrow wedge before expanding.\n\nCipher closed a pre-seed round in late 2024, though the exact amount hasn't been publicly disclosed—likely in the $1.5-2M range based on typical fintech raises at that stage. The company has been in private beta with three design partners, all smaller neobanks looking to differentiate on payment flexibility. Early feedback has been positive, though integrations have taken longer than anticipated due to legacy system constraints on the partner side.\n\nMia has been intentionally quiet about the company publicly, preferring to let the product speak once it's ready. She's mentioned in interviews that Cipher won't be doing a splashy launch—instead, they'll scale through word of mouth in the developer comunity. The name itself, Cipher, reflects both the cryptographic roots and the idea of encoding complex logic into simple interfaces.",
"timeline": "- **2024-01-15** | [Mia Lee](people/mia-lee-13) incorporates Cipher in Delaware, begins recruiting founding engineers\n- **2024-03-02** | First technical architecture doc completed; decides on Rust for core payment engine\n- **2024-04-18** | [Noah Williams](people/noah-williams-198) joins as advisor after intro through mutual investor contact\n- **2024-06-10** | Cipher closes pre-seed round, terms undisclosed\n- **2024-08-22** | Private beta launches with first design partner, a challenger bank based in Austin\n- **2024-10-05** | Second and third beta partners onboarded; team grows to five full-time\n- **2024-11-30** | Mia presents Cipher at a closed fintech founders dinner in SF\n- **2025-01-14** | First successful production transaction processed through Cipher rails\n- **2025-03-08** | Beginning conversations with potential seed investors for next round",
"_facts": {
"type": "company",
"slug": "companies/cipher-13",
"name": "Cipher",
"category": "startup",
"industry": "fintech",
"founded_year": 2024,
"founders": [
"people/mia-lee-13"
],
"employees": [
"people/julia-thomas-123"
],
"advisors": [
"people/noah-williams-198"
]
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/compass-11",
"type": "company",
"title": "Compass",
"compiled_truth": "Compass is a crypto startup founded in 2018 by [Mark Thomas](people/mark-thomas-11), positioning itself as an early mover in blockchain-based navigation and location services. The company has carved out a niche attempting to decentralize geospatial data, arguing that traditional mapping services concentrate too much power in the hands of a few tech giants.\n\nThe core product is a token-incentivized network where users contribute location data and receive CMPS tokens in return. Think of it as a crypto-native alternative to Google Maps, though the comparison is admittedly generous given Compass's current scale. The protocol allows developers to build location-aware dApps without relying on centralized APIs, which has attracted some interest from the DeFi and gaming communities.\n\nMark Thomas serves as CEO and has been the driving force behind the company's technical vision. Before founding Compass, he worked in geospatial analytics and became convinced that location data would become increasingly valuable—and increasingly surveilled. His pitch to investors centered on data sovereignty and the idea that people should own their movement patterns.\n\n[Chris Miller](people/chris-miller-101) came in as an early investor during the 2019 seed round, providing both capital and credibility in crypto circles. Miller's involvement helped Compass attract additional funding and connected the team to key infrastructure partners. The relationship has been mutually beneficial, with Miller often pointing to Compass as an example of \"real utility\" in the blockchain space.\n\nOn the advisory side, [Sam Garcia](people/sam-garcia-188) has been instrumental in shaping go-to-market strategy. Garcia joined as an advisor in late 2021 and helped the company navigate the treacherous waters of the 2022 crypto winter. His experience with enterprise sales proved valuable when Compass pivoted toward B2B partnerships with logistics companies.\n\nRecent moves include a partnership with several delivery startups in Southeast Asia and the launch of Compass SDK 2.0, which simplifies integration for third-party developers. The team remains small—around 25 people—but has managed to maintain steady growth despite market volatility. Their approach has been decidedly un-hypey by crypto standards, focusing on incremental adoption rather then moonshot promises.",
"timeline": "- **2018-06-15** | Compass incorporated by [Mark Thomas](people/mark-thomas-11) in Delaware, initial whitepaper published\n- **2019-03-22** | Seed round closed with [Chris Miller](people/chris-miller-101) leading, $2.1M raised\n- **2020-11-08** | CMPS token launched on mainnet, initial contributor network goes live\n- **2021-09-14** | [Sam Garcia](people/sam-garcia-188) joins as strategic advisor\n- **2022-05-30** | Company survives Terra collapse fallout, announces pivot toward enterprise partnerships\n- **2023-02-17** | Partnership signed with three logistics firms in Singapore and Vietnam\n- **2024-01-09** | Compass SDK 2.0 released, developer signups increase 340% in Q1\n- **2024-08-23** | Mark Thomas speaks at ETH Denver on decentralized infrastructure\n- **2025-04-11** | Series A discussions reportedly underway, targeting $15M raise",
"_facts": {
"type": "company",
"slug": "companies/compass-11",
"name": "Compass",
"category": "startup",
"industry": "crypto",
"founded_year": 2018,
"founders": [
"people/mark-thomas-11"
],
"investors": [
"people/chris-miller-101"
],
"employees": [
"people/rachel-davis-121"
],
"advisors": [
"people/sam-garcia-188"
]
}
}
@@ -1,28 +0,0 @@
{
"slug": "companies/delta-3",
"type": "company",
"title": "Delta",
"compiled_truth": "Delta is a biotech startup founded in 2022 by [Victor Wilson](people/victor-wilson-3), who previously spent nearly a decade in academic research before making the jump to entrepreneurship. The company focuses on developing novel protein engineering platforms, with an initial emphasis on therapeutic applications for rare genetic disorders. Based out of the Boston-Cambridge biotech corridor, Delta has quickly gained attention for its unconventional approach to computational biology.\n\nThe founding story is somewhat unusual. Victor had been sitting on the core intellectual property for years, hesitant to commercialize what he considered fundamental research. It wasn't until a chance meeting with [David Zhang](people/david-zhang-83) at a conference in late 2021 that the idea of building a company around the technology started to take shape. Zhang, known for his patient capital approach, saw potential where others had passed.\n\nDelta's seed round closed in early 2023, with [Rachel Brown](people/rachel-brown-95) joining as a co-lead investor alongside Zhang. Brown brought not just capital but also deep operational expertise from her previous biotech exits. The round was modest by industry standards—around $4.2M—but sufficient to build out the initial lab infrastructure and hire a small team of computational biologists.\n\n[David Brown](people/david-brown-187) serves as the company's primary advisor, providing guidance on regulatory pathways and clinical trial design. His involvement has been instrumental in helping Delta avoid some of the common pitfalls that trap early-stage biotech ventures. The advisory relationship began informally but was formalized in mid-2023.\n\nThe company remains small, with fewer than fifteen full-time employees. Victor Wilson continues to lead as CEO, though there's been some internal discussion about bringing in an experienced biotech operator as the company approaches its Series A. Delta's platform has shown promising early results in preclinical models, though significant validation work remains before any theraputic candidates could advance to human trials. The team is currently focused on partnership discussions with larger pharma players who might provide both capital and developmnet expertise.",
"timeline": "- **2021-11-18** | Victor Wilson meets [David Zhang](people/david-zhang-83) at BioFuture Conference in San Francisco; initial conversations about commercialization begin\n- **2022-03-07** | Delta formally incorporated in Delaware; Victor Wilson named founding CEO\n- **2022-06-14** | First lab space secured in Cambridge, MA; initial equipment purchases made\n- **2023-02-22** | Seed round closes at $4.2M led by [David Zhang](people/david-zhang-83) and [Rachel Brown](people/rachel-brown-95)\n- **2023-05-30** | [David Brown](people/david-brown-187) joins as formal advisor; focuses on regulatory strategy\n- **2023-09-11** | Delta publishes preprint on novel protein folding methodology; generates significant academic interest\n- **2024-01-16** | Team expands to 12 FTEs; hires head of computational biology from Stanford\n- **2024-07-08** | First preclinical proof-of-concept data shared with potential pharma partners\n- **2025-02-03** | Delta enters preliminary partnership discussions with two top-20 pharma companies",
"_facts": {
"type": "company",
"slug": "companies/delta-3",
"name": "Delta",
"category": "startup",
"industry": "biotech",
"founded_year": 2022,
"founders": [
"people/victor-wilson-3"
],
"investors": [
"people/david-zhang-83",
"people/rachel-brown-95"
],
"employees": [
"people/adam-lopez-113"
],
"advisors": [
"people/david-brown-187"
]
}
}
@@ -1,29 +0,0 @@
{
"slug": "companies/delta-labs-53",
"type": "company",
"title": "Delta Labs",
"compiled_truth": "Delta Labs is a climate tech startup founded in 2021 by [Will Garcia](people/will-garcia-53), who left a senior role at a major energy company to pursue what he calls \"the only problem worth solving.\" The company focuses on direct air capture technology, specifically developing modular units that can be deployed at scale in industrial settings. Their approach differs from competitors by integrating with existing HVAC infrastructure rather than requiring standalone installations.\n\nThe company has attracted notable backing from angel investors including [Wendy Hernandez](people/wendy-hernandez-80) and [Tina Hernandez](people/tina-hernandez-97), both of whom have deep networks in the cleantech space. Delta Labs closed their seed round in late 2022, though exact figures weren't publicly disclosed. Industry insiders estimate somewhere between $4-6M based on hiring patterns and equipment purchases.\n\nOn the advisory side, Delta brought in [Wendy Wilson](people/wendy-wilson-170) for her expertise in regulatory navigation—critical for a company operating in a space where policy can make or break unit economics. [Grace Singh](people/grace-singh-197) rounds out the advisory board, contributing her background in scaling hardware startups through the notorious \"valley of death\" between prototype and production.\n\nDelta's current focus is on their second-generation capture modules, which promise 40% better efficiency than their initial designs. Will Garcia has been particularly vocal about avoiding the hype cycles that have plagued other climate tech ventures, preferring to let results speak. The team has grown to roughly 25 people, mostly engineers with backgrounds in chemical enginering and mechanical systems.\n\nThe company operates out of a converted warehouse in Oakland, where they run continuous testing on their prototype units. Early pilot programs with two Fortune 500 companies are underway, though Delta Labs hasn't named partners publicly. Garcia has mentioned in interviews that revenue isn't the immediate priority—proving the technology works at scale is. Whether that patience will pay off remains to be seen, but the climate tech sector is watching closely.",
"timeline": "- **2021-03-15** | Delta Labs incorporated in Delaware by founder [Will Garcia](people/will-garcia-53)\n- **2021-09-02** | First prototype capture unit completed; internal testing begins at Oakland facility\n- **2022-04-18** | [Wendy Hernandez](people/wendy-hernandez-80) joins as lead investor in pre-seed round\n- **2022-11-30** | Seed round closed with participation from [Tina Hernandez](people/tina-hernandez-97) and other angels\n- **2023-02-14** | [Wendy Wilson](people/wendy-wilson-170) announced as regulatory advisor\n- **2023-07-22** | Delta Labs hits 15 employees; opens second testing bay\n- **2024-01-10** | Gen-2 modular unit enters development phase\n- **2024-06-05** | First enterprise pilot program signed (partner undisclosed)\n- **2025-03-28** | Will Garcia speaks at Climate Forward conference on scaling DAC technology\n- **2025-09-12** | Second Fortune 500 pilot announced; team reaches 25 people",
"_facts": {
"type": "company",
"slug": "companies/delta-labs-53",
"name": "Delta Labs",
"category": "startup",
"industry": "climate tech",
"founded_year": 2021,
"founders": [
"people/will-garcia-53"
],
"investors": [
"people/wendy-hernandez-80",
"people/tina-hernandez-97"
],
"employees": [
"people/liam-miller-163"
],
"advisors": [
"people/wendy-wilson-170",
"people/grace-singh-197"
]
}
}
@@ -1,30 +0,0 @@
{
"slug": "companies/drift-31",
"type": "company",
"title": "Drift",
"compiled_truth": "Drift is a developer tools startup founded in 2021 by [Frank Hernandez](people/frank-hernandez-31), who saw an opportunity to streamline the way engineering teams manage configuration drift across distributed systems. The company emerged from Frank's frustration while working at larger tech firms, where he noticed teams spending countless hours debugging issues caused by configuration mismatches between environments.\n\nThe core product offers real-time monitoring and automated remediation for infrastructure configurations, targeting mid-size engineering organizations running complex microservices architectures. Drift's approach differs from traditional configuration managment tools by focusing on detection and alerting rather than enforcement, giving teams flexibility while maintaining visibility. The platform integrates with major cloud providers and works alongside existing CI/CD pipelines.\n\nEarly funding came from a group of angel investors including [Wendy Hernandez](people/wendy-hernandez-80), [Fiona Moore](people/fiona-moore-88), and [Jack Davis](people/jack-davis-89). The diverse investor group brought both capital and operational expertise to the young company. Wendy in particular has been instrumental in connecting Drift with potential enterprise customers through her network.\n\n[Xavier Patel](people/xavier-patel-183) serves as an advisor, bringing deep experience in developer tooling and go-to-market strategy. His guidance helped shape Drift's initial product positioning and pricing model. Xavier pushed the team to focus on a specific use case rather than trying to boil the ocean with features.\n\nThe company operates with a lean team, currently around 15 employees, mostly engineers. They've taken a developer-first approach to sales, offering generous free tiers and building community through open source contributions. Their CLI tool has gained traction on GitHub, serving as a funnel for the commercial product.\n\nDrift has seen steady growth among startups and scale-ups, though breaking into true enterprise accounts remains a challenge. The team is currently working on SOC 2 compliance and additional security features to address enterprise requirements. Competition in the config management space is fierce, but Drift's focused approach has carved out a niche among teams who value simplicity over comprehensiveness.",
"timeline": "- **2021-03-15** | Company founded by [Frank Hernandez](people/frank-hernandez-31) after leaving his role at a major cloud provider\n- **2021-06-22** | Closed pre-seed round with participation from [Wendy Hernandez](people/wendy-hernandez-80) and [Fiona Moore](people/fiona-moore-88)\n- **2021-11-08** | Launched private beta with 12 design partner companies\n- **2022-04-03** | [Xavier Patel](people/xavier-patel-183) joined as formal advisor\n- **2022-09-17** | Public launch of Drift CLI tool, gained 2k GitHub stars in first month\n- **2023-02-28** | [Jack Davis](people/jack-davis-89) participated in seed extension round\n- **2023-08-14** | Shipped Kubernetes-native integration, biggest feature release to date\n- **2024-01-22** | Frank spoke at DevOpsDays SF on configuration observability\n- **2024-07-09** | Reached 500 active organizations on the platform\n- **2025-03-11** | Began SOC 2 Type II certification process",
"_facts": {
"type": "company",
"slug": "companies/drift-31",
"name": "Drift",
"category": "startup",
"industry": "developer tools",
"founded_year": 2021,
"founders": [
"people/frank-hernandez-31"
],
"investors": [
"people/wendy-hernandez-80",
"people/fiona-moore-88",
"people/jack-davis-89",
"people/tina-hernandez-97"
],
"employees": [
"people/olivia-garcia-141"
],
"advisors": [
"people/xavier-patel-183"
]
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/echo-32",
"type": "company",
"title": "Echo - Robotics Startup",
"compiled_truth": "Echo is a robotics startup founded in 2025 by [Helen Johnson](people/helen-johnson-32), a serial entrepreneur with deep expertise in automation and machine learning. The company focuses on developing autonomous robotic systems for warehouse logistics and last-mile delivery, positioning itself at the intersection of AI and physical hardware. Based in Austin, Texas, Echo has quickly gained attention for its modular approach to robot design, allowing clients to customize units for specific operational needs.\n\nThe founding team came together after Helen's previous venture in industrial automation was aquired by a larger player in the space. She saw an opportunity to build something more agile, more responsive to the needs of mid-sized fulfillment centers that couldn't afford the massive infrastructure investments required by legacy robotics providers. Echo's flagship product, the E-1 mobile unit, can navigate complex warehouse environments with minimal setup time.\n\nEarly backing came from angel investors including [Julia Davis](people/julia-davis-86) and [Helen Martinez](people/helen-martinez-87), both of whom have track records in deep tech investments. Julia Davis in particular has been instrumental in connecting Echo with potential enterprise customers through her network in the logistics industry. The company closed a small seed round in early 2025, though exact figures haven't been publicly disclosed.\n\nEcho operates with a lean team of around twelve engineers and has partnered with several contract manufacturers to scale production. The startup has been notably secretive about its technical roadmap, though rumors suggest they're working on swarm coordination protocols that would allow multiple E-1 units to operate collaboratively. Helen Johnson has hinted at plans to expand into agricultural robotics by 2026, leveraging the same core platform.\n\nThe robotics space is crowded, but Echo's emphasis on affordabilty and rapid deployment has resonated with smaller operators who feel underserved by existing solutions. Whether they can maintain this edge as they scale remains to be seen.",
"timeline": "- **2024-09-15** | [Helen Johnson](people/helen-johnson-32) begins initial R&D work on modular robotics platform\n- **2025-01-20** | Echo officially incorporated in Austin, Texas\n- **2025-02-08** | [Julia Davis](people/julia-davis-86) commits as lead angel investor\n- **2025-02-14** | [Helen Martinez](people/helen-martinez-87) joins seed round\n- **2025-03-30** | First E-1 prototype completed and demonstrated internally\n- **2025-05-12** | Echo hires VP of Engineering from Boston Dynamics\n- **2025-07-22** | Pilot program launched with regional fulfillment center in Dallas\n- **2025-09-10** | Helen Johnson speaks at RoboWorld Conference on modular design philosophy\n- **2025-11-01** | Company reaches 12 full-time employees",
"_facts": {
"type": "company",
"slug": "companies/echo-32",
"name": "Echo",
"category": "startup",
"industry": "robotics",
"founded_year": 2025,
"founders": [
"people/helen-johnson-32"
],
"investors": [
"people/julia-davis-86",
"people/helen-martinez-87"
],
"employees": [
"people/fiona-hernandez-142"
]
}
}
@@ -1,30 +0,0 @@
{
"slug": "companies/epsilon-4",
"type": "company",
"title": "Epsilon",
"compiled_truth": "Epsilon is a cybersecurity startup founded in 2021 by [Paul Rodriguez](people/paul-rodriguez-4), a veteran security researcher who previously led threat intelligence teams at two Fortune 500 companies. The company focuses on automated vulnerability detection for cloud-native infrastructure, using machine learning models trained on proprietary datasets of real-world attack patterns.\n\nFrom the begining, Epsilon positioned itself as a developer-first security platform. Rather than bolting security onto existing workflows, the product integrates directly into CI/CD pipelines, scanning code and infrastructure-as-code templates before deployment. This approach resonated with engineering teams frustrated by traditional security tools that generated endless false positives and slowed down releases.\n\nThe company has attracted notable backing from angel investors including [Sarah Lopez](people/sarah-lopez-84), [Sarah Williams](people/sarah-williams-92), and [Kate Lopez](people/kate-lopez-99). Their combined experience in enterprise software and fintech has helped Epsilon navigate early sales cycles with large financial institutions. The advisory board includes [Olivia Miller](people/olivia-miller-176), who brings deep expertise in go-to-market strategy for B2B SaaS, and [Bob Chen](people/bob-chen-185), a respected figure in the open-source security community.\n\nEpsilon's flagship product, ShieldScan, launched in late 2022 and has since been adopted by over 150 organizations. The platform monitors Kubernetes clusters, AWS environments, and Azure deployments in real-time, alerting teams to misconfigurations and potential breach vectors. Recent product updates have added support for GCP and introduced a compliance module targeting SOC 2 and HIPAA requirements.\n\nPaul Rodriguez has been vocal about the need for security tooling that \"meets developers where they are\" rather than imposing rigid workflows. This philosophy has driven Epsilon's product roadmap and contributed to strong word-of-mouth growth among DevOps teams. The company currently employs around 45 people, with engineering and customer success making up the bulk of headcount. Headquarters are in Austin, Texas, though most of the team works remotely.\n\nCompetition in the cloud security space is intense, with well-funded players like Wiz and Lacework dominating mindshare. Epsilon differentiates through pricing transparency and a self-serve model that lets smaller teams get started without lengthy enterprise sales processes.",
"timeline": "- **2021-03-15** | Epsilon incorporated in Delaware by [Paul Rodriguez](people/paul-rodriguez-4)\n- **2021-07-22** | Closed $1.2M pre-seed round led by [Sarah Lopez](people/sarah-lopez-84)\n- **2022-01-10** | [Olivia Miller](people/olivia-miller-176) joins advisory board\n- **2022-06-08** | First enterprise customer signed — regional bank in Texas\n- **2022-11-03** | ShieldScan v1.0 publicly launched\n- **2023-04-17** | Epsilon raises $8M seed round; [Kate Lopez](people/kate-lopez-99) participates\n- **2023-09-25** | [Bob Chen](people/bob-chen-185) added as technical advisor\n- **2024-02-12** | Surpassed 100 paying customers milestone\n- **2024-08-30** | Announced GCP integration at CloudSecCon\n- **2025-03-05** | Opened first international office in London",
"_facts": {
"type": "company",
"slug": "companies/epsilon-4",
"name": "Epsilon",
"category": "startup",
"industry": "cybersecurity",
"founded_year": 2021,
"founders": [
"people/paul-rodriguez-4"
],
"investors": [
"people/sarah-lopez-84",
"people/sarah-williams-92",
"people/kate-lopez-99"
],
"employees": [
"people/julia-johnson-114"
],
"advisors": [
"people/olivia-miller-176",
"people/bob-chen-185"
]
}
}
@@ -1,28 +0,0 @@
{
"slug": "companies/epsilon-labs-54",
"type": "company",
"title": "Epsilon Labs",
"compiled_truth": "Epsilon Labs is a fintech startup founded in 2023 by [Diana Wilson](people/diana-wilson-54), a serial entrepreneur with a background in quantitative finance and distributed systems. The company operates in the payments infrastructure space, building API-first solutions for cross-border B2B transactions. Their flagship product, EpsilonPay, enables businesses to settle international invoices in near real-time while automatically handling currency conversion and compliance checks.\n\nThe founding story traces back to Diana's frustration with legacy payment rails during her previous venture. She saw an oportunity to leverage modern cloud infrastructure and machine learning to dramatically reduce settlement times and fees. Within months of incorporating, Epsilon Labs had assembled a small but experienced engineering team, many recruited from established fintech players.\n\nEpsilon raised a seed round in late 2023, with [Iris Lee](people/iris-lee-82) leading the investment. Iris brought not just capital but also deep connections in the Asian fintech ecosystem, which has proven valuable as Epsilon eyes expansion into Singapore and Hong Kong markets. [Grace Martinez](people/grace-martinez-109) also participated in the round, adding her expertise in regulatory strategy to the cap table. The total raise was reportedly around $4.2 million, though the company hasn't disclosed exact figures publicly.\n\nOn the advisory side, [Zoe Jackson](people/zoe-jackson-199) has been instrumental in shaping Epsilon's go-to-market strategy. Zoe's experience scaling enterprise sales teams has helped the startup land its first handful of mid-market customers, including a logistics company and two e-commerce platforms.\n\nEpsilon Labs currently employs around 18 people, mostly engineers and product folks, operating out of a modest office in San Francisco's SoMa district. The company culture leans heavily toward async communication and documentation — a reflection of Diana's management philosophy. Recent LinkedIn posts suggest they're hiring aggresively for compliance and partnerships roles, hinting at plans to expand their banking relationships.\n\nThe fintech space is crowded, but Epsilon's focus on the unglamorous middle-market segment gives them room to grow without directly competing with giants like Stripe or Wise. At least for now.",
"timeline": "- **2023-02-14** | Diana Wilson incorporates Epsilon Labs in Delaware, begins recruiting co-founding engineers\n- **2023-05-03** | First working prototype of EpsilonPay API demoed internally\n- **2023-08-21** | Seed round closes with [Iris Lee](people/iris-lee-82) as lead investor, $4.2M raised\n- **2023-09-15** | [Zoe Jackson](people/zoe-jackson-199) joins as formal advisor, begins weekly strategy sessions\n- **2023-11-30** | EpsilonPay enters private beta with three launch partners\n- **2024-01-22** | [Grace Martinez](people/grace-martinez-109) introduces Epsilon to key banking contacts in Latin America\n- **2024-04-10** | Public launch of EpsilonPay, first press coverage in TechCrunch\n- **2024-07-08** | Team grows to 18 employees, opens dedicated compliance function\n- **2024-10-02** | Diana Wilson speaks at Fintech Summit SF on future of B2B payments\n- **2025-01-15** | Epsilon Labs begins exploratory conversations for Series A",
"_facts": {
"type": "company",
"slug": "companies/epsilon-labs-54",
"name": "Epsilon Labs",
"category": "startup",
"industry": "fintech",
"founded_year": 2023,
"founders": [
"people/diana-wilson-54"
],
"investors": [
"people/iris-lee-82",
"people/grace-martinez-109"
],
"employees": [
"people/owen-martinez-164"
],
"advisors": [
"people/zoe-jackson-199"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/first-round-10",
"type": "company",
"title": "First Round Capital",
"compiled_truth": "First Round Capital is a seed-stage venture capital firm that has established itself as one of the most influential early-stage investors in the technology ecosystem. Founded in 2004 by Josh Kopelman, the firm focuses exclusively on being the first institutional investor in technology companies, typically leading seed rounds and participating in early follow-on financing.\n\nThe firm has built a remarkable portfolio over the years, with notable investments including Uber, Square, Roblox, Notion, and Warby Parker. First Round is known for its operator-friendly approach and has developed an extensive platform of resources for founders, including the First Round Review publication which shares tactical advice from experienced entrepreneurs and executives.\n\nFirst Round operates with a relatively small partnership structure compared to larger VC firms, which allows partners to maintain close relationships with portfolio companies. The firm typically invests between $1-3 million in initial checks, though this has crept upward in recent years as seed rounds have grown larger across the industry. They maintain offices in San Francisco, New York, and Philadelphia.\n\nOne distinguishing characteristic of First Round is their community-building efforts. The firm hosts an annual CEO Summit and runs various programs designed to connect founders with each other and with potential hires. Their talent team actively helps portfolio companeis with recruiting, recognizing that early hiring decisions are often make-or-break for startups.\n\nThe firm has raised multiple funds over its history, with recent vehicles exceeding $500 million in committed capital. Despite the larger fund sizes, First Round has maintained its focus on seed-stage investing rather than moving upstream to compete with Series A and B investors. This disciplined approach has helped them maintain strong returns and a clear market position.\n\nFirst Round's investment thesis centers on backing exceptional founders at the earliest stages, often before there's significant traction or revenue. They look for founders with deep domain expertise, unique insights into markets, and the resilience needed to build compaines over the long term. The firm has been particularly active in enterprise software, fintech, and consumer technology sectors.",
"timeline": "- **2021-03-15** | First Round closes Fund VII at $540 million, largest fund to date\n- **2021-09-22** | Led seed round for emerging AI startup, marking early bet on generative technology\n- **2022-02-08** | First Round Review publishes widely-shared piece on startup hiring in remote era\n- **2022-11-30** | Partner Todd Jackson joins board of breakout portfolio company\n- **2023-04-12** | Hosted annual CEO Summit in San Francisco with 200+ portfolio founders attending\n- **2023-08-19** | Announced new $600M Fund VIII focused on seed and pre-seed investments\n- **2024-01-25** | First Round portfolio company achieves unicorn status after Series C\n- **2024-06-03** | Launched new founder fellowship program targeting underrepresented entrepreneurs\n- **2025-02-14** | Published annual State of Startups report showing shifting founder sentiment on fundraising\n- **2025-09-08** | Expanded New York office, adding three new partners to the team",
"_facts": {
"type": "company",
"slug": "companies/first-round-10",
"name": "First Round",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/floodgate-9",
"type": "company",
"title": "Floodgate - Early-Stage Venture Capital Firm",
"compiled_truth": "Floodgate is a prominent seed-stage venture capital firm based in Palo Alto, California, known for its thesis-driven approach to early-stage investing. Founded in 2006 by Mike Maples Jr. and Ann Miura-Ko, the firm has established itself as one of the most respected names in Silicon Valley's seed investing landscape. They've built a reputation for backing founders at the earliest stages, often before there's much more than an idea and a passionate team.\n\nThe firm operates with a relatively small team compared to larger VC shops, which allows them to maintain close relationships with portfolio founders. Ann Miura-Ko, often referred to as one of the most powerful women in startups, brings an academic rigor to investing—she holds a PhD from Stanford and teaches there as a lecturing professor. Mike Maples Jr. previously founded Motive Communications and brings operational experiance to the table.\n\nFloodgate's investment philosophy centers on what they call \"thunder lizards\"—startups with the potential to fundamentally reshape markets rather than just iterate on existing solutions. They're looking for companies that can create entirely new categories. This approach has led to early investments in companies like Lyft, Twitter, and Twitch, demonstrating their ability to identify transformative platforms before they become household names.\n\nRecent activity shows Floodgate continuing to deploy capital across emerging sectors including AI infrastructure, developer tools, and consumer applications. They've been particularly active in the generative AI space, recognizing the platform shift early and positioning their portfolio accordingly. The firm typically invests $1-3 million in initial checks, reserving capital for follow-on investments in their highest-conviction companies.\n\nTheir fund sizes have grown over the years, though they've remained disciplined about not scaling beyond what allows them to maintain their hands-on approach. Floodgate often co-invests alongside other top-tier firms like [Sequoia Capital](companies/sequoia-capital) and [Andreessen Horowitz](companies/andreessen-horowitz), building syndicates that provide founders with diverse perspectives and networks. The firm runs a tight operation, believing that constraint breeds creativity—both for themselves and for the founders they back.",
"timeline": "- **2021-03-15** | Floodgate closes Fund VII at $181 million, continuing their focused seed-stage strategy\n- **2021-09-22** | Ann Miura-Ko speaks at TechCrunch Disrupt on identifying breakthrough startups\n- **2022-04-08** | Lead investment in AI developer tools company, $3.2M seed round\n- **2022-11-14** | Mike Maples Jr. publishes essay on \"thunder lizard\" thesis, gains wide circulation\n- **2023-02-28** | Portfolio company exits via acquisition by [Stripe](companies/stripe), returning 47x\n- **2023-08-19** | Floodgate announces Fund VIII targeting $200M for seed investments\n- **2024-01-10** | Partnership with Stanford's StartX program for deal flow collaboration\n- **2024-06-25** | Co-leads $8M seed round alongside [Sequoia Capital](companies/sequoia-capital) in robotics startup\n- **2025-03-12** | Ann Miura-Ko joins board of major fintech company following Series B\n- **2025-09-04** | Floodgate hosts annual founder summit in Palo Alto, 200+ portfolio founders attend",
"_facts": {
"type": "company",
"slug": "companies/floodgate-9",
"name": "Floodgate",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,29 +0,0 @@
{
"slug": "companies/forge-19",
"type": "company",
"title": "Forge",
"compiled_truth": "Forge is a crypto startup founded in 2022 by [Adam Lee](people/adam-lee-19), focused on building infrastructure for decentralized asset management. The company emerged during a turbulent period for the crypto industry, but Lee's vision for institutional-grade tooling attracted early believers despite market headwinds.\n\nThe core product is a non-custodial vault system that lets DAOs and crypto-native funds manage treasuries with multi-sig controls and on-chain governance integration. Forge differentiates itself by targeting the mid-market—organizations too sophisticated for basic multisigs but not large enough to justify custom smart contract development. Early traction came from several DeFi protocols looking to professionalize their treasury operations.\n\nFunding has come from angels with deep crypto experience. [Sarah Lopez](people/sarah-lopez-84) led the pre-seed round, bringing not just capital but introductions across the DeFi ecosystem. [Sarah Wang](people/sarah-wang-104) joined as an investor shortly after, drawn to the team's pragmatic approach to security. Both remain actively involved, participating in monthly strategy calls.\n\nOn the advisory side, Forge has assembled a small but impactful group. [Tara Jackson](people/tara-jackson-173) advises on go-to-market strategy, having scaled several B2B crypto companies previously. [David Brown](people/david-brown-187) provides technical guidance, particularly around smart contract auditing and security architecture—areas where Forge cannot afford to cut corners.\n\nThe team remains lean, hovering around twelve people as of late 2024. Adam has been deliberate about hiring, prefering experienced builders over rapid headcount growth. Engineering is split between protocol development and a surprisingly robust frontend team, reflecting the company's belief that UX remains crypto's biggest barrier to adoption.\n\nForge launched its mainnet product in early 2024 after an extended beta period. Growth has been steady if not explosive—the team claims over $180M in assets under managment across 40+ vaults. Revenue comes from a modest protocol fee, though the company has hinted at premium enterprise features in development. The roadmap includes cross-chain expansion and integration with traditional finance rails, positioning Forge at the intersection of DeFi and institutional money.",
"timeline": "- **2022-03-14** | Adam Lee incorporates Forge, begins building initial prototype for DAO treasury management\n- **2022-08-22** | Pre-seed round closes with [Sarah Lopez](people/sarah-lopez-84) leading; $1.2M raised\n- **2022-11-03** | [Sarah Wang](people/sarah-wang-104) joins as angel investor, contributes to security roadmap discussions\n- **2023-02-17** | [Tara Jackson](people/tara-jackson-173) signs on as go-to-market advisor\n- **2023-06-30** | Private beta launches with 8 DAOs onboarded for testing\n- **2023-09-12** | [David Brown](people/david-brown-187) joins advisory board to oversee smart contract security\n- **2024-01-28** | Mainnet launch after completing two independent audits\n- **2024-07-15** | Crosses $100M in assets under management milestone\n- **2024-11-02** | Announces partnership with major L2 for cross-chain vault support\n- **2025-02-10** | Team offsite in Lisbon; roadmap planning for enterprise tier features",
"_facts": {
"type": "company",
"slug": "companies/forge-19",
"name": "Forge",
"category": "startup",
"industry": "crypto",
"founded_year": 2022,
"founders": [
"people/adam-lee-19"
],
"investors": [
"people/sarah-lopez-84",
"people/sarah-wang-104"
],
"employees": [
"people/sam-nakamura-129"
],
"advisors": [
"people/tara-jackson-173",
"people/david-brown-187"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/founders-fund-0",
"type": "company",
"title": "Founders Fund",
"compiled_truth": "Founders Fund is a San Francisco-based venture capital firm that has become one of the most influential investors in technology over the past two decades. Founded in 2005 by Peter Thiel, Ken Howery, and Luke Nosek, the firm has distinguished itself through a contrarian investment philosophy that favors bold, transformative companies over incremental innovation. Their famous motto — \"We wanted flying cars, instead we got 140 characters\" — encapsulates this ethos.\n\nThe firm manages over $11 billion in assets and has backed some of the most consequential technology companies of the modern era. Early bets on SpaceX, Palantir, and Facebook established Founders Fund's reputation for identifying generational companies before they achieve mainstream recognition. More recently, the fund has made significant investments in defense technology, artificial intelligence, and biotechnology sectors.\n\nFounders Fund operates with a relatively lean partnership structure compared to traditional VC firms. Key partners include Thiel, Keith Rabois, and Brian Singerman, each bringing distinct investment theses to the table. Singerman in particular has driven the firm's biotech strategy, while Rabois focuses on enterprise software and fintech opportunities. The firm typically writes checks ranging from seed-stage investments up to growth rounds exceeding $100 million.\n\nTheir portfolio company [Anduril Industries](companies/anduril-industries) represents the quintessential Founders Fund investment — a defense technology company challenging incumbant contractors with software-defined hardware. Similarly, their continued support of [Stripe](companies/stripe) through multiple rounds demonstrates their conviction-based approach to backing founders.\n\nThe firm has been notably active in the AI space, making early investments in several frontier model companies. They've also shown willingness to back controversial founders and companies that other firms might avoid for reputational reasons. This approach has generated both outsized returns and occasional criticism.\n\nFounders Fund raised its eighth flagship fund in 2022, reportedly at $1.8 billion, signaling continued LP confidence despite broader market turbulence. The firm maintains offices in San Francisco and Austin, reflecting the broader tech migration trends of recent years.",
"timeline": "- **2021-03-15** | Led $450M growth round in Anduril Industries, valuing the defense startup at $4.6 billion\n- **2021-09-22** | Partner Keith Rabois announced relocation to Miami, opening satellite office presence\n- **2022-04-10** | Closed Fund VIII at $1.8B despite deteriorating market conditions\n- **2022-11-30** | Participated in emergency bridge financing discussions with [Stripe](companies/stripe) amid valuation reset\n- **2023-06-14** | Brian Singerman led investment in AI drug discovery platform, marking expanded biotech thesis\n- **2023-12-01** | Peter Thiel keynoted internal LP meeting on defense tech opportunities\n- **2024-05-18** | Announced strategic partnership with [Anduril Industries](companies/anduril-industries) for follow-on manufacturing facility investment\n- **2024-09-25** | Recruited two new partners from Tiger Global amid broader industry consolidation\n- **2025-02-11** | Published annual letter highlighting 3.2x net returns across 2020-2024 vintage\n- **2025-08-03** | Began fundraising for Fund IX, targeting $2.5B",
"_facts": {
"type": "company",
"slug": "companies/founders-fund-0",
"name": "Founders Fund",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,30 +0,0 @@
{
"slug": "companies/foundry-33",
"type": "company",
"title": "Foundry",
"compiled_truth": "Foundry is an AI applications startup founded in 2023 by [Ian Davis](people/ian-davis-33), a serial entrepreneur with a background in enterprise software. The company operates in the increasingly crowded AI applications space, though it has carved out a niche focusing on workflow automation for mid-market manufacturing companies. Their flagship product, FoundryOS, uses large language models to interpret unstructured data from factory floors and convert it into actionable insights for operations managers.\n\nThe company raised its seed round from a syndicate led by [Tina Hernandez](people/tina-hernandez-97), with participation from [Zoe Gonzalez](people/zoe-gonzalez-100) and [Alice Kapoor](people/alice-kapoor-108). Total funding to date sits around $4.2M, though rumors suggest Foundry is currently in conversations for a Series A that would value the company north of $30M. Ian has been characteristically tight-lipped about fundraising progress, preferring to focus public communications on product development.\n\nFoundry's advisory board includes [Rachel Gonzalez](people/rachel-gonzalez-175), who brings deep expertise in industrial automation, and [Noah Nakamura](people/noah-nakamura-182), whose connections in the manufacturing sector have reportedly helped open doors with several Fortune 500 prospects. The team has grown to roughly 18 people, mostly engineers, operating out of a small office in Austin.\n\nRecent moves include a partnership with a major automotive parts supplier, though the details remain under NDA. The company has been aggresively hiring ML engineers and recently posted roles for enterprise sales reps, signaling a shift toward scaling go-to-market efforts. Ian Davis presented at the Industrial AI Summit in March 2024, where he demoed FoundryOS processing real-time sensor data and generating maintenance recommendations. The demo received strong reception, though some attendees noted the system's latency issues under heavy load.\n\nFoundry faces competition from both established industrial software players and well-funded AI startups, but the team beleives their vertical focus gives them an edge. Early customer testimonials highlight the product's ease of integration with legacy systems, a persistent pain point in manufacturing tech.",
"timeline": "- **2023-03-15** | Foundry incorporated in Delaware by [Ian Davis](people/ian-davis-33)\n- **2023-06-22** | Closed $1.8M pre-seed round led by [Tina Hernandez](people/tina-hernandez-97)\n- **2023-09-10** | First engineering hires made; team moves into Austin office\n- **2023-12-01** | FoundryOS alpha launched with two pilot customers\n- **2024-02-14** | [Alice Kapoor](people/alice-kapoor-108) joins seed round, bringing total funding to $4.2M\n- **2024-03-28** | Ian Davis presents at Industrial AI Summit in Chicago\n- **2024-06-05** | Advisory board formalized with [Rachel Gonzalez](people/rachel-gonzalez-175) and [Noah Nakamura](people/noah-nakamura-182)\n- **2024-09-12** | Partnership announced with undisclosed automotive parts supplier\n- **2024-11-20** | Team reaches 18 employees; Series A conversations reportedly underway\n- **2025-01-08** | Enterprise sales hiring push begins",
"_facts": {
"type": "company",
"slug": "companies/foundry-33",
"name": "Foundry",
"category": "startup",
"industry": "AI applications",
"founded_year": 2023,
"founders": [
"people/ian-davis-33"
],
"investors": [
"people/tina-hernandez-97",
"people/zoe-gonzalez-100",
"people/alice-kapoor-108"
],
"employees": [
"people/wendy-taylor-143"
],
"advisors": [
"people/rachel-gonzalez-175",
"people/noah-nakamura-182"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/gamma-2",
"type": "company",
"title": "Gamma - Fintech Startup",
"compiled_truth": "Gamma is a fintech startup founded in 2022 by [Mark Jones](people/mark-jones-2), a serial entrepreneur with a background in payment infrastructure. The company has positioned itself at the intersection of embedded finance and small business lending, targeting an underserved market of micro-merchants who struggle to access traditional credit products.\n\nThe core product is a lending-as-a-service API that allows platforms to offer instant credit decisioning to their users. Gamma's approach relies on alternative data sources—transaction history, platform engagement metrics, and cash flow patterns—rather than traditional credit scores. This has allowed them to approve merchants that banks typically reject while maintaining what they claim are competitive default rates.\n\nMark Jones serves as CEO and has been the public face of the company since launch. His previous experience building payment rails for gig economy platforms informed much of Gamma's technical architecture. The founding team remains relatively small, with around 25 employees as of late 2024, mostly engineers and data scientists based in Austin.\n\nEarly backing came from [Vera Gonzalez](people/vera-gonzalez-103), who led the seed round and has remained actively involved as a board observer. Her portfolio expertise in B2B fintech reportedly helped Gamma avoid some common pitfalls around compliance and bank partnerships. The company has been somewhat quiet about total funding raised, though industry estimates put it somewhere in the $8-12M range across seed and bridge rounds.\n\nGamma faces stiff competiton from larger players like Stripe Capital and Square Loans, but has carved out a niche by focusing exclusively on platform partnerships rather than direct-to-merchant sales. Recent moves suggest they're expanding beyond pure lending into cash flow management tools, though details remain sparse. The company has been hiring aggressively for a Series A push expected sometime in 2025.",
"timeline": "- **2022-03-14** | Gamma incorporated in Delaware by [Mark Jones](people/mark-jones-2)\n- **2022-06-22** | Closed seed round led by [Vera Gonzalez](people/vera-gonzalez-103), terms undisclosed\n- **2022-11-08** | First API version shipped to beta partners\n- **2023-02-15** | Reached $1M in loans facilitated through platform\n- **2023-07-20** | Expanded engineering team to 15 employees\n- **2023-11-30** | Launched v2.0 of lending API with improved decisioning engine\n- **2024-04-12** | Mark Jones spoke at Fintech Summit Austin on alternative credit scoring\n- **2024-09-05** | Announced partnership with three unnamed e-commerce platforms\n- **2025-01-18** | Bridge round closed, preparing for Series A conversations",
"_facts": {
"type": "company",
"slug": "companies/gamma-2",
"name": "Gamma",
"category": "startup",
"industry": "fintech",
"founded_year": 2022,
"founders": [
"people/mark-jones-2"
],
"investors": [
"people/vera-gonzalez-103"
],
"employees": [
"people/tina-jones-112"
]
}
}
@@ -1,28 +0,0 @@
{
"slug": "companies/gamma-labs-52",
"type": "company",
"title": "Gamma Labs",
"compiled_truth": "Gamma Labs is an edtech startup founded in 2023 by [Iris Nakamura](people/iris-nakamura-52), a former learning sciences researcher who spent nearly a decade studying how students retain information in digital environments. The company emerged from Nakamura's frustration with existing adaptive learning platforms, which she felt were too focused on content delivery and not enough on genuine comprehension.\n\nThe core product is an AI-powered tutoring system that adapts not just to what students get wrong, but to *how* they think through problems. Gamma Labs calls this approach \"cognitive mirroring\" — the system builds a model of each student's reasoning patterns and adjusts its teaching style accordingly. Early pilots with community colleges showed promising results, though the sample sizes were admittedly small.\n\nFunding came through a pre-seed round led by [David Zhang](people/david-zhang-83), who has been increasingly active in education technology investments over the past two years. [Rosa Miller](people/rosa-miller-98) also participated in the round, bringing her experience scaling consumer apps to the cap table. The total raise was reportedly around $1.8 million, though the company hasn't confirmed exact figures publically.\n\nOn the advisory side, Gamma brought in [Steve Martinez](people/steve-martinez-192) to help navigate enterprise sales cycles with school districts. Martinez's background in B2B edtech has proven valuable as the startup shifts from direct-to-student pilots toward institutional contracts.\n\nThe team remains small — just seven full-time employees as of late 2024 — but they've been shipping quickly. Their beta platform launched in Q2 2024, and early users have praised the interface's simplicity. Critics note that the AI explanations can sometimes feel repetitive, a known issue the team says they're addressing.\n\nGamma Labs operates out of a coworking space in Oakland, though Iris has mentioned considering a move to a dedicated office if headcount doubles. The edtech space is crowded, but Gamma's focus on reasoning rather than rote memorization gives it a differentiated angle. Whether that translates to sustainable growth remains to be seen.",
"timeline": "- **2023-03-15** | Gamma Labs incorporated in Delaware by founder Iris Nakamura\n- **2023-06-22** | Pre-seed round closed with [David Zhang](people/david-zhang-83) and [Rosa Miller](people/rosa-miller-98) participating\n- **2023-09-10** | First pilot program launched with two community colleges in California\n- **2024-01-18** | [Steve Martinez](people/steve-martinez-192) joined as formal advisor\n- **2024-04-05** | Beta platform shipped to 500 early access users\n- **2024-07-12** | Gamma Labs presented at EdTech Summit in Austin, demo well-received\n- **2024-10-30** | Signed first enterprise contract with a mid-sized school district in Texas\n- **2025-02-14** | Team expanded to 12 employees, opened dedicated Oakland office\n- **2025-06-01** | Series A discussions reportedly underway with multiple firms",
"_facts": {
"type": "company",
"slug": "companies/gamma-labs-52",
"name": "Gamma Labs",
"category": "startup",
"industry": "edtech",
"founded_year": 2023,
"founders": [
"people/iris-nakamura-52"
],
"investors": [
"people/david-zhang-83",
"people/rosa-miller-98"
],
"employees": [
"people/ian-kapoor-162"
],
"advisors": [
"people/steve-martinez-192"
]
}
}
@@ -1,15 +0,0 @@
{
"slug": "companies/google-1",
"type": "company",
"title": "Google",
"compiled_truth": "Google is one of the most influential technology conglomerates in the world, though its founding date of 1996 places it slightly earlier than commonly cited. The company has evolved far beyond its origins as a search engine, becoming a major player in cloud computing, artificial intelligence, consumer hardware, and notably, robotics.\n\nThe robotics division at Google has seen significant investment and strategic maneuvering over the years. Starting with the aqusition of Boston Dynamics in 2013, Google signaled its intent to dominate the robotics space. While Boston Dynamics was later sold to SoftBank, Google retained numerous other robotics ventures and continued building internal capabilities through its X division and other research arms.\n\nAs an acquirer in the robotics industry, Google has been particularly agressive in targeting startups with promising automation technology. The company's approach tends to focus on companies developing AI-driven manipulation systems, warehouse automation, and autonomous systems that can integrate with Google's broader cloud and AI infrastructure. Their acquisition strategy often involves absorbing talented engineering teams rather than just acquiring technology—a practice sometimes called acqui-hiring.\n\nGoogle's parent company Alphabet provides the financial backing for these robotics ambitions. The company has partnerships with various research institutions and maintains close relationships with other tech giants, though it also competes fiercely with them. Recent moves suggest Google is positioning itself to offer robotics-as-a-service solutions to enterprise customers, leveraging its cloud platform.\n\nThe leadership at Google has emphasized that robotics represents a natural extension of their AI capabilities. With advances in machine learning and computer vision coming out of DeepMind and Google Brain (now merged), the company believes it can solve many of the perception and planning challenges that have historically limited robotic systems. Their focus areas include logistics automation, healthcare robotics, and general-purpose manipulation platforms that could eventaully find applications in homes and offices.\n\nGoogle continues to be a dominant force in shaping the future of intelligent machines, combining its vast computational resources with ambitious research agendas.",
"timeline": "- **2021-03-15** | Google announces expanded robotics research initiative under X division, committing $400M over three years\n- **2021-09-22** | Acquired stealth warehouse automation startup for undisclosed sum, team of 45 engineers joins Google Cloud\n- **2022-04-08** | Unveiled Everyday Robots project demonstrating general-purpose manipulation in office environments\n- **2022-11-30** | Partnership announced with major logistics provider to pilot autonomous sorting systems\n- **2023-06-14** | Google I/O keynote features live demo of AI-powered robotic assistant prototype\n- **2024-01-19** | Robotics division restructured, now reports directly to Google Cloud leadership\n- **2024-08-03** | Acquired computer vision startup specializing in 3D scene understanding for $180M\n- **2025-02-27** | Launched Robotics Foundation Model, open-sourcing base architecture for research community\n- **2025-10-11** | Enterprise robotics platform enters general availability, initial customers include three Fortune 100 companies",
"_facts": {
"type": "company",
"slug": "companies/google-1",
"name": "Google",
"category": "acquirer",
"industry": "robotics",
"founded_year": 1996
}
}
@@ -1,32 +0,0 @@
{
"slug": "companies/gravity-17",
"type": "company",
"title": "Gravity",
"compiled_truth": "Gravity is a biotech startup founded in 2021 by [Quinten Wang](people/quinten-wang-17), a computational biologist who previously led protein engineering efforts at a major pharma company. The company focuses on developing novel gravity-sensing mechanisms in cellular therapies, aiming to create treatments that respond to mechanical forces within the human body. Their core platform uses mechanosensitive proteins to trigger therapeutic payloads in response to specific gravitational or pressure conditions.\n\nThe founding thesis came from Wang's doctoral research on how cells detect and respond to physical forces. Gravity has raised seed funding from a syndicate that includes [Chris Jackson](people/chris-jackson-91), [Rosa Nakamura](people/rosa-nakamura-94), and [Rachel Brown](people/rachel-brown-95). The round closed in early 2022 and gave the company runway to build out its initial research team and secure wet lab space in the South San Francisco biotech corridor.\n\nOn the advisory side, Gravity has brought in [Tina Wang](people/tina-wang-179) for regulatory strategy and [Xavier Patel](people/xavier-patel-183) to help with business development and partnership discussions. Both advisors have been instrumental in shaping the companys go-to-market approach, particularly around identifying therapeutic areas where mechanosensitive delivery could provide clear advantages over existing modalties.\n\nThe startup has been relatively quiet publicly, preferring to focus on R&D milestones rather than press coverage. Internally, they've made progress on their lead program targeting osteoarthritis, where the therapy would activate in response to joint compression. Early in vitro results have been promising, though animal studies are still ongoing. The team has grown to about 15 people, mostly PhDs in bioengineering and cell biology.\n\nGravity faces significant technical risk—mechanobiology is still a nascent field and translating bench results to clinical outcomes will be challenging. But the upside is substantial if they can crack it. Wang has been vocal in investor updates about the potential for platform expansion into cardiac and oncology applications down the line.",
"timeline": "- **2021-03-15** | Gravity incorporated in Delaware by [Quinten Wang](people/quinten-wang-17)\n- **2021-07-22** | Signed lease for lab space in South San Francisco\n- **2022-01-10** | Closed $4.2M seed round led by [Chris Jackson](people/chris-jackson-91)\n- **2022-06-03** | Hired first VP of Research from Genentech\n- **2022-11-18** | [Tina Wang](people/tina-wang-179) joined as regulatory advisor\n- **2023-04-25** | Filed provisional patent on mechanosensitive protein delivery system\n- **2023-09-12** | Presented preclinical data at ASGCT conference\n- **2024-02-08** | Initiated IND-enabling studies for lead osteoarthritis program\n- **2024-08-30** | [Xavier Patel](people/xavier-patel-183) formalized advisory role, began pharma outreach\n- **2025-03-17** | Reached 15 employees, expanded lab footprint",
"_facts": {
"type": "company",
"slug": "companies/gravity-17",
"name": "Gravity",
"category": "startup",
"industry": "biotech",
"founded_year": 2021,
"founders": [
"people/quinten-wang-17"
],
"investors": [
"people/chris-jackson-91",
"people/rosa-nakamura-94",
"people/rachel-brown-95"
],
"employees": [
"people/quinn-jones-127"
],
"advisors": [
"people/tina-wang-179",
"people/xavier-patel-183",
"people/sam-garcia-188",
"people/beth-wang-196"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/greylock-4",
"type": "company",
"title": "Greylock Partners",
"compiled_truth": "Greylock Partners is one of Silicon Valley's oldest and most prestigious venture capital firms, founded in 1965. The firm has built a reputation for early-stage investing in enterprise software, consumer internet, and infrastructure companies. Their portfolio reads like a who's who of tech success stories—LinkedIn, Facebook, Airbnb, Dropbox, and Discord among them.\n\nThe firm operates with a relatively small partnership structure, which they argue allows for deeper engagement with founders. Notable partners include Reid Hoffman, the LinkedIn co-founder who joined after selling his company to Microsoft. The firm's been particularly active in AI and developer tools lately, reflecting broader market trends. They typically write checks ranging from seed to Series B, though they're not afraid to lead larger rounds for breakout companies.\n\nGreylock maintains offices in Menlo Park and San Francisco, though like most VCs they've adapted to a more distributed model post-pandemic. Their investment thesis centers on what they call \"product-first founders\"—technical leaders who deeply understand the problems they're solving. This approach has led them to back companies like Figma early, before design tools became a hot category.\n\nThe partnership has been vocal about their views on AI, with several partners publishing extensively on where they see oportunities in the space. They've made multiple bets on AI infrastructure and application layers. Recent portfolio companies include Adept AI and various developer productivity startups.\n\nUnlike some mega-funds, Greylock has resisted the temptation to raise massive vehicles, generally keeping fund sizes in the $1-2 billion range. This discipline, they argue, keeps them focused on early-stage where they have the most edge. The firm competes directly with [Sequoia Capital](companies/sequoia-capital) and [Andreessen Horowitz](companies/a16z-3) for the best deals, though each firm has developed somewhat distinct positioning over time.\n\nTheir brand among founders remains strong, particularly for B2B and infrastructure plays. The firm hosts regular content series and podcasts featuring partners discussng market trends, which serves both as thought leadership and deal flow generation.",
"timeline": "- **2021-03-15** | Led $40M Series B in Snyk, continuing their security software thesis\n- **2021-09-22** | Reid Hoffman published essay on future of work, generating significant discussion in tech media\n- **2022-02-08** | Announced Fund XVI at $1.2 billion, focused on AI and enterprise\n- **2022-11-30** | Participated in Discord's $500M round alongside [Sequoia Capital](companies/sequoia-capital)\n- **2023-04-17** | Partner Sarah Guo departed to launch her own AI-focused fund Conviction\n- **2023-08-25** | Led seed round for stealth AI infrastructure startup\n- **2024-01-12** | Hosted annual Greylock Techfair recruiting event for portfolio companies\n- **2024-06-03** | Published internal AI research report, shared selectively with LPs\n- **2024-11-19** | Co-invested with [Andreessen Horowitz](companies/a16z-3) in Series A for developer tools company\n- **2025-02-28** | Promoted two principals to partner, signaling generational transition",
"_facts": {
"type": "company",
"slug": "companies/greylock-4",
"name": "Greylock",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/gust-34",
"type": "company",
"title": "Gust",
"compiled_truth": "Gust is a data infrastructure startup founded in 2020 by [Steve Liu](people/steve-liu-34), who previously spent time at Snowflake and Databricks before striking out on his own. The company focuses on building real-time data pipelines that can handle massive throughput without the typical overhead of traditional ETL systems. Their core product lets engineering teams ingest, transform, and route streaming data with minimal configuration—think Kafka meets dbt but with a much simpler developer experience.\n\nThe founding story is pretty straightforward. Steve had grown frustrated with the complexity of existing data infrastructure tools while working on analytics pipelines at his previous roles. He saw an opportunity to build something cleaner, something that didn't require a dedicated platform team just to keep running. Gust was born out of that frustration, initially as a side project before Steve commited to it full-time.\n\nEarly traction came from mid-sized fintech companies who needed reliable streaming infrastructure but couldn't justify the headcount to manage Kafka clusters. Gust's managed offering hit a sweet spot—enterprise-grade reliability without the operational burden. By late 2021, the company had a handful of paying customers and was generating modest but growing revenue.\n\n[Sarah Lopez](people/sarah-lopez-84) led their seed round in early 2022, betting on Steve's technical chops and the growing demand for simplified data tooling. Sarah had been tracking the data infrastructure space for years and saw Gust as a potential breakout player. Her investment gave the company runway to expand the engineering team and accelerate product developement.\n\nToday Gust operates with a lean team of about 25 people, mostly engineers. They've been deliberate about not over-hiring, preferring to stay focused and capital-efficient. The company has expanded its product to include schema management, data quality monitoring, and connectors for most major data warehouses. Competition from bigger players like Confluent and newer startups remains intense, but Gust has carved out a loyal customer base that values simplicity over feature bloat.",
"timeline": "- **2020-03-15** | Steve Liu incorporates Gust and begins building the initial prototype\n- **2020-09-22** | First beta customer signs up—a small fintech startup in NYC\n- **2021-04-10** | Gust launches publicly with support for Postgres and Snowflake sinks\n- **2022-02-08** | Closes $4.2M seed round led by [Sarah Lopez](people/sarah-lopez-84)\n- **2022-07-19** | Hires first head of engineering from Stripe\n- **2023-01-30** | Launches schema registry feature after months of customer requests\n- **2023-11-14** | [Steve Liu](people/steve-liu-34) speaks at Data Council on simplifying streaming architectures\n- **2024-05-02** | Crosses 100 paying customers milestone\n- **2024-12-11** | Announces partnership with major cloud provider for native integration\n- **2025-08-20** | Begins work on Series A fundraising process",
"_facts": {
"type": "company",
"slug": "companies/gust-34",
"name": "Gust",
"category": "startup",
"industry": "data infrastructure",
"founded_year": 2020,
"founders": [
"people/steve-liu-34"
],
"investors": [
"people/sarah-lopez-84"
],
"employees": [
"people/xavier-jackson-144"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/hatch-35",
"type": "company",
"title": "Hatch",
"compiled_truth": "Hatch is an edtech startup founded in 2019 by [Eric Miller](people/eric-miller-35), who saw an opportunity to reimagine how young professionals develop career skills outside traditional academic settings. The company operates in the increasingly crowded learn-to-earn space, but distinguishes itself through a cohort-based model that emphasizes peer accountability and real-world project work.\n\nThe platform connects early-career workers with mentors from established companies, facilitating structured 8-week programs in areas like product management, data analytics, and business development. Hatch takes a different aproach than most competitors—rather than selling courses to individuals, they partner directly with employers who want to upskill entry-level hires or create alternative talent pipelines. This B2B focus has given them more predictable revenue, though it's also meant slower user growth compared to consumer-facing platforms.\n\n[Steve Martinez](people/steve-martinez-192) joined as an advisor sometime in 2022, bringing his network in workforce development and helping Hatch refine their enterprise sales motion. His involvement signaled a shift toward targeting larger organizations rather than the SMB market they'd initially pursued. Martinez has been particularly helpful in opening doors at companies looking to diversify their hiring beyond traditional university recruiting.\n\nEric Miller remains the driving force behind product decisions. He's known for being hands-on with curriculum design, often personally reviewing program content and sitting in on mentor sessions. Some employees find this level of involvement micromanage-y, but others appreciate the attention to quality. The company has stayed relatively lean—around 35 employees as of late 2024—and Miller has been vocal about not raising more capital than necessary.\n\nHatch completed a Series A in early 2023, though they haven't disclosed the amount publicly. They're headquartered in Austin but operate fully remote, with mentors and participants spread across North America. Recent moves suggest they're exploring expansion into technical skills training, potentially competing more directly with bootcamps.",
"timeline": "- **2019-06-12** | Hatch incorporated in Delaware; [Eric Miller](people/eric-miller-35) begins building initial prototype\n- **2020-03-08** | Launched first pilot cohort with 24 participants across three employer partners\n- **2021-09-15** | Closed seed round of $2.4M led by Reach Capital\n- **2022-04-22** | [Steve Martinez](people/steve-martinez-192) formally joins advisory board\n- **2022-11-03** | Surpassed 2,000 program graduates; announced partnership with two Fortune 500 retailers\n- **2023-02-17** | Series A closed; terms undisclosed but reportedly in $8-12M range\n- **2023-08-29** | Launched data analytics track, first technical program offering\n- **2024-01-14** | Eric Miller spoke at ASU+GSV Summit on alternative credentialing\n- **2024-07-20** | Opened pilot in Canada with three Toronto-based employers\n- **2025-03-11** | Announced curriculum partnership with major cloud provider for technical upskilling",
"_facts": {
"type": "company",
"slug": "companies/hatch-35",
"name": "Hatch",
"category": "startup",
"industry": "edtech",
"founded_year": 2019,
"founders": [
"people/eric-miller-35"
],
"employees": [
"people/diana-brown-145"
],
"advisors": [
"people/steve-martinez-192"
]
}
}
@@ -1,26 +0,0 @@
{
"slug": "companies/helix-9",
"type": "company",
"title": "Helix",
"compiled_truth": "Helix is an AI infrastructure startup founded in 2021 by [Rachel Garcia](people/rachel-garcia-9), a veteran systems engineer who previously led distributed computing teams at major cloud providers. The company focuses on building foundational tooling for deploying and managing large-scale machine learning workloads, with particular emphasis on GPU orchestration and model serving optimization.\n\nThe core product is a Kubernetes-native platform that abstracts away much of the complexity involved in running inference at scale. Helix's approach differs from competitors in that it prioritizes cost efficiency over raw performance—their scheduling algorithms are designed to maximize GPU utilization across heterogenous hardware, which appeals to companies running mixed fleets of older and newer accelerators. Early customers include several mid-size fintech firms and a handful of healthcare AI startups.\n\nRachel Garcia serves as CEO and has been the public face of the company since launch. She's known for her pragmatic approach to infrastructure problems and has spoken at several industry conferences about the \"unsexy\" challenges of ML ops. Under her leadership, Helix has grown to roughly 35 employees, mostly engineers with backgrounds in distributed systems and cloud infrastucture.\n\nThe advisory board includes [Xavier Patel](people/xavier-patel-183), who brings deep expertise in enterprise sales and go-to-market strategy, and [Bob Chen](people/bob-chen-185), a technical advisor with experience scaling infrastructure at hypergrowth companies. Both have been instrumental in shaping Helix's enterprise positioning.\n\nHelix raised a Series A in early 2023, though the company has been relatively quiet about specific metrics. Industry observers note that the AI infrastructure space has become increasingly crowded, but Helix's focus on cost optimization rather than cutting-edge performance gives it a distinct niche. The startup has been expanding its sales team and recently opened a small office in Austin to complement its San Francisco headquarters. Recent product updates have focused on observability features and tighter integrations with popular ML frameworks.",
"timeline": "- **2021-03-15** | Company incorporated by [Rachel Garcia](people/rachel-garcia-9) in Delaware\n- **2021-09-02** | Closed $4.2M seed round led by Gradient Ventures\n- **2022-01-18** | First production customer goes live on Helix platform\n- **2022-07-11** | [Xavier Patel](people/xavier-patel-183) joins as advisor to help with enterprise strategy\n- **2023-02-28** | Announced Series A funding, expanded engineering team to 25\n- **2023-08-14** | [Bob Chen](people/bob-chen-185) joins advisory board\n- **2024-01-22** | Launched Helix Observe, new monitoring and cost analytics product\n- **2024-06-09** | Rachel Garcia keynotes at MLOps World conference in Austin\n- **2024-11-03** | Opened Austin office, announced plans to double sales team\n- **2025-04-17** | Partnership announced with major cloud provider for marketplace listing",
"_facts": {
"type": "company",
"slug": "companies/helix-9",
"name": "Helix",
"category": "startup",
"industry": "AI infrastructure",
"founded_year": 2021,
"founders": [
"people/rachel-garcia-9"
],
"employees": [
"people/quinn-park-119"
],
"advisors": [
"people/xavier-patel-183",
"people/bob-chen-185",
"people/victor-smith-193"
]
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/helix-labs-59",
"type": "company",
"title": "Helix Labs",
"compiled_truth": "Helix Labs is a cybersecurity startup founded in 2020 by [Bob Jackson](people/bob-jackson-59), a former penetration tester who spent nearly a decade at major defense contractors before striking out on his own. The company focuses on automated threat detection for mid-market enterprises, a segment Jackson felt was underserved by existing solutions that either targeted Fortune 500 companies or were too basic for sophisticated threats.\n\nThe company's flagship product, HelixShield, uses behavioral analysis to identify anomalous network activity before breaches occur. Unlike traditional signature-based detection, their approach learns what 'normal' looks like for each client and flags deviations in real-time. Early customers have praised the low false-positive rate, though some have noted the onboarding process can be lengthy.\n\nHelix raised its seed round in late 2021 from angel investors including [Priya Taylor](people/priya-taylor-85) and [Julia Davis](people/julia-davis-86), both of whom have backgrounds in enterprise software. Priya in particular has been an active advisor, reportedly introducing the team to several key enterprise clients in the healthcare vertical. The company closed a Series A in 2023, though terms were not publicly disclosed.\n\nThe team has grown to around 45 employees, with engineering concentrated in Austin and a small sales presence in New York. Jackson remains CEO and is known for his hands-on technical involvement—he still reviews major architecture decisions and ocasionally jumps into customer calls when things get hairy. Former colleagues describe him as demanding but fair, with a tendency to work late nights that sometimes sets unrealistic expectations for the rest of the team.\n\nHelix Labs has been relatively quiet in terms of press, preferring to let customer referrals drive growth rather than splashy marketing campaigns. That said, there's been some chatter about a potential expansion into cloud security posture management, which would put them in direct competition with larger players. Whether they have the resources to fight on multiple fronts remaind to be seen.",
"timeline": "- **2020-03-15** | Helix Labs incorporated in Delaware by [Bob Jackson](people/bob-jackson-59)\n- **2020-09-22** | First prototype of HelixShield deployed internally for testing\n- **2021-06-10** | Closed seed round with participation from [Priya Taylor](people/priya-taylor-85) and [Julia Davis](people/julia-davis-86)\n- **2021-11-03** | Landed first paying customer, a regional hospital network in Texas\n- **2022-04-18** | Expanded engineering team to 20 people, opened Austin office\n- **2023-02-27** | Series A closed; valuation undisclosed but rumored around $40M\n- **2023-09-14** | HelixShield 2.0 launched with improved ML detection pipeline\n- **2024-05-06** | [Bob Jackson](people/bob-jackson-59) spoke at RSA Conference on behavioral threat detection\n- **2025-01-22** | Announced partnership with managed security provider NorthWatch\n- **2025-08-30** | Internal planning meetings hint at cloud security product expansion",
"_facts": {
"type": "company",
"slug": "companies/helix-labs-59",
"name": "Helix Labs",
"category": "startup",
"industry": "cybersecurity",
"founded_year": 2020,
"founders": [
"people/bob-jackson-59"
],
"investors": [
"people/priya-taylor-85",
"people/julia-davis-86"
],
"employees": [
"people/sam-wilson-169"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/index-ventures-7",
"type": "company",
"title": "Index Ventures",
"compiled_truth": "Index Ventures is one of Europe's most storied venture capital firms, with a track record that spans three decades and includes some of the most consequential technology companies of the modern era. Founded in Geneva in 1996, the firm has grown to operate across offices in San Francisco, London, and Geneva, positioning itself as a truly transatlantic investor with deep roots on both sides of the pond.\n\nThe firm operates across multiple stages, from seed through growth, and has backed companies like Figma, Discord, Notion, Roblox, and Deliveroo. Index made early bets on European champions like Skype and King Digital, establishing its reputation for identifying category-defining companies before they hit mainstream radar. Their portfolio reflects a broad thesis covering enterprise software, fintech, consumer internet, and increasingly, AI-native applications.\n\nIndex is known for its partnership-driven model, where partners maintain significant autonomy in dealmaking while sharing economics equally. Notable partners include Danny Rimer, who led investments in Dropbox and Glossier, and Mike Volpi, a former Cisco executive who's become one of the most respected enterprise investors in the industry. The firm's approach tends to be founder-friendly, often taking board seats but avoiding the heavy-handed governance that characterizes some of their peers.\n\nRecent years have seen Index raising substantial funds—their 2021 vintage exceeded $3 billion across seed and growth vehicles. They've been particularly active in the AI infrastructure space, competing aggressively with firms like [Sequoia Capital](companies/sequoia-capital-12) for the hottest deals. Some partners have noted tension between maintaining their European identity while increasingly deploying capital into Silicon Valley's AI boom.\n\nThe firm has also made notable investments alongside [Andreessen Horowitz](companies/andreessen-horowitz-9) in several high-profile rounds, demonstrating their ability to co-invest with top-tier American firms while maintaining deal leadership. Index's LP base includes major endowments, sovereign wealth funds, and family offices who've stuck with the firm through multiple fund cycles.\n\nCriticism sometimes surfaces around their growth-stage valuations—some observers argue Index overpaid during the 2021 bubble. But their seed practice has remained disciplined, and their multi-stage model provides natural follow-on optionality that pure-play seed funds lack.",
"timeline": "- **2021-03-15** | Closed Index Ventures Growth VI at $2.3B, largest fund in firm history\n- **2021-09-22** | Led $150M Series C for AI startup alongside [Sequoia Capital](companies/sequoia-capital-12)\n- **2022-04-10** | Partner Martin Mignot promoted to lead European seed practice\n- **2022-11-08** | Portfolio company Figma announced $20B acquisition by Adobe (later terminated)\n- **2023-02-14** | Participated in Discord's down round, maintaining pro-rata\n- **2023-08-30** | Co-led infrastructure deal with [Andreessen Horowitz](companies/andreessen-horowitz-9) at $800M valuation\n- **2024-01-19** | Published annual European tech ecosystem report showing record unicorn creation\n- **2024-06-05** | Danny Rimer keynoted at Index's annual founder summit in London\n- **2025-02-28** | Announced new $1.8B early-stage fund focused on AI-native applications\n- **2025-09-12** | Opened small Tel Aviv office to expand Middle East dealflow",
"_facts": {
"type": "company",
"slug": "companies/index-ventures-7",
"name": "Index Ventures",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/initialized-11",
"type": "company",
"title": "Initialized Capital",
"compiled_truth": "Initialized Capital is a seed-stage venture capital firm that made a significant mark on Silicon Valley's early-stage investing landscape. Founded in 2011 by Alexis Ohanian and Garry Tan, the firm quickly established itself as a go-to partner for ambitious founders building transformative companies. Initialized became known for writing the first checks into startups that would go on to become household names.\n\nThe firm's portfolio included some remarkable successes. Coinbase, Instacart, Cruise Automation, and Flexport all received early backing from Initialized, demonstrating the partners' ability to identify breakout opportunities before they became obvious. The fund's investment thesis centered on backing technical founders with strong product instincts, often at the pre-seed or seed stage when most institutional investors wouldn't engage.\n\nGarry Tan served as managing partner and was the driving force behind much of the firm's deal flow and investment decisions. His background as a founder (he co-founded Posterous) and his time as a partner at Y Combinator gave him unique insight into what makes early-stage companies succeed. In 2022, Tan departed Initialized to take on the role of President and CEO at [Y Combinator](companies/y-combinator), leaving the firm at an inflection point.\n\nFollowing Tan's departure, the future of Initalized became somewhat uncertain. The firm had raised multiple funds over the years, with later vehicles exceeding $300 million in committed capital. Some partners continued to manage existing investments while the firm's active deployment slowed considerably.\n\nInitialized was part of a broader wave of seed-focused firms that emerged in the early 2010s, alongside peers like First Round Capital and [Floodgate](companies/floodgate). These micro-VCs helped fill a gap left by larger funds that had moved upstream to Series A and beyond. The firm's legacy lives on through its portfolio companies, many of wich continue to shape their respective industries. Alexis Ohanian has since focused his attention on other ventures, including Seven Seven Six, his newer investment vehicle.",
"timeline": "- **2011-06-15** | Initialized Capital founded by Alexis Ohanian and Garry Tan with a focus on seed-stage investments\n- **2017-03-22** | Closed Fund III at $225 million, marking significant growth from earlier vehicles\n- **2019-09-10** | Portfolio company Coinbase valuation exceeds $8 billion following private funding round\n- **2021-04-14** | Coinbase direct listing on NASDAQ delivers massive returns for early Initialized investment\n- **2022-01-18** | Garry Tan announced as incoming CEO of [Y Combinator](companies/y-combinator), signaling transition at Initialized\n- **2022-03-01** | Tan officially departs managing partner role to lead YC full-time\n- **2023-08-12** | Firm continues managing existing portfolio with reduced new investment activity\n- **2024-02-28** | Several Initialized portfolio companies announce down rounds amid market correction\n- **2025-05-14** | Legacy fund distributions continue as mature portfolio companies reach liquidity events",
"_facts": {
"type": "company",
"slug": "companies/initialized-11",
"name": "Initialized",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/iris-36",
"type": "company",
"title": "Iris",
"compiled_truth": "Iris is a consumer social startup founded in 2024 by [Mia Park](people/mia-park-36), a first-time founder with a background in behavioral psychology and product design. The company is building what it describes as a \"mood-first\" social platform—users share emotional states and context rather than polished photos or status updates. The core thesis is that Gen Z craves authenticity but existing platforms still incentivize performance. Iris flips that by making vulnerability the default.\n\nThe app launched in closed beta in late 2024, initially targeting college campuses on the West Coast. Early traction was promising, with retention numbers that caught the attention of several angel investors. [Jack Davis](people/jack-davis-89) led a pre-seed round, drawn to Mia's unconventional approach and the product's sticky engagement loops. He's been hands-on, joining weekly product reviews and pushing the team to nail the onboarding flow before scaling.\n\nIris operates with a lean team of five, mostly engineers and one designer Mia poached from her previous gig at a larger social app. The company runs out of a cramped co-working space in San Francisco's Mission district. Culture is intense but collaborative—Mia sets aggressive ship cycles but also mandates \"disconnect Fridays\" to prevent burnout. There's a scrappy energy to the operation.\n\n[David Kim](people/david-kim-186) serves as an advisor, providing strategic guidence on growth tactics and helping Mia navigate the fundraising landscape. He's introduced her to several potential Series A leads, though the company isn't actively raising yet. The plan is to hit 100k MAU before pursuing a priced round.\n\nRecent product moves include a \"resonance\" feature that matches users with strangers experiencing similar emotional states. It's controversial internally—some worry about safety implications—but early data shows it drives significent engagement. Mia has publicly stated that Iris will never sell emotional data to advertisers, a stance that's resonated with privacy-conscious users but raises questions about eventual monetization.",
"timeline": "- **2024-01-15** | [Mia Park](people/mia-park-36) incorporates Iris and begins recruiting founding team\n- **2024-03-22** | Closed alpha launches with 200 users from Stanford and Berkeley\n- **2024-05-10** | [Jack Davis](people/jack-davis-89) commits to leading pre-seed round after demo day pitch\n- **2024-06-01** | Pre-seed closes at $1.2M, valuation undisclosed\n- **2024-08-14** | [David Kim](people/david-kim-186) joins as formal advisor\n- **2024-10-03** | Beta expands to 12 universities across California and Oregon\n- **2024-11-19** | \"Resonance\" feature ships, driving 40% increase in daily sessions\n- **2025-01-08** | Iris hits 25k monthly active users milestone\n- **2025-02-20** | Mia speaks at a consumer social meetup in SF about emotional-first design\n- **2025-04-12** | Company begins exploratory conversations with Series A investors",
"_facts": {
"type": "company",
"slug": "companies/iris-36",
"name": "Iris",
"category": "startup",
"industry": "consumer social",
"founded_year": 2024,
"founders": [
"people/mia-park-36"
],
"investors": [
"people/jack-davis-89"
],
"employees": [
"people/david-anderson-146"
],
"advisors": [
"people/david-kim-186"
]
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/jolt-37",
"type": "company",
"title": "Jolt - AI Applications Startup",
"compiled_truth": "Jolt is an early-stage startup founded in 2025 by [Chris Williams](people/chris-williams-37), operating in the AI applications space. The company emerged during a particularly competitive period for AI ventures, yet managed to secure backing from notable angel investors including [Tina Hernandez](people/tina-hernandez-97) and [Chris Miller](people/chris-miller-101).\n\nThe company focuses on building AI-powered productivity tools aimed at small and medium businesses. Their flagship product, still in development, promises to automate routine administrative tasks using a combination of large language models and custom workflow engines. Chris Williams has described the vision as \"AI that actually fits into how people already work, not the other way around.\"\n\nJolt operates with a lean team, currently around 8 people, mostly engineers with backgrounds in ML infrastructure and frontend development. The company maintains offices in Austin, though most of the team works remotley. Williams has been vocal about keeping the team small until they achieve stronger product-market fit, a philosophy he picked up from his previous startup experience.\n\nFunding details remain somewhat private, but sources suggest the initial round was in the $2-3M range. [Chris Miller](people/chris-miller-101) reportedly led the round after meeting Williams at a conference in late 2024. The investment thesis centered on Williams' track record and the team's technical depth rather than any revolutionary technology moat.\n\nThe startup has been relatively quiet publicly, preferring to focus on building rather than marketing. A private beta launched in Q1 2025 with around 50 companies participating. Early feedback has been mixed but promising—users appreciate the simplicity but want more integrations. The team is currently heads-down on expanding connector support for popular tools like Slack, Notion, and various CRMs.\n\nCompetition in the AI productivity space is fierce, with both well-funded startups and big tech players vying for attention. Jolt's bet is that their focus on SMBs and ease of deployment will carve out a defensible niche. Whether that pans out remains to be seen.",
"timeline": "- **2024-11-15** | Chris Williams meets [Chris Miller](people/chris-miller-101) at AI Summit Austin, initial discussions about Jolt concept\n- **2025-01-08** | Jolt officially incorporated in Delaware\n- **2025-01-22** | Seed round closes with participation from [Tina Hernandez](people/tina-hernandez-97) and Chris Miller\n- **2025-02-10** | First two engineers hired, both former colleagues of [Chris Williams](people/chris-williams-37)\n- **2025-03-05** | Internal alpha of core product completed\n- **2025-04-12** | Private beta launches with 50 SMB partners\n- **2025-05-20** | Team expands to 8 people, adds first dedicated product manager\n- **2025-06-18** | Partnership discussions begin with major CRM vendor\n- **2025-07-02** | Beta feedback review leads to pivot toward deeper integrations focus",
"_facts": {
"type": "company",
"slug": "companies/jolt-37",
"name": "Jolt",
"category": "startup",
"industry": "AI applications",
"founded_year": 2025,
"founders": [
"people/chris-williams-37"
],
"investors": [
"people/tina-hernandez-97",
"people/chris-miller-101"
],
"employees": [
"people/xavier-johnson-147"
]
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/keel-38",
"type": "company",
"title": "Keel",
"compiled_truth": "Keel is a crypto startup founded in early 2025 by [Steve Williams](people/steve-williams-38), a serial entrepreneur with a background in decentralized finance protocols. The company operates in the digital asset infrastructure space, focusing on building institutional-grade custody and settlement solutions for blockchain networks. Despite being a newcomer to an already crowded market, Keel has positioned itself as a lean alternative to legacy crypto custodians, emphasizing speed and regulatory compliance from day one.\n\nThe founding thesis behind Keel centers on the belief that traditional crypto custody providers have become bloated and slow to adapt to emerging Layer 2 ecosystems. Steve Williams has been vocal about this gap, arguing that institutions need nimble partners who understand the nuances of rollups, bridges, and cross-chain liquidity. The company's initial product focuses on Ethereum L2 settlement, with plans to expand into Bitcoin sidechains by late 2025.\n\nKeel raised a pre-seed round in Q1 2025, with [Carol Jackson](people/carol-jackson-81) serving as the lead investor. Jackson, known for her contrarian bets in fintech infrastructure, apparently saw potential in Williams' vision despite the bear market sentiment still lingering from 2024. The round was modest—reportedly under $3 million—but gave the team runway to build out their core platform and hire a small enginering team.\n\nAdvisory support comes from [Linda Taylor](people/linda-taylor-178), who brings regulatory expertise to the table. Taylor's involvement signals that Keel is serious about compliance, a differentiator in an industry still grappling with enforcement actions. Her guidance has reportedly shaped the company's approach to KYC/AML integration and its conversations with potential banking partners.\n\nThe team remains small, operating out of a co-working space in Austin. Williams has kept headcount intentionally low, preferring to ship fast with a tight-knit group rather than scale prematurely. Early users include a handful of crypto-native hedge funds testing the settlement infrastucture in sandbox environments. Keel's public launch is expected sometime in Q3 2025.",
"timeline": "- **2024-11-15** | Steve Williams begins exploratory conversations with early backers about a new custody venture\n- **2025-01-08** | Keel officially incorporated in Delaware; [Steve Williams](people/steve-williams-38) named CEO\n- **2025-01-22** | [Carol Jackson](people/carol-jackson-81) commits to leading the pre-seed round\n- **2025-02-10** | Pre-seed funding closes at $2.8M; team begins hiring engineers\n- **2025-02-28** | [Linda Taylor](people/linda-taylor-178) joins as regulatory advisor\n- **2025-03-15** | First internal demo of L2 settlement prototype completed\n- **2025-04-02** | Keel signs NDA with two crypto hedge funds for pilot testing\n- **2025-05-19** | Williams speaks at ETH Denver satellite event on institutional DeFi infrastructure\n- **2025-06-07** | Sandbox testing begins with select institutional partners",
"_facts": {
"type": "company",
"slug": "companies/keel-38",
"name": "Keel",
"category": "startup",
"industry": "crypto",
"founded_year": 2025,
"founders": [
"people/steve-williams-38"
],
"investors": [
"people/carol-jackson-81"
],
"employees": [
"people/zoe-nakamura-148"
],
"advisors": [
"people/linda-taylor-178"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/khosla-ventures-8",
"type": "company",
"title": "Khosla Ventures",
"compiled_truth": "Khosla Ventures is a prominent Silicon Valley venture capital firm founded in 2004 by Vinod Khosla, a co-founder of Sun Microsystems. The firm has established itself as one of the most influential investors in technology and cleantech, with a particular focus on companies that can have transformative impact across industries. Headquartered in Menlo Park, California, Khosla operates with a distinctive philosophy that embraces high-risk, high-reward bets on unproven technologies.\n\nThe firm manages multiple funds totaling billions in assets under managment, including seed funds for earlier-stage investments and larger growth funds for follow-on financing. Khosla Ventures has backed some notable successes including Square, DoorDash, and Instacart. More recently, the firm has been aggressively investing in artificial intelligence infrastructure and applications, recognizing the generational shift hapening in enterprise software.\n\nVinod Khosla himself remains deeply involved in investment decisions and is known for his contrarian views and willingness to fund moonshot ideas. The firm's team includes partners with deep technical backgrounds, which allows them to evaluate complex technologies that other VCs might shy away from. They've developed a reputation for being founder-friendly while also providing substantial operational support.\n\nKhosla Ventures has been particularly active in climate tech, betting big on carbon capture, alternative proteins, and next-generation energy storage. This aligns with Vinod's long-standing interest in technologies that address major societal challenges. The firm often co-invests alongside other major venture players like [Andreessen Horowitz](companies/a16z) on larger rounds, though they're equally comfortable leading deals solo.\n\nTheir investment approach tends to be thesis-driven rather than opportunistic. Partners develop deep conviction around specific technology shifts and then actively seek out founders building in those areas. This has led to early positions in categories before they become crowded. The firm maintains close relationships with the Stanford ecosystem and frequently backs technical founders straight out of PhD programs. Recent portfolio companies have explored everything from quantum computing to synthetic biology, reflecting Khosla's continued appetite for frontier tech bets.",
"timeline": "- **2021-03-15** | Khosla Ventures closed Fund VII at $1.4 billion, oversubscribed due to strong LP demand\n- **2021-09-22** | Led $50M Series B in carbon removal startup, signaling renewed climate focus\n- **2022-04-08** | Vinod Khosla keynoted Stanford entrepreneurship conference on AI's transformative potential\n- **2022-11-30** | Announced strategic partnership with [Andreessen Horowitz](companies/a16z) for joint investment in AI infrastructure deals\n- **2023-06-14** | Portfolio company Impossible Foods explored IPO options with firm's guidance\n- **2023-12-01** | Khosla published annual predictions letter, forecasting major disruption in healthcare from AI diagnostics\n- **2024-05-19** | Promoted two new general partners from within, expanding investment team to twelve\n- **2024-09-03** | Led $120M growth round for enterprise AI startup at $900M valuation\n- **2025-02-28** | Filed for Fund VIII targeting $2.1 billion across seed and growth vehicles\n- **2025-08-11** | Hosted annual LP summit in Palo Alto featuring portfolio company demos",
"_facts": {
"type": "company",
"slug": "companies/khosla-ventures-8",
"name": "Khosla Ventures",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/kindle-20",
"type": "company",
"title": "Kindle - Climate Tech Startup",
"compiled_truth": "Kindle is a climate tech startup founded in 2023 by [Vera Singh](people/vera-singh-20), focused on developing next-generation carbon capture solutions for industrial emitters. The company emerged from Singh's doctoral research at MIT, where she pioneered novel membrane technologies that significantly reduce the energy costs of direct air capture.\n\nThe startup operates out of Oakland, California, with a small but growing team of around 15 engineers and scientists. Kindle's core product is a modular carbon capture unit designed for mid-sized manufacturing facilities—a market segment that's been largely overlooked by bigger players chasing utility-scale deployments. Their approach prioritizes affordability and ease of installation over raw capture volume, betting that widespread adoption matters more than individual unit performance.\n\nKindle has attracted notable advisors including [Tina Moore](people/tina-moore-191), who brings decades of experience scaling hardware startups. Moore's involvement has been particularly valuable in helping the company navigate supply chain challenges and establish early manufacturing partnerships. The advisory relationship reportedly began after a chance meeting at a climate conference in late 2023.\n\nThe company closed a seed round in early 2024, though exact figures haven't been publicly disclosed. Industry sources suggest somewhere in the $4-6M range, with participation from several climate-focused VCs and a strategic investment from a major cement manufacturer. Vera has been quoted saying the cement partnership represents exactly the kind of industrial collaboration Kindle needs to prove out thier technology at scale.\n\nRecent activity suggests Kindle is preparing for pilot deployments at two manufacturing sites in the midwest, with plans to gather operational data through 2025. The team has been hiring aggressivley for field engineering roles, a sign that real-world testing is imminent. Competition in the carbon capture space remains fierce, but Kindle's focus on the underserved mid-market could give them a meaningful niche if execution goes well.",
"timeline": "- **2023-03-15** | Kindle incorporated in Delaware by founder [Vera Singh](people/vera-singh-20)\n- **2023-06-22** | First prototype membrane unit achieves 40% efficiency improvement over baseline\n- **2023-11-08** | [Tina Moore](people/tina-moore-191) joins as lead advisor following Climate Forward conference\n- **2024-01-30** | Seed funding round closed with climate-focused VC syndicate\n- **2024-04-12** | Strategic partnership announced with Midwest cement manufacturer\n- **2024-07-19** | Team expands to 15 employees, opens Oakland R&D facility\n- **2024-10-03** | Vera Singh presents at TechCrunch Disrupt climate track\n- **2025-02-14** | Pilot deployment begins at first manufacturing partner site\n- **2025-05-20** | Second pilot location confirmed in Ohio",
"_facts": {
"type": "company",
"slug": "companies/kindle-20",
"name": "Kindle",
"category": "startup",
"industry": "climate tech",
"founded_year": 2023,
"founders": [
"people/vera-singh-20"
],
"employees": [
"people/julia-jones-130"
],
"advisors": [
"people/tina-moore-191"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/kleiner-perkins-14",
"type": "company",
"title": "Kleiner Perkins",
"compiled_truth": "Kleiner Perkins is one of the most storied venture capital firms in Silicon Valley, with a legacy stretching back to 1972. Founded by Eugene Kleiner and Tom Perkins, the firm helped shape the modern tech landscape through early bets on companies like Amazon, Google, and Genentech. Today, KP continues to operate as a top-tier growth and early-stage investor, though its position has evolved considerably from its peak influence in the 1990s and 2000s.\n\nThe firm operates primarily out of Menlo Park, California, maintaining a relatively focused team compared to mega-funds like Andreessen Horowitz or Sequoia. Kleiner Perkins has historically been organized around sector-specific practices, including digital health, fintech, enterprise, and consumer technology. Recent years have seen the firm double down on AI and machine learning opportunities, recognizing the transformative potential of foundation models and applied AI startups.\n\nNotable current partners include Mamoon Hamid, who joined from Social Capital, and Bucky Moore, known for his work in enterprise software. The firm has maintained relationships with iconic founders and frequently co-invests alongside other major players in the ecosystem. Their portfolio includes breakout successes like Figma, Rippling, and several emerging AI-native companies that are reshaping enterprise workflows.\n\nKleiner's approach to venture has shifted somewhat over the past decade. After struggling with its green tech investments in the early 2010s, the firm refocused on software and healthcare, areas where it had demonstrated repeateable success. The cleantech experiment, while producing some winners, largely taught KP hard lessons about capital intensity and market timing. They've since been more disciplined about sector allocation.\n\nThe firm typically writes checks ranging from $1M to $50M depending on stage, though they've participated in larger rounds for high-conviction bets. KP maintains a builder-friendly reputation, often providing operational support through its platform team and network of advisors. They host regular founder dinners and have been known to facilitate introductions across their portfolio companies.\n\nAs of 2024, Kleiner Perkins manages several billion dollars across multiple funds, continuing to attract institutional LPs despite increased competition in the venture landscape. The firm remains a sought-after partner for founders seeking both capital and credibility, though they face stiff competiton from newer entrants with aggressive deployment strategies.",
"timeline": "- **2021-03-15** | Kleiner Perkins closed Fund XX at $1.8B, marking a return to larger fund sizes after years of more modest raises.\n- **2021-09-22** | Led Series B for an AI-native workflow automation startup, signaling renewed focus on enterprise machine learning applications.\n- **2022-04-08** | Partner Bucky Moore spoke at a founders summit on the future of vertical SaaS and embedded fintech.\n- **2022-11-30** | KP participated in Figma's final private round before the Adobe acquisition announcement.\n- **2023-06-14** | Announced new partner hire from Stripe, expanding fintech and payments expertise within the firm.\n- **2023-10-02** | Hosted annual CEO Summit in Napa Valley, bringing together portfolio founders for networking and strategy sessions.\n- **2024-02-19** | Led $40M Series A for a foundation model fine-tuning platform focused on healthcare applications.\n- **2024-08-07** | Kleiner Perkins published research report on AI agent adoption trends across enterprise customers.\n- **2025-01-23** | Participated in growth round for Rippling, continuing long-standing relationship with Parker Conrad.\n- **2025-05-11** | Mamoon Hamid joined board of a stealth climate software startup, marking selective return to climate-adjacent investments.",
"_facts": {
"type": "company",
"slug": "companies/kleiner-perkins-14",
"name": "Kleiner Perkins",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/lattice-39",
"type": "company",
"title": "Lattice - Enterprise SaaS Startup",
"compiled_truth": "Lattice is an enterprise SaaS startup founded in 2022 by [Quinn Miller](people/quinn-miller-39), a repeat founder with a background in developer tools and infrastructure software. The company focuses on building next-generation workflow automation platfroms for mid-market and enterprise customers, specifically targeting operations teams who struggle with fragmented tooling across their organizations.\n\nThe company emerged from Quinn's frustration with existing solutions that either served small teams or required massive implementation budgets. Lattice positions itself in the middle ground—powerful enough for complex enterprise needs, but accessible enough that a single ops manager can get started without a consulting engagement. Their core product offers visual workflow builders, deep integrations with popular SaaS tools, and an AI-assisted configuration layer that helps users identify automation opportunities.\n\nEarly backing came from [Vera Gonzalez](people/vera-gonzalez-103), who led a seed round in late 2022. Vera had previously invested in several successful enterprise software companies and saw Lattice as addressing a genuine gap in the market. The company has since grown to approximately 25 employees, with engineering and product teams based primarily in San Francisco.\n\nOn the advisory side, Lattice brought on [Steve Martinez](people/steve-martinez-192) to help navigate enterprise sales cycles and GTM strategy. Steve's experience scaling sales organizations has proven valuable as Lattice transitions from founder-led sales to building out a dedicated revenue team. His connections in the Fortune 500 have also opened doors for pilot conversations that would otherwise take months to secure.\n\nLattice has been relatively quiet publicly, preferring to focus on product development and early customer success over PR. However, industry insiders note that the company has secured several notable design partners in the fintech and healthcare sectors. Their approach emphasizes landing with a single team and expanding organically—a strategy that keeps churn low but requires patience on revenue growth. The company is currently preparing for a Series A raise expected sometime in mid-2025.",
"timeline": "- **2022-03-15** | [Quinn Miller](people/quinn-miller-39) incorporates Lattice and begins initial product development\n- **2022-09-22** | Closes $3.2M seed round led by [Vera Gonzalez](people/vera-gonzalez-103)\n- **2022-12-01** | First design partner signed—a mid-sized fintech processing loan applications\n- **2023-04-18** | [Steve Martinez](people/steve-martinez-192) joins as formal advisor to help build sales playbook\n- **2023-08-30** | Launches private beta with 12 companies participating\n- **2024-01-15** | Reaches $500K ARR milestone, transitions to general availability\n- **2024-06-12** | Expands integration library to cover 80+ enterprise tools\n- **2024-11-03** | Hires first dedicated VP of Sales, growing team to 25 employees\n- **2025-02-20** | Begins Series A fundraising conversations with top-tier VCs",
"_facts": {
"type": "company",
"slug": "companies/lattice-39",
"name": "Lattice",
"category": "startup",
"industry": "enterprise SaaS",
"founded_year": 2022,
"founders": [
"people/quinn-miller-39"
],
"investors": [
"people/vera-gonzalez-103"
],
"employees": [
"people/owen-patel-149"
],
"advisors": [
"people/steve-martinez-192"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/lightspeed-6",
"type": "company",
"title": "Lightspeed Venture Partners",
"compiled_truth": "Lightspeed Venture Partners is a global venture capital firm with a storied history dating back to 2000. The firm has established itself as one of the most influential players in early and growth-stage investing, with a particular strength in enterprise software, consumer internet, and fintech. Headquartered in Menlo Park, California, Lightspeed operates across multiple geographies including offices in India, China, Israel, and Europe.\n\nThe firm manages over $25 billion in committed capital across various funds and has backed some of the most consequential technology companies of the past two decades. Notable investments include Snap, Affirm, Mulesoft, and Rubrik. Lightspeed tends to take a hands-on approach with portfolio companies, often providing operational support and leveraging their extensive network to help founders scale.\n\nIn recent years, Lightspeed has been particularly agressive in the AI and machine learning space, deploying significant capital into foundational model companies and AI-native applications. The firm closed a $7.1 billion fund in 2022, one of the largest in its history, signaling continued confidence from LPs despite broader market uncertainty. Partners like Ravi Mhatre and Arif Janmohamed have been instrumental in shaping the firm's enterprise investing thesis.\n\nLightspeed has developed relationships with other major firms in the ecosystem, occasionally co-investing alongside [Andreessen Horowitz](companies/a16z) on competitive deals. The firm is known for moving quickly on conviction and has a reputation for being founder-friendly, though they maintain rigourous diligence processes. Their global footprint allows them to spot trends early—the India team, for instance, was early to companies like Oyo and Byju's before those markets became crowded.\n\nThe firm also runs Lightspeed Faction, a growth-stage vehicle that targets later rounds. This multi-stage capability has become increasingly important as companies stay private longer. They've competed for deals with firms like [Sequoia Capital](companies/sequoia) across multiple stages, sometimes winning on speed and sometimes on terms. Lightspeed remains a top-tier firm that consistently ranks among the most active investors globally.",
"timeline": "- **2021-03-15** | Lightspeed leads $150M Series C for enterprise AI startup, marking increased focus on machine learning infrastructure\n- **2021-09-22** | Announced expansion of Israel office with three new partner hires\n- **2022-04-10** | Closed $7.1 billion across early and growth funds, largest raise in firm history\n- **2022-11-08** | Co-invested alongside [Andreessen Horowitz](companies/a16z) in developer tools company seed round\n- **2023-02-14** | Published annual report showing 47 new investments across global portfolio in 2022\n- **2023-07-19** | Partner Mercedes Bent promoted to lead consumer investing practice\n- **2024-01-30** | Lightspeed Faction leads $200M growth round for cybersecurity unicorn\n- **2024-06-12** | Competed with [Sequoia Capital](companies/sequoia) for Series B deal in logistics automation space\n- **2025-02-28** | Opened new office in London to expand European coverage\n- **2025-09-05** | Announced $500M opportunity fund focused exclusively on AI applications",
"_facts": {
"type": "company",
"slug": "companies/lightspeed-6",
"name": "Lightspeed",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,28 +0,0 @@
{
"slug": "companies/lucid-21",
"type": "company",
"title": "Lucid",
"compiled_truth": "Lucid is a climate tech startup founded in 2020 by [Eric Lee](people/eric-lee-21), focused on developing next-generation carbon capture monitoring systems. The company emerged from Eric's frustration with the lack of real-time verification tools in the voluntary carbon markets—a gap he identified while working on sustainability initiatives at his previous role.\n\nThe core product is a hardware-software platform that provides continous monitoring of carbon sequestration projects, particularly direct air capture facilities and reforestation efforts. Lucid's sensors collect granular data on CO2 flux, which feeds into their analytics dashboard used by project developers, carbon credit buyers, and third-party verifiers. The pitch is simple: if you're buying carbon credits, you should know they're actually removing carbon.\n\nIn 2022, Lucid raised a seed round led by [Fiona Moore](people/fiona-moore-88), with participation from [Ian Anderson](people/ian-anderson-105). The round valued the company at roughly $18M and gave them runway to expand their pilot programs across North America. Fiona joined the board and has been instrumental in connecting Lucid to her network of institutional investors interested in climate infrastructure.\n\nThe company operates lean—around 25 employees as of late 2024, split between hardware engineering in Oakland and a software team that's mostly remote. [Vera Rodriguez](people/vera-rodriguez-171) serves as an advisor, bringing her expertise in carbon markets and regulatory frameworks. Her guidance has been particularly valuable as Lucid navigates the evolving landscape of carbon credit certification standards.\n\nLucid has faced some headwinds. The voluntary carbon market contracted in 2023 amid scrutiny over credit quality, which ironically validated Lucid's core thesis but also slowed sales cycles. Several potential enterprise deals got pushed as companies reassesed their offset strategies. Still, the team sees this as a temporary correction that ultimately benefits players focused on verification and transparency.\n\nRecent moves include a partnership with a major reforestation nonprofit to pilot their monitoring tech across 50,000 hectares in the Pacific Northwest. Eric has been increasingly visible at climate conferences, positioning Lucid as the \"trust layer\" for carbon markets.",
"timeline": "- **2020-06-15** | Lucid incorporated by [Eric Lee](people/eric-lee-21) in Delaware, initial focus on carbon monitoring R&D\n- **2021-03-22** | First prototype sensor deployed at a test site in Nevada desert\n- **2021-11-08** | Accepted into climate tech accelerator program, relocated operations to Oakland\n- **2022-04-30** | Closed $4.2M seed round led by [Fiona Moore](people/fiona-moore-88)\n- **2022-09-14** | Hired VP of Engineering from Planet Labs to scale hardware team\n- **2023-02-17** | [Vera Rodriguez](people/vera-rodriguez-171) formally joins as strategic advisor\n- **2023-08-05** | Eric presents at Climate Week NYC on verification standards\n- **2024-01-20** | Announced partnership with ForestWatch nonprofit for Pacific Northwest pilot\n- **2024-07-11** | Reached 15 active deployment sites across US and Canada\n- **2025-03-03** | Began Series A conversations, targeting $15-20M raise",
"_facts": {
"type": "company",
"slug": "companies/lucid-21",
"name": "Lucid",
"category": "startup",
"industry": "climate tech",
"founded_year": 2020,
"founders": [
"people/eric-lee-21"
],
"investors": [
"people/fiona-moore-88",
"people/ian-anderson-105"
],
"employees": [
"people/ian-nakamura-131"
],
"advisors": [
"people/vera-rodriguez-171"
]
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/lumen-12",
"type": "company",
"title": "Lumen - Biotech Startup",
"compiled_truth": "Lumen is a biotech startup founded in 2018 by [Henry Johnson](people/henry-johnson-12), focused on developing novel diagnostic tools for early-stage cancer detection. The company operates out of Cambridge, Massachusetts, positioning itself within one of the most concentrated biotech ecosystems in the world. Their core technology leverages proprietary biomarker identification methods combined with machine learning to detect malignancies from standard blood draws—sometimes called liquid biopsy approaches.\n\nThe founding story traces back to Johnson's graduate research at MIT, where he first identified a unique protein signature associated with pancreatic cancer. Rather than pursue a traditional academic path, he spun out the research into what would become Lumen. Early days were scrappy. The company ran lean for nearly two years before securing meaningful outside investment.\n\nLumen's investor base includes [Kate Lopez](people/kate-lopez-99), who led their seed round in late 2020, and [Sarah Wang](people/sarah-wang-104), who joined during the Series A. Both have been activley involved in shaping company strategy, with Lopez taking a board observer seat and Wang providing introductions to pharmaceutical partners. The relationship with these backers has been described as collaborative rather than hands-off—monthly check-ins, strategic planning sessions, the works.\n\nOn the product side, Lumen has made steady progress. Their flagship diagnostic, LumenScreen, completed initial clinical validation in 2023 and is currently pursuing FDA breakthrough device designation. The team has grown to around 45 employees, split between R&D and clinical operations. They've also inked a partnership with a major regional hospital network for pilot testing, though terms weren't disclosed publically.\n\nHenry Johnson remains CEO and is known for a somewhat reserved public presence—he rarely speaks at conferences and prefers to let data do the talking. Internally, employees describe the culture as intense but mission-driven. Turnover has been relatively low for a company at this stage.\n\nLumen faces stiff competition from larger players in the liquid biopsy space, including Grail and Guardant Health. But the company's narrow focus on specific cancer types may prove advantageous for regulatory approval and clinical adoption. The next 18 months will be critical as they push toward commercialization.",
"timeline": "- **2018-03-15** | Lumen incorporated in Delaware by [Henry Johnson](people/henry-johnson-12)\n- **2018-09-22** | First lab space secured in Cambridge, initial team of 3 hired\n- **2020-11-08** | Seed round closed with [Kate Lopez](people/kate-lopez-99) leading at $2.4M\n- **2021-06-30** | Biomarker panel v1 validated in preclinical studies\n- **2022-04-12** | Series A announced, $18M raised with participation from [Sarah Wang](people/sarah-wang-104)\n- **2023-01-19** | LumenScreen enters clinical validation trials across 4 sites\n- **2023-08-07** | Partnership announced with Northeast Regional Health System for pilot deployment\n- **2024-02-28** | FDA breakthrough device designation application submitted\n- **2024-11-15** | Team expands to 45 full-time employees\n- **2025-03-22** | Preliminary data from clinical trials presented at AACR annual meeting",
"_facts": {
"type": "company",
"slug": "companies/lumen-12",
"name": "Lumen",
"category": "startup",
"industry": "biotech",
"founded_year": 2018,
"founders": [
"people/henry-johnson-12"
],
"investors": [
"people/kate-lopez-99",
"people/sarah-wang-104"
],
"employees": [
"people/grace-miller-122"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/mantle-16",
"type": "company",
"title": "Mantle",
"compiled_truth": "Mantle is a consumer social startup founded in 2024 by [Ulrich Wang](people/ulrich-wang-16), an entrepreneur with a background in community-driven products. The company is building what they describe as a \"social layer for real-world experiences\" — essentially trying to bridge the gap between digital social graphs and physical gatherings. Early product demos have shown features around spontaneous meetups, location-based discovery, and ephemeral group chats tied to specific venues or events.\n\nThe founding team is lean, with Ulrich handling most of the product vision and early engineering. He's been advised by [Julia Wilson](people/julia-wilson-194), who brings experience from previous consumer social ventures and has been instrumental in shaping Mantle's go-to-market thinking. Julia's involvement suggests the company is serious about avoiding the common pitfalls of consumer social — namely, building features nobody asked for and failing to find organic growth loops.\n\nMantle's thesis is that existing social apps have become too performative, too oriented around content creation rather than genuine connection. The team believes there's an underserved segment of users who want lower-friction ways to coordinate IRL hangs without the pressure of posting or maintaining a public persona. It's a crowded space, but Wang argues that most competitors have gotten the incentive structures wrong — focusing on creator monetization when they should be focusing on social utility.\n\nThe company hasn't announced any funding publicly, though sources suggest they've raised a small pre-seed round from angels in the consumer space. Headcount remains under five as of late 2024. Mantle is currently testing with a closed beta group, primarly college students in the Bay Area and a few cities on the East Coast.\n\nWhether Mantle can break through remains to be seen. Consumer social is notoriously difficult — network effects cut both ways, and user attention is finite. But with Ulrich's obsessive focus on user experience and Julia Wilson's strategic guidance, the company has a shot at carving out a niche. Early retention numbers are reportedly encouraging, though the team is tight-lipped about specifics.",
"timeline": "- **2024-01-18** | Ulrich Wang incorporates Mantle as a Delaware C-corp, begins solo development on MVP.\n- **2024-03-02** | [Julia Wilson](people/julia-wilson-194) joins as an advisor after intro from a mutual investor.\n- **2024-04-15** | Mantle closes a small pre-seed round; terms undisclosed.\n- **2024-06-10** | First internal alpha launched to ~50 testers across three college campuses.\n- **2024-08-22** | Company hires first full-time engineer, a former classmate of [Ulrich Wang](people/ulrich-wang-16).\n- **2024-09-30** | Closed beta expands to 500 users; early retention data looks promising.\n- **2024-11-12** | Mantle presents at a small consumer social showcase in SF, generates some buzz.\n- **2025-01-08** | Team begins exploring partnerships with event venues for location-based features.\n- **2025-03-20** | Beta user count crosses 2,000; team considering seed raise timing.",
"_facts": {
"type": "company",
"slug": "companies/mantle-16",
"name": "Mantle",
"category": "startup",
"industry": "consumer social",
"founded_year": 2024,
"founders": [
"people/ulrich-wang-16"
],
"employees": [
"people/noah-lopez-126"
],
"advisors": [
"people/julia-wilson-194"
]
}
}
@@ -1,29 +0,0 @@
{
"slug": "companies/meridian-40",
"type": "company",
"title": "Meridian",
"compiled_truth": "Meridian is a developer tools startup founded in 2022 by [Chris Nakamura](people/chris-nakamura-40), a former infrastructure engineer who spent years frustrated by the fragmented state of debugging workflows. The company focuses on building unified observability tooling that sits between traditional logging platforms and APM solutions—a niche that's proven surprisingly sticky with mid-sized engineering teams.\n\nThe founding thesis came from Nakamura's experience at larger tech companies where he watched teams cobble together five or six different tools just to trace a single production incident. Meridian's core product aggregates logs, traces, and metrics into what they call a \"narrative view\"—essentially reconstructing the story of what happened in your system without requiring engineers to context-switch between dashboards. Its a deceptively simple idea that turns out to be technically complex to execute well.\n\nFunding came together relatively quickly. [Priya Taylor](people/priya-taylor-85) led the seed round after seeing an early demo, and she brought in [Chris Jackson](people/chris-jackson-91) who had been looking for developer tools plays. [Vera Gonzalez](people/vera-gonzalez-103) joined as a smaller check but has been actively involved in go-to-market strategy. The total seed was $3.2M, closed in late 2022.\n\nOn the advisory side, [Zoe Jackson](people/zoe-jackson-199) has been instrumental in helping Meridian think through enterprise sales motions. Her background in scaling developer-focused products gave the team a playbook they've been iterating on throughout 2023 and into 2024.\n\nMeridian currently has about 14 employees, mostly engineers, operating out of a small office in San Francisco's Dogpatch neighborhood. They've been deliberatley slow on hiring, preferring to keep the team tight while they nail down product-market fit. Revenue numbers aren't public but word is they crossed $500K ARR sometime in early 2024, with a handful of paying customers in the fintech and healthtech spaces.\n\nThe company's biggest challenge right now is differentiation. The observability market is crowded, and larger players like Datadog keep expanding their feature sets. Nakamura has been vocal about staying focused on the \"debugging narrative\" angle rather than trying to become a full platform. Whether that strategy holds as they scale remains to be seen.",
"timeline": "- **2022-03-14** | Chris Nakamura incorporates Meridian, begins building initial prototype\n- **2022-08-22** | First demo shown to [Priya Taylor](people/priya-taylor-85), receives positive feedback and term sheet discussions begin\n- **2022-11-03** | Seed round closes at $3.2M with [Chris Jackson](people/chris-jackson-91) and [Vera Gonzalez](people/vera-gonzalez-103) participating\n- **2023-02-17** | Meridian launches private beta, onboards first 12 design partners\n- **2023-06-09** | [Zoe Jackson](people/zoe-jackson-199) joins as formal advisor, begins weekly office hours with team\n- **2023-09-28** | Public launch at a small developer conference in SF, picks up first paying customers\n- **2024-01-15** | Crosses $500K ARR milestone, team celebrates with low-key dinner\n- **2024-05-20** | Hires first dedicated sales rep, begins outbound motion targeting Series B+ startups\n- **2024-11-08** | Ships major \"Narrative 2.0\" update with improved trace visualization\n- **2025-02-14** | Begins early conversations about Series A, [Priya Taylor](people/priya-taylor-85) making introductions to growth-stage funds",
"_facts": {
"type": "company",
"slug": "companies/meridian-40",
"name": "Meridian",
"category": "startup",
"industry": "developer tools",
"founded_year": 2022,
"founders": [
"people/chris-nakamura-40"
],
"investors": [
"people/priya-taylor-85",
"people/chris-jackson-91",
"people/vera-gonzalez-103"
],
"employees": [
"people/kate-kapoor-150"
],
"advisors": [
"people/zoe-jackson-199"
]
}
}
-15
View File
@@ -1,15 +0,0 @@
{
"slug": "companies/meta-2",
"type": "company",
"title": "Meta (Cybersecurity)",
"compiled_truth": "Meta is a cybersecurity firm founded in 1997, not to be confused with the social media giant of the same name. Operating in the enterprise security space for over two decades, the company has built a reputation as a quiet but effective acquirer of smaller security startups and niche technology providers.\n\nThe company specializes in network security infrastructure and threat detection systems, serving primarily Fortune 500 clients and government contractors. Their flagship product line focuses on perimeter defense and intrusion detection, though they've expanded considerably through strategic acquisitions over the years. Meta's approach has always been to identify promising early-stage cybersecurity companies and integrate their technology into the broader Meta ecosystem.\n\nIn recent years, Meta has been particularly active in the acqusition market, snapping up several AI-driven security startups looking to modernize their offerings. The company completed at least three acquisitions in 2024 alone, focusing on machine learning-based threat analysis and zero-trust architecture providers. Their M&A strategy tends to favor companies with strong technical teams rather than those with large customer bases—they're buying talent and IP, not revenue.\n\nLeadership at Meta Cybersecurity has remained relatively stable, with most of the executive team having been with the company for over a decade. This continuity has allowed them to maintain consistent strategic direction even as the cybersecurity landscape shifts dramatically. They've been rumored to be in discussions with [Anduril Industries](companies/anduril-industries) regarding potential partnership opportunities in the defense sector, though neither party has confirmed these reports.\n\nThe firm maintains a low public profile compared to flashier competitors, preferring to let their client relationships speak for themselves. Their government contracting work, in particular, requires discretion. Meta has also been mentioned in connection with [Palantir Technologies](companies/palantir-technologies) as a potential acquisition target, though industry analysts consider this unlikely given Meta's own acquisition-focused strategy and the cultural differences between the two organizations.\n\nHeadquartered in the Washington D.C. metro area, Meta employs approximately 800 people across their main office and satellite locations in Austin and Tel Aviv.",
"timeline": "- **2021-03-15** | Meta acquires small endpoint security startup based in Boston for undisclosed sum\n- **2021-09-22** | Company celebrates 24 years in operation with internal summit featuring keynote on future of zero-trust\n- **2022-04-08** | Meta Cybersecurity signs major contract with Department of Defense for network monitoring services\n- **2022-11-30** | Opens new R&D facility in Tel Aviv focused on threat intelligence\n- **2023-06-14** | Partnership discussions reportedly begin with [Anduril Industries](companies/anduril-industries) around defense applications\n- **2024-02-19** | Completes acquisition of AI security startup, third deal in eight months\n- **2024-08-05** | Meta leadership meets with [Palantir Technologies](companies/palantir-technologies) executives at RSA Conference, sparking merger speculation\n- **2025-01-12** | Launches next-generation threat detection platform incorporating acquired ML technology\n- **2025-07-28** | Announces expansion of Austin office, adding 150 new engineering positions\n- **2026-03-03** | Named to Gartner Magic Quadrant for Enterprise Network Security for fifth consecutive year",
"_facts": {
"type": "company",
"slug": "companies/meta-2",
"name": "Meta",
"category": "acquirer",
"industry": "cybersecurity",
"founded_year": 1997
}
}
@@ -1,15 +0,0 @@
{
"slug": "companies/microsoft-0",
"type": "company",
"title": "Microsoft",
"compiled_truth": "Microsoft is a dominant force in the cybersecurity landscape, having transformed itself from a traditional software giant into one of the most aggressive acquirers in the security space. Founded in 1995, the company has methodically built out its security portfolio through strategic acquisitions and internal development, positioning itself as a one-stop shop for enterprise security needs.\n\nThe company's cybersecurity division generates over $20 billion in annual revenue, making it one of the largest security vendors globally. Microsoft's approach has been to embed security deeply into its cloud infrastructure, particularly Azure and Microsoft 365, creating an integrated ecosystem thats difficult for competitors to match. Their Defender suite, Sentinel SIEM platform, and Entra identity solutions form the backbone of security for thousands of enterprises worldwide.\n\nMicrosoft's acquisition strategy has been notably aggressive. They've snapped up numerous startups and established players alike, often integrating the technology directly into their existing platforms. This has created tension with pure-play security vendors who find themselves competing against a company that bundles security features into products their customers already use. Some critics argue this bundling approach leads to \"good enough\" security rather than best-in-class protection, but the convenience factor has proven compelling for many IT departments.\n\nThe company has also invested heavily in threat intelligence, operating one of the largest security research teams in the industry. Their visibility into global attack patterns—derived from telemetry across Windows, Azure, and Office 365—gives them unique insights that feed back into their products. Recent moves have focused on AI-powered security tools, with Microsoft positioning Copilot for Security as a force multiplier for understaffed security teams.\n\nLeadership under Satya Nadella has prioritized security as a core pillar, especially following several high-profile breaches affecting Microsoft's own infrastructure. The company has faced scrutiny from government agencies and enterprise customers demanding better baseline security, prompting internal reorganizations and the Secure Future Initiative. Despite these challanges, Microsoft remains a category-defining player that shapes how the industry thinks about integrated security platforms.",
"timeline": "- **2021-03-15** | Microsoft announces acquisition of RiskIQ for threat intelligence capabilities, expanding its external attack surface management\n- **2021-07-22** | Completed purchase of CloudKnox Security to bolster identity and access management portfolio\n- **2022-04-18** | Launched Microsoft Entra brand, consolidating identity products under unified naming\n- **2022-11-09** | Security revenue surpasses $20 billion annually, making MSFT one of the largest security vendors globally\n- **2023-03-28** | Unveiled Security Copilot at Ignite, bringing generative AI to security operations workflows\n- **2023-08-14** | Faced congressional scrutiny following Chinese threat actor breach of government email accounts via compromised signing keys\n- **2024-01-22** | Announced Secure Future Initiative following internal security review, pledging fundamental changes to development practices\n- **2024-06-11** | Expanded partnership with major defense contractors for classified cloud security workloads\n- **2025-02-19** | Acquired endpoint detection startup to enhance Defender capabilities in OT/IoT environments\n- **2025-09-03** | Microsoft Security leadership presented at RSA Conference on next-generation SIEM architecture",
"_facts": {
"type": "company",
"slug": "companies/microsoft-0",
"name": "Microsoft",
"category": "acquirer",
"industry": "cybersecurity",
"founded_year": 1995
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/mosaic-14",
"type": "company",
"title": "Mosaic - Consumer Social Startup",
"compiled_truth": "Mosaic is a consumer social startup founded in 2018 by [Vera Chen](people/vera-chen-14), who serves as the company's CEO. The company operates in the consumer social space, building products that aim to reimagine how people connect and share experiences online. Based on the premise that traditional social media has become too performative and shallow, Mosaic set out to create more authentic digital spaces for meaningful interaction.\n\nThe platform's core product allows users to create collaborative visual stories—essentially shared digital scrapbooks that multiple people can contribute to in real-time. Think of it as a blend between Pinterest boards and group chats, but with richer media capabilities. The name \"Mosaic\" reflects this vision: individual pieces coming together to form something beautiful and cohesive.\n\nVera Chen built the initial prototype while working nights and weekends, drawing on her background in interaction design and her frustration with existing social platforms. Early traction came from college students coordinating group trips and long-distance friend groups trying to stay connected. The organic growth caught the attention of several investors in the Bay Area.\n\n[Helen Martinez](people/helen-martinez-87) led an early investment round, providing crucial capital that allowed Mosaic to expand its engineering team and improve infastructure. Martinez saw potential in Chen's vision and the company's strong retention metrics among its early user base. The investment also brought valuable mentorship to the young founder.\n\nThe company has faced significant competition from established players who've tried to replicate similar features. Instagram's \"Collabs\" and Snapchat's shared stories both emerged after Mosaic gained traction. However, the startup has maintained its niche by focusing on depth over breadth—their users create fewer posts but spend more time on each one.\n\nMosiac currently employs around 35 people, mostly engineers and designers. The team operates with a hybrid work model, with offices in San Francisco. Revenue comes primarily from a freemium subscription model, though the company has experimented with brand partnerships for special templates and features.",
"timeline": "- **2018-03-15** | Vera Chen incorporates Mosaic and begins building the first prototype\n- **2018-11-02** | Beta launch to 500 users, mostly from Chen's network and local universities\n- **2019-06-20** | [Helen Martinez](people/helen-martinez-87) leads seed round of $2.1M\n- **2020-01-08** | Mosaic hits 100,000 registered users during pandemic surge in social app usage\n- **2021-04-12** | Series A closes at $12M, company expands engineering team to 20\n- **2022-09-30** | Launch of Mosaic Pro subscription tier with premium collaborative features\n- **2023-03-18** | [Vera Chen](people/vera-chen-14) speaks at SXSW on \"Building for Authentic Connection\"\n- **2024-07-22** | Partnership announced with major photo printing service for physical mosaic books\n- **2025-02-14** | Company reaches 2 million monthly active users milestone\n- **2025-11-03** | Mosaic acquires small AR startup to integrate spatial features into platform",
"_facts": {
"type": "company",
"slug": "companies/mosaic-14",
"name": "Mosaic",
"category": "startup",
"industry": "consumer social",
"founded_year": 2018,
"founders": [
"people/vera-chen-14"
],
"investors": [
"people/helen-martinez-87"
],
"employees": [
"people/chris-rodriguez-124"
]
}
}
-14
View File
@@ -1,14 +0,0 @@
{
"slug": "companies/nea-13",
"type": "company",
"title": "NEA (New Enterprise Associates)",
"compiled_truth": "New Enterprise Associates, commonly known as NEA, stands as one of the largest and most established venture capital firms in the world. Founded in 1977, the firm has grown from its roots in early-stage technology investing to become a multi-stage powerhouse with assets under management exceeding $25 billion. NEA operates across the full spectrum of venture investing, from seed rounds to growth equity, with a particular focus on technology and healthcare sectors.\n\nThe firm maintains offices in Menlo Park, San Francisco, New York, Boston, and internationally, giving it substantial reach across major startup ecosystems. NEA's investment philosophy emphasizes long-term partnerships with founders, and they've backed some of the most consequential companies of the past several decades including Salesforce, Workday, and Uber. Their healthcare practice is particularly notable, having invested in numerous successful biotech and medical device companies.\n\nIn recent years NEA has continued to raise substantial funds, with their latest flagship fund exceeding $3.6 billion. The firm operates with a relatively large partnership compared to some peers, allowing them to cover more ground but sometimes leading to questions about decision-making speed. Partners like Scott Sandell and Peter Barris have shaped the firms direction over multiple decades, though newer partners are increasingly taking lead roles on deals.\n\nNEA has shown interest in emerging areas like AI infrastructure and climate tech, competing with firms like [Andreessen Horowitz](companies/a16z-9) for the hottest deals. Their approach tends to be more traditional than some newer entrants to venture — they're known for thorough due dilligence and sometimes slower processes, which can be both a feature and a bug depending on founder preferences. The firm frequently co-invests alongside other major players including [Sequoia Capital](companies/sequoia-capital-6), particularly on larger growth rounds where syndicate diversity matters to founders.\n\nNEA's brand carries significant weight in boardrooms and with LPs, though they face ongoing pressure to demonstrate continued relevance as the venture landscape evolves rapidly around them.",
"timeline": "- **2021-03-15** | NEA closes Fund XIV at $3.6 billion, one of the largest funds in firm history\n- **2021-09-22** | Lead investment in Series B for AI-native cybersecurity startup alongside [Sequoia Capital](companies/sequoia-capital-6)\n- **2022-04-08** | Partner Hannah Kreiswirth promoted to lead healthcare investing practice\n- **2022-11-30** | NEA portfolio company exits via SPAC merger, generating 8x return\n- **2023-06-14** | Announced strategic focus on climate tech, committing $500M to sector\n- **2023-10-02** | Co-led $180M growth round in enterprise AI company with [Andreessen Horowitz](companies/a16z-9)\n- **2024-02-19** | Opened new office in London to expand European presence\n- **2024-08-07** | Scott Sandell announces transition to Chairman role, new managing partners named\n- **2025-01-23** | Led seed round for stealth quantum computing startup at $40M valuation\n- **2025-05-11** | NEA portfolio company IPO on NYSE, largest venture-backed healthcare listing of the year",
"_facts": {
"type": "company",
"slug": "companies/nea-13",
"name": "NEA",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,21 +0,0 @@
{
"slug": "companies/nexus-41",
"type": "company",
"title": "Nexus",
"compiled_truth": "Nexus is a biotech startup founded in 2023 by [Alice Kim](people/alice-kim-41), a computational biologist who previously spent nearly a decade at Genentech before striking out on her own. The company operates in the synthetic biology space, specifically focused on developing novel protein engineering platforms that leverage machine learning to accelerate drug discovery timelines.\n\nThe founding thesis behind Nexus centers on a simple but powerful idea: traditional protein design is too slow and too expensive. [Alice Kim](people/alice-kim-41) built the initial prototype while still moonlighting at her previous role, using transformer-based models to predict protein folding outcomes with what she claims is 40% better accuracy than existing tools. Bold claim. The early data seems to back it up, though peer review is still pending on their foundational paper.\n\nNexus raised a $4.2M seed round in late 2023, led by a syndicate of biotech-focused angels and one undisclosed strategic investor rumored to be connected to a major pharma company. The funds went primarily toward buildling out their wet lab capabilities in South San Francisco and hiring a small but senior team of six full-time employees. Alice has been deliberate about keeping the team lean—she's said publicly that she'd rather have five exceptional people than fifteen mediocre ones.\n\nThe company's go-to-market strategy involves partnering with mid-size pharmaceutical companies who lack the in-house ML expertise to build these platforms themselves. Nexus positions itself as a \"co-pilot\" rather than a replacement, which has helped ease concerns about IP ownership and control. Two pilot partnerships were announced in early 2024, though neither partner has been named publicly.\n\nCulturally, Nexus operates with an almost academic intensity. Weekly journal clubs, mandatory documentation of experiments, open internal debates about methodology. Alice brought this ethos from her research days and has made it core to how the company functions. Some employees thrive in this environment; others have found it exhausting. Turnover has been minimal so far, but the company is still young.",
"timeline": "- **2023-03-15** | [Alice Kim](people/alice-kim-41) incorporates Nexus as a Delaware C-corp while still employed at Genentech\n- **2023-06-22** | Alice leaves Genentech to work on Nexus full-time; secures initial $500K pre-seed from angel investors\n- **2023-09-08** | Nexus closes $4.2M seed round; announces plans to open South San Francisco wet lab\n- **2023-11-30** | First full-time hire: Dr. Marcus Chen joins as Head of Protein Engineering\n- **2024-01-17** | Wet lab facility becomes operational; first internal experiments begin\n- **2024-04-03** | Nexus announces two unnamed pharmaceutical partnership pilots\n- **2024-07-12** | [Alice Kim](people/alice-kim-41) presents preliminary platform results at SynBioBeta conference\n- **2024-10-25** | Team expands to six FTEs; company moves to larger office space\n- **2025-02-14** | Submits foundational paper on ML-driven protein folding to Nature Methods\n- **2025-06-01** | Series A discussions reportedly underway with multiple tier-1 biotech VCs",
"_facts": {
"type": "company",
"slug": "companies/nexus-41",
"name": "Nexus",
"category": "startup",
"industry": "biotech",
"founded_year": 2023,
"founders": [
"people/alice-kim-41"
],
"employees": [
"people/eric-park-151"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/nimbus-5",
"type": "company",
"title": "Nimbus",
"compiled_truth": "Nimbus is a climate tech startup founded in early 2025 by [Mia Anderson](people/mia-anderson-5), a serial entrepreneur with a background in atmospheric science and distributed systems. The company is building what they describe as a \"climate intelligence layer\" — essentially a real-time data platform that aggregates satellite imagery, sensor networks, and predictive models to help enterprises and governments make better decisions around carbon accounting, extreme weather preparedness, and supply chain resiliance.\n\nThe founding story is pretty straightforward. Mia had been working on climate modeling tools at a larger company, got frustrated with how slow things moved, and decided to spin out her own thing. She bootstrapped for about three months before bringing on [Noah Nakamura](people/noah-nakamura-182) as an advisor. Noah's been instrumental in shaping their go-to-market strategy, particularly around enterprise sales cycles and pricing architecture.\n\nNimbus operates with a small but focused team — currently around 8 people, mostly engineers with a couple of climate scientists. They've been pretty heads-down on product development, though theyve started doing some early pilots with logistics companies in the Pacific Northwest. The initial use case seems to be helping shipping and freight operations anticipate weather disruptions and reroute proactively.\n\nWhat makes Nimbus interesting is their approach to data fusion. Rather than building their own sensor network from scratch, they're aggregating existing data sources — NOAA feeds, commercial satellite providers, IoT sensors already deployed by clients — and layering their own ML models on top. This keeps their infrastructure costs relatively low while still delivering actionable insights.\n\nThe company hasn't announced any formal funding rounds yet, though rumors suggest they're in conversations with a few climate-focused VCs. Mia Anderson has been intentionally keeping things quiet, preferring to let the product speak for itself before raising. Their advisory relationship with Noah Nakamura gives them some credibility in enterprise circles, which should help when they do decide to go out for capital.",
"timeline": "- **2024-09-15** | [Mia Anderson](people/mia-anderson-5) leaves previous role to begin exploring climate intelligence concepts\n- **2025-01-08** | Nimbus officially incorporated in Delaware\n- **2025-02-14** | [Noah Nakamura](people/noah-nakamura-182) joins as advisor, begins weekly strategy sessions\n- **2025-03-22** | First engineering hire made — backend systems specialist from Google\n- **2025-04-10** | Internal alpha of climate data platform completed\n- **2025-05-18** | Pilot program launched with two Pacific Northwest logistics companies\n- **2025-07-02** | Team expands to 8 full-time employees\n- **2025-08-29** | Nimbus presents at Climate Tech Connect conference in Portland\n- **2025-10-15** | Early discussions begin with climate-focused VC firms",
"_facts": {
"type": "company",
"slug": "companies/nimbus-5",
"name": "Nimbus",
"category": "startup",
"industry": "climate tech",
"founded_year": 2025,
"founders": [
"people/mia-anderson-5"
],
"employees": [
"people/quinten-nakamura-115"
],
"advisors": [
"people/noah-nakamura-182"
]
}
}
@@ -1,21 +0,0 @@
{
"slug": "companies/nimbus-labs-55",
"type": "company",
"title": "Nimbus Labs",
"compiled_truth": "Nimbus Labs is a developer tools startup founded in 2019 by [Vera Kapoor](people/vera-kapoor-55), who previously spent nearly a decade building infrastructure at larger tech companies before striking out on her own. The company focuses on cloud-native debugging and observability tooling, with their flagship product being a distributed tracing platform that's gained significant traction among mid-sized engineering teams.\n\nThe core thesis behind Nimbus is that debugging microservices shouldn't require a PhD in distributed systems. Their approach combines automatic instrumentation with AI-assisted root cause analysis, letting developers pinpoint issues across complex service meshes without manually correlating logs across dozens of services. It's an opinionated take on observability that's rubbed some infrastructure purists the wrong way, but the product's ease of adoption has won over plenty of converts.\n\nVera has been the public face of the company since day one, frequently speaking at conferences about the future of developer experience. She's known for her direct communication style and has built a small but loyal following on technical blogs. Under her leadership, Nimbus Labs has grown from a three-person team working out of a WeWork to roughly 45 employees spread across San Francisco and a small office in Bangalore.\n\nThe company raised a Series A in late 2021 and has been relatively quiet about fundraising since, though rumors of a Series B have circulated. Nimbus competes in a crowded space against established players like Datadog and newer entrants, but they've carved out a niche by focusing specifically on the debugging workflow rather than trying to be an all-in-one platform. Recent product updates have emphasized integration with popular CI/CD pipelines and expanded support for serverless architectures.\n\n[Vera Kapoor](people/vera-kapoor-55) remains CEO and maintains a hands-on role in product decisions, which some investors see as both a strength and potential bottleneck as the company scales. The next year will likely determine whether Nimbus can break out of its current niche or gets aquired by a larger platform player.",
"timeline": "- **2019-03-14** | Nimbus Labs incorporated in Delaware; [Vera Kapoor](people/vera-kapoor-55) listed as sole founder and CEO\n- **2019-11-02** | First public beta launched at a small developer meetup in SF; initial feedback was mixed but enthusiastic from early adopters\n- **2021-06-18** | Closed $8.5M Series A led by Baseline Ventures; announced plans to triple engineering headcount\n- **2022-02-10** | Shipped v2.0 of core tracing platform with AI-assisted analysis features\n- **2022-09-23** | Vera Kapoor delivered keynote at DevOpsCon on \"The Death of Manual Debugging\"\n- **2023-04-05** | Opened Bangalore engineering office; hired first international team members\n- **2023-11-30** | Reached 1,000 paying customers milestone; mostly SMB and mid-market\n- **2024-07-12** | Launched serverless support after months of customer requests\n- **2025-01-20** | Rumored acquisition talks with larger observability vendor fell through\n- **2025-08-03** | Announced partnership with major cloud provider for native integration",
"_facts": {
"type": "company",
"slug": "companies/nimbus-labs-55",
"name": "Nimbus Labs",
"category": "startup",
"industry": "developer tools",
"founded_year": 2019,
"founders": [
"people/vera-kapoor-55"
],
"employees": [
"people/iris-jones-165"
]
}
}
@@ -1,25 +0,0 @@
{
"slug": "companies/orbit-42",
"type": "company",
"title": "Orbit - Biotech Startup",
"compiled_truth": "Orbit is a biotech startup founded in 2021 by [Jack Patel](people/jack-patel-42), focused on developing novel protein engineering platforms for therapeutic applications. The company emerged from Patel's earlier research work and has positioned itself at the intersection of computational biology and wet lab innovation. Based out of the Boston-Cambridge biotech corridor, Orbit has built a lean but ambitious team.\n\nThe company's core technology revolves around machine learning-driven protein design, enabling faster iteration cycles for drug candidates targeting rare genetic disorders. Their proprietary platform, internally called \"Orbital,\" can predict protein folding outcomes with unusual accuracy, cutting development timelines significantly. Early partnerships with academic institutions have validated their approach, though comercial traction remains nascent.\n\nFunding has come from angel investors including [Julia Davis](people/julia-davis-86) and [Zoe Gonzalez](people/zoe-gonzalez-100), both of whom participated in Orbit's seed round. Davis in particular has been an active advisor, leveraging her network in the life sciences space to open doors for the young company. Gonzalez contributed not just capital but also operational guidance, having scaled biotech ventures before.\n\nJack Patel serves as CEO and remains deeply involved in the scientific direction. He's known for being hands-on in the lab despite growing management responsibilites. The team has grown to roughly 15 people as of late 2024, with key hires in protein chemistry and ML engineering.\n\nOrbit has kept a relatively low profile compared to flashier biotech startups, preferring to let results speak. They've published two peer-reviewed papers and presented at major conferences including the Biotech Showcase in San Francisco. The company is currently running preclinical studies for their lead program, OBT-101, targeting a rare metabolic condition. Industry watchers see Orbit as a company to watch—small but technically rigorous, with a founder who understands both the science and the business.",
"timeline": "- **2021-03-15** | Orbit incorporated in Delaware by [Jack Patel](people/jack-patel-42)\n- **2021-08-22** | Closed $1.2M seed round led by [Julia Davis](people/julia-davis-86)\n- **2022-02-10** | First version of Orbital platform completed internally\n- **2022-09-18** | Published initial findings in Nature Biotechnology\n- **2023-01-24** | [Zoe Gonzalez](people/zoe-gonzalez-100) joins as advisor and investor\n- **2023-06-30** | Hired Dr. Maria Chen as Head of Protein Chemistry\n- **2024-01-12** | Presented OBT-101 preclinical data at JP Morgan Healthcare Conference\n- **2024-07-08** | Expanded lab space in Cambridge, MA\n- **2025-03-20** | Initiated IND-enabling studies for lead program\n- **2025-11-05** | Announced collaboration with major pharma partner (undisclosed)",
"_facts": {
"type": "company",
"slug": "companies/orbit-42",
"name": "Orbit",
"category": "startup",
"industry": "biotech",
"founded_year": 2021,
"founders": [
"people/jack-patel-42"
],
"investors": [
"people/julia-davis-86",
"people/zoe-gonzalez-100"
],
"employees": [
"people/rachel-jones-152"
]
}
}
@@ -1,31 +0,0 @@
{
"slug": "companies/prism-43",
"type": "company",
"title": "Prism",
"compiled_truth": "Prism is a cybersecurity startup founded in 2023 by [David Patel](people/david-patel-43), who previously spent nearly a decade building threat detection systems at larger security firms. The company focuses on what it calls 'adaptive perimeter defense'—essentially AI-driven intrusion detection that learns an organization's normal traffic patterns and flags anomolies in real-time. Its early traction has been notable, particularly among mid-market financial services companies who find enterprise solutions too expensive but need more than basic firewall protections.\n\nThe founding story is pretty straightforward. David had grown frustrated with the slow pace of innovation at his previous employer and saw an opening in the market for lightweight, intelligent security tooling that didn't require a dedicated SOC team to operate. He bootstrapped the initial prototype over six months before raising a seed round.\n\nPrism's investor syndicate includes [Carol Jackson](people/carol-jackson-81), [Rosa Jackson](people/rosa-jackson-90), and [Tina Hernandez](people/tina-hernandez-97). Carol led the seed round and reportedly pushed hard for the company to focus on the SMB market rather than chasing enterprise deals too early. This strategic direction has shaped much of Prism's go-to-market approach. Rosa came in through an angel allocation and has been relatively hands-off, while Tina joined the cap table in a follow-on extension round in late 2024.\n\nOn the advisory side, [Alice Davis](people/alice-davis-172) provides guidance on product architecture—she's known for her work on distributed systems and has been instrumental in helping Prism scale its detection engine. [Olivia Miller](people/olivia-miller-176) advises on sales strategy and customer success, drawing on her background in enterprise software GTM.\n\nThe team has grown to around 18 people, mostly engineers, with a small but scrappy sales org. Prism operates out of Austin but has several remote employees scattered across the US. The company culture skews technical and moves fast—David himself still reviews most major PRs. Revenue is growing but the company isn't yet profitable, which is typical for this stage. They're expected to raise a Series A sometime in mid-2025.",
"timeline": "- **2023-02-14** | David Patel incorporates Prism and begins building initial prototype\n- **2023-07-22** | Seed round closes with [Carol Jackson](people/carol-jackson-81) leading, $2.1M raised\n- **2023-11-03** | First paying customer signs—a regional credit union in Texas\n- **2024-01-18** | [Alice Davis](people/alice-davis-172) joins as technical advisor\n- **2024-04-09** | Prism launches v1.0 of its adaptive perimeter defense platform\n- **2024-08-15** | Team hits 12 employees, opens small Austin office\n- **2024-10-30** | Extension round adds [Tina Hernandez](people/tina-hernandez-97) to investor group\n- **2025-01-22** | [Olivia Miller](people/olivia-miller-176) begins advising on GTM strategy\n- **2025-03-11** | ARR crosses $800K, Series A conversations begin",
"_facts": {
"type": "company",
"slug": "companies/prism-43",
"name": "Prism",
"category": "startup",
"industry": "cybersecurity",
"founded_year": 2023,
"founders": [
"people/david-patel-43"
],
"investors": [
"people/carol-jackson-81",
"people/rosa-jackson-90",
"people/tina-hernandez-97"
],
"employees": [
"people/mia-singh-153"
],
"advisors": [
"people/alice-davis-172",
"people/olivia-miller-176",
"people/zoe-jackson-199"
]
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/pulse-8",
"type": "company",
"title": "Pulse - EdTech Startup",
"compiled_truth": "Pulse is an edtech startup founded in 2022 by [Yara Johnson](people/yara-johnson-8), a former learning experience designer who spent nearly a decade observing how students actually engage with digital content. The company's core product is a real-time engagement analytics platform designed for K-12 classrooms and higher education institutions. Unlike traditional LMS analytics that track completion rates and grades, Pulse monitors micro-behaviors—pause patterns, scroll velocity, re-reads—to give educators a genuine sense of whether students are struggling before they fail a test.\n\nThe founding thesis came from Johnson's frustration with existing tools that treated engagement as a binary: either a student watched the video or they didn't. Pulse argues that the *how* matters more than the whether. Their proprietary algorithm flags what they call \"confusion signals\" and surfaces them to teachers in a simple dashboard. Early pilots in three school districts showed a 23% reduction in students falling behind, though critics have raised privacy concerns about the level of behavioral tracking involved.\n\nFunding has been modest but strategic. [Eric Martinez](people/eric-martinez-93) led the seed round in late 2022, bringing not just capital but connections to several charter school networks in Texas and California. Martinez has been vocal about his belief that edtech needs more \"unsexy infrastructure\" plays rather than consumer apps, and Pulse fits that thesis perfectly. The company currently employs around 15 people, mostly engineers and former educators.\n\n[David Kim](people/david-kim-186) serves as an advisor, helping Pulse navigate enterprise sales cycles and district procurement processes—notoriously slow and bureacratic. Kim's background in B2B SaaS has been instrumental in shaping Pulse's go-to-market strategy, which prioritizes landing a few large district contracts over chasing individual schools. As of early 2024, Pulse has contracts with 12 districts serving roughly 40,000 students combined. Revenue isn't disclosed but is rumored to be in the low seven figures. Yara Johnson remains CEO and has been clear she's building for the long haul, not a quick exit.",
"timeline": "- **2022-03-14** | Yara Johnson incorporates Pulse after leaving her role at a major textbook publisher\n- **2022-09-08** | Closes seed round led by [Eric Martinez](people/eric-martinez-93), raising $1.8M\n- **2022-11-20** | First pilot launches in Austin ISD with 3 middle schools\n- **2023-02-15** | [David Kim](people/david-kim-186) joins as official advisor\n- **2023-06-01** | Pulse ships v2.0 with redesigned teacher dashboard based on pilot feedback\n- **2023-10-12** | Signs first major district contract with Fresno Unified (18,000 students)\n- **2024-01-29** | Presents at SXSWedu panel on ethical student analytics\n- **2024-05-17** | Expands engineering team to 9 people, opens small Denver office\n- **2024-11-03** | Reaches 40,000 students across 12 districts\n- **2025-02-22** | Begins early conversations about Series A with several edtech-focused VCs",
"_facts": {
"type": "company",
"slug": "companies/pulse-8",
"name": "Pulse",
"category": "startup",
"industry": "edtech",
"founded_year": 2022,
"founders": [
"people/yara-johnson-8"
],
"investors": [
"people/eric-martinez-93"
],
"employees": [
"people/xavier-nakamura-118"
],
"advisors": [
"people/david-kim-186"
]
}
}
@@ -1,26 +0,0 @@
{
"slug": "companies/pulse-labs-58",
"type": "company",
"title": "Pulse Labs",
"compiled_truth": "Pulse Labs is a developer tools startup founded in 2019 by [Rachel Lopez](people/rachel-lopez-58), who previously spent nearly a decade building internal tooling at larger tech companies before striking out on her own. The company focuses on API observability and debugging tools, helping engineering teams identify performance bottlenecks and trace issues across distributed systems. Their flagship product, Pulse Trace, has gained traction among mid-sized SaaS companies looking for alternatives to more expensive enterprise solutions.\n\nThe company operates with a relatively lean team of around 35 employees, mostly engineers, spread across San Francisco and a satellite office in Austin. Rachel has been vocal about maintaining a sustainable growth trajectory rather than chasing hypergrowth, which has shaped the company's culture and hiring practices. This philosophy resonated with their investor group, which includes [Carol Jackson](people/carol-jackson-81), [Priya Taylor](people/priya-taylor-85), and [Rosa Jackson](people/rosa-jackson-90).\n\nPulse Labs raised a $4.2M seed round in early 2020, followed by a Series A of $18M in 2022 led by Priya Taylor's fund. The Series A came at a time when developer tooling was seeing significant investor intrest, and Pulse was well-positioned with strong retention metrics among its early customers. Rosa Jackson joined as an angel investor during the seed round and has remained an active advisor, particularly on go-to-market strategy.\n\nRecent moves include expanding their platform to support OpenTelemetry natively, a decision that required significant engineering investment but opened up compatability with a broader ecosystem. The company also launched a free tier in late 2024 aimed at individual developers and small teams, a strategic bet on bottom-up adoption. Rachel Lopez has mentioned in interviews that they're exploring AI-assisted debugging features, though nothing concrete has been announced yet.\n\nPulse Labs competes with established players like Datadog and newer entrants in the observability space, but differentiates through pricing transparency and a focus on developer experience over enterprise feature bloat.",
"timeline": "- **2019-03-15** | Pulse Labs incorporated by [Rachel Lopez](people/rachel-lopez-58) in Delaware\n- **2020-01-22** | Closed $4.2M seed round with participation from [Rosa Jackson](people/rosa-jackson-90)\n- **2020-09-08** | Launched Pulse Trace beta to first 50 customers\n- **2021-06-14** | Reached 200 paying customers milestone\n- **2022-04-03** | Announced $18M Series A led by [Priya Taylor](people/priya-taylor-85)\n- **2022-11-17** | Opened Austin office, hired VP of Engineering\n- **2023-05-22** | Rachel Lopez spoke at DevToolsCon on sustainable startup growth\n- **2024-02-09** | Shipped native OpenTelemetry support in Pulse Trace 3.0\n- **2024-10-30** | Launched free tier for individual developers\n- **2025-03-12** | [Carol Jackson](people/carol-jackson-81) joined board as observer seat",
"_facts": {
"type": "company",
"slug": "companies/pulse-labs-58",
"name": "Pulse Labs",
"category": "startup",
"industry": "developer tools",
"founded_year": 2019,
"founders": [
"people/rachel-lopez-58"
],
"investors": [
"people/carol-jackson-81",
"people/priya-taylor-85",
"people/rosa-jackson-90"
],
"employees": [
"people/alice-jones-168"
]
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/quantum-7",
"type": "company",
"title": "Quantum",
"compiled_truth": "Quantum is a fintech startup founded in 2022 by [Ulrich Johnson](people/ulrich-johnson-7), a serial entrepreneur with a background in quantitative finance and distributed systems. The company emerged from Johnson's frustration with the sluggish settlement times and opaque fee structures that plague traditional payment rails. Based out of Austin, Texas, Quantum has built a real-time payment reconciliation platform targeting mid-market e-commerce businesses and SaaS companies.\n\nThe core product offers instant transaction matching, automated dispute resolution, and predictive cash flow analytics. What sets Quantum apart from competitors is their proprietary matching algorithm, which reportedly achieves 99.7% accuracy on first-pass reconciliation—a significant improvement over industry standards. The platform integrates with major payment processors, banking APIs, and accounting software, positioning itself as the connective tissue in a fragmented fintech ecosystem.\n\nEarly backing came from [Kate Anderson](people/kate-anderson-107), who led a $2.1M seed round in late 2022. Anderson's involvement brought not just capital but credibility, given her track record of identifying breakout fintech plays. The company has since grown to around 25 employees, with plans to double headcount by end of 2025.\n\nOn the advisory side, [Noah Williams](people/noah-williams-198) has been instrumental in shaping Quantum's go-to-market strategy. Williams' connections in the enterprise software space have opened doors to several pilot programs with Fortune 500 companies—a surprising feat for such a young startup. His guidance on pricing and packaging helped the team move away from a pure usage-based model toward a hybrid subscription approach that's proven more predictable for customers and investors alike.\n\nQuantum's roadmap includes international expansion, starting with the UK and EU markets where PSD2 regulations have created fertile ground for innovative payment solutions. There's also talk of an AI-powered fraud detection layer, though details remain sparse. The company operates somewhat stealthily, preferring to let product traction speak rather than chasing press coverage.",
"timeline": "- **2022-03-14** | Ulrich Johnson incorporates Quantum in Delaware, begins recruiting founding engineering team\n- **2022-09-22** | Closes $2.1M seed round led by [Kate Anderson](people/kate-anderson-107)\n- **2022-11-08** | Launches private beta with 12 e-commerce customers\n- **2023-02-15** | [Noah Williams](people/noah-williams-198) joins as lead advisor, focuses on GTM stratgy\n- **2023-06-30** | Exits beta, announces general availability of reconciliation platform\n- **2023-10-12** | Surpasses 200 paying customers, hits $1M ARR milestone\n- **2024-04-18** | Opens Austin headquarters, team grows to 25 employees\n- **2024-08-07** | Begins enterprise pilot program with two Fortune 500 retailers\n- **2025-01-20** | Announces plans for UK expansion, begins regulatory groundwork\n- **2025-05-11** | [Ulrich Johnson](people/ulrich-johnson-7) speaks at FinTech Connect conference on real-time reconciliation",
"_facts": {
"type": "company",
"slug": "companies/quantum-7",
"name": "Quantum",
"category": "startup",
"industry": "fintech",
"founded_year": 2022,
"founders": [
"people/ulrich-johnson-7"
],
"investors": [
"people/kate-anderson-107"
],
"employees": [
"people/tina-lopez-117"
],
"advisors": [
"people/noah-williams-198"
]
}
}
@@ -1,28 +0,0 @@
{
"slug": "companies/quantum-labs-57",
"type": "company",
"title": "Quantum Labs",
"compiled_truth": "Quantum Labs is an early-stage biotech startup founded in 2024 by [Liam Wilson](people/liam-wilson-57), a computational biologist who previously led protein folding research at a major pharma company. The company operates out of a small lab space in Cambridge, MA, though much of the early work has been computational in nature.\n\nThe startup focuses on quantum computing applications for drug discovery, specifically targeting protein-ligand binding simulations that would take classical computers years to process. Their core thesis is that near-term quantum hardware, combined with clever error mitigation techniques, can already provide meaningful speedups for certain molecular dynamics calculations. Its a bold bet, and not everyone in the industry is convinced the hardware is ready.\n\nQuantum Labs raised a pre-seed round in late 2024, with [Rachel Brown](people/rachel-brown-95) leading the investment. Rachel has been particularly bullish on quantum-adjacent biotech plays and saw Liam's background as uniquely suited to bridge the gap between quantum computing hype and actual pharmaceutical applications. [Rosa Miller](people/rosa-miller-98) also participated in the round, bringing her experience scaling deep tech companies.\n\nOn the advisory side, the company brought on [Tara Johnson](people/tara-johnson-189) to help navigate regulatory pathways and partnership discussions with larger pharma players. Tara's connections have already opened doors to several exploratory conversations, though nothing has been announced publically yet.\n\nThe team remains small—just five people including Liam—but they've made progress on their initial benchmarking studies. Early results suggest their hybrid classical-quantum approach can reduce simulation time by roughly 40% for certain small molecule interactions. Whether this translates to real-world drug discovery value remains to be seen. Quantum Labs is currently focused on publishing these findings to establish credibility before pursuing a larger seed round, likely in mid-2025.",
"timeline": "- **2024-01-15** | Liam Wilson begins preliminary research and files initial IP for quantum-enhanced molecular simulation methods\n- **2024-03-22** | Quantum Labs officially incorporated in Delaware\n- **2024-05-10** | [Rachel Brown](people/rachel-brown-95) commits to leading pre-seed investment after initial pitch\n- **2024-06-18** | Lab space secured in Cambridge, MA; first equipment purchases made\n- **2024-07-30** | [Rosa Miller](people/rosa-miller-98) joins the round, bringing total pre-seed to $1.8M\n- **2024-09-12** | [Tara Johnson](people/tara-johnson-189) formally joins as advisor\n- **2024-11-05** | First proof-of-concept results show promising speedups on protein-ligand simulations\n- **2025-01-20** | Team expands to five with hire of quantum software engineer from IBM\n- **2025-03-08** | Submits first paper to Nature Computational Science on hybrid simulation methodology",
"_facts": {
"type": "company",
"slug": "companies/quantum-labs-57",
"name": "Quantum Labs",
"category": "startup",
"industry": "biotech",
"founded_year": 2024,
"founders": [
"people/liam-wilson-57"
],
"investors": [
"people/rachel-brown-95",
"people/rosa-miller-98"
],
"employees": [
"people/frank-moore-167"
],
"advisors": [
"people/tara-johnson-189"
]
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/quasar-44",
"type": "company",
"title": "Quasar",
"compiled_truth": "Quasar is a data infrastructure startup founded in early 2025 by [Mark Wilson](people/mark-wilson-44), a serial entrepreneur with deep roots in distributed systems. The company emerged from Wilson's frustration with existing data pipeline tools, which he found too brittle for modern real-time workloads. Based in San Francisco, Quasar is building what they call a \"unified data fabric\" — essentially a layer that sits between data sources and downstream applications, handling ingestion, transformation, and delivery with minimal configuration.\n\nThe founding team is lean but experienced. Mark Wilson previously led infrastructure at two mid-stage startups, one of wich was aquired by Snowflake in 2022. He's known for strong opinions on developer experience and has been vocal on Twitter about what he sees as the over-complexity of the modern data stack. Early angel investment came from [Jack Davis](people/jack-davis-89), who reportedly wrote a check after a single demo meeting. Davis has been an active advisor beyond just capital, making introductions to potential design partners in the fintech space.\n\nOn the advisory side, Quasar brought on [Grace Singh](people/grace-singh-197) to help shape go-to-market strategy. Singh's background in enterprise sales has already influenced how the company thinks about pricing and packaging. Internal docs suggest they're leaning toward a consumption-based model with a generous free tier to drive adoption among smaller teams.\n\nQuasar is still in stealth mode as of mid-2025, though they've been quietly onboarding design partners. Early feedback has centered on the product's speed — some users report 10x improvements in query latency compared to legacy tools. The tech stack is Rust-heavy, which aligns with Wilson's preference for performance-first engineering. There's some chatter that a seed round is in the works, though nothing confirmed publicly. The company employs around eight people, mostly engineers recruited from Wilson's network.",
"timeline": "- **2025-01-14** | Quasar incorporated in Delaware by [Mark Wilson](people/mark-wilson-44)\n- **2025-01-28** | Initial angel check from [Jack Davis](people/jack-davis-89), terms undisclosed\n- **2025-02-10** | First engineering hire joins from Databricks\n- **2025-03-05** | [Grace Singh](people/grace-singh-197) formally joins as advisor\n- **2025-03-22** | Internal alpha of core data fabric released to team\n- **2025-04-18** | First design partner signed — a Series B fintech in NYC\n- **2025-05-09** | Wilson presents at private invite-only infrastructure meetup\n- **2025-06-01** | Team grows to eight full-time employees\n- **2025-06-15** | Second design partner onboarded, early latency benchmarks shared internally",
"_facts": {
"type": "company",
"slug": "companies/quasar-44",
"name": "Quasar",
"category": "startup",
"industry": "data infrastructure",
"founded_year": 2025,
"founders": [
"people/mark-wilson-44"
],
"investors": [
"people/jack-davis-89"
],
"employees": [
"people/liam-patel-154"
],
"advisors": [
"people/grace-singh-197"
]
}
}
@@ -1,28 +0,0 @@
{
"slug": "companies/ranger-22",
"type": "company",
"title": "Ranger",
"compiled_truth": "Ranger is a health tech startup founded in 2024 by [Quinten Rodriguez](people/quinten-rodriguez-22), a first-time founder who previously spent six years in clinical operations at major hospital systems. The company is building what it describes as a \"proactive health monitoring platform\" — essentially a combination of wearable integration, predictive analytics, and care coordination tools aimed at catching health issues before they become emergencies.\n\nThe core product pulls data from consumer wearables and runs it through proprietary algorithms that flag concerning patterns. When something looks off, Ranger connects users directly with healthcare providers through an integrated telehealth layer. It's ambitious, maybe overly so for such an early-stage company, but the team seems to be executing well so far.\n\nRanger raised a pre-seed round in early 2024 with participation from [Helen Martinez](people/helen-martinez-87) and [Sarah Wang](people/sarah-wang-104), both of whom have been active in the health tech space. The round was reportedly around $2.1M, though the company hasn't confirmed exact figures publicly. [Beth Williams](people/beth-williams-177) came on as an advisor shortly after, bringing regulatory expertise that will likely prove critical as Ranger navigates FDA considerations around its predictive features.\n\nThe founding team is still small — just seven people as of late 2024 — but they've been hiring aggresively for ML engineering roles. Quinten has been vocal about wanting to build the technical foundation right before scaling the team further. Smart approach, though it means they're moving slower on go-to-market than some competitors.\n\nRanger's initial focus is on cardiovascular health monitoring for adults over 50, a demographic that's both high-risk and increasingly comfortable with wearable technology. Early pilot programs with two regional health systems have shown promising engagement numbers, though clinical outcomes data is still being collected. The company faces stiff competiton from both established players and well-funded startups, but their emphasis on provider integration rather than direct-to-consumer sales could be a meaningful differentiator.",
"timeline": "- **2024-01-15** | Ranger incorporated in Delaware by [Quinten Rodriguez](people/quinten-rodriguez-22)\n- **2024-03-08** | Closed pre-seed round with [Helen Martinez](people/helen-martinez-87) and [Sarah Wang](people/sarah-wang-104) participating\n- **2024-04-22** | [Beth Williams](people/beth-williams-177) joins as regulatory advisor\n- **2024-06-10** | First engineering hire — ML lead recruited from Apple Health team\n- **2024-08-14** | Launched private beta with 200 users in Austin area\n- **2024-10-03** | Announced pilot partnership with Memorial Regional Health System\n- **2024-11-19** | Quinten presented at Digital Health Summit on predictive monitoring\n- **2025-02-01** | Second pilot program launched with Coastal Medical Group\n- **2025-04-28** | Team expanded to 12 people, opened small office in Austin\n- **2025-07-15** | Began conversations with FDA around De Novo pathway for predictive features",
"_facts": {
"type": "company",
"slug": "companies/ranger-22",
"name": "Ranger",
"category": "startup",
"industry": "health tech",
"founded_year": 2024,
"founders": [
"people/quinten-rodriguez-22"
],
"investors": [
"people/helen-martinez-87",
"people/sarah-wang-104"
],
"employees": [
"people/rachel-miller-132"
],
"advisors": [
"people/beth-williams-177"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/resonance-45",
"type": "company",
"title": "Resonance",
"compiled_truth": "Resonance is an enterprise SaaS startup founded in 2022 by [Grace Thomas](people/grace-thomas-45), a former product lead who spent nearly a decade building internal tools at large tech companies before striking out on her own. The company focuses on helping mid-market enterprises manage and optimize their internal communication workflows—think of it as a layer that sits atop Slack, Teams, and email to surface what actually matters and reduce notification fatigue.\n\nThe core product uses machine learning to prioritize messages, flag action items, and generate daily digests tailored to each employee's role and responsiblities. Early customers have described it as \"finally making enterprise chat usable again.\" Resonance has found particular traction in professional services firms and fast-growing startups where information overload is a constant complaint.\n\nGrace Thomas serves as CEO and has been the public face of the company, frequently speaking at SaaS conferences about the hidden costs of context-switching. She's known for her direct communication style and her insistence on dogfooding—the entire Resonance team uses an internal build of the product daily, often shipping fixes within hours of discovering friction points.\n\nThe company has benefited from the guidance of [Yara Singh](people/yara-singh-195), who joined as an advisor shortly after launch. Yara's experience scaling go-to-market motions has been instrumental in shaping Resonance's sales strategy, particularly around land-and-expand deals with departmental buyers. Under her mentorship, the startup has refined its pricing model and built out a small but effective sales team.\n\nResonance operates with a lean team of about 15 people, mostly engineers and a handful of customer success managers. The company is headquartered in Austin but operates fully remote, drawing talent from across North America. Recent product updates have focused on deeper integrations with project managment tools and improved analytics dashboards for IT admins. The roadmap hints at AI-generated meeting summaries and automated escalation paths, though those features remain in beta.",
"timeline": "- **2022-03-14** | Resonance incorporated in Delaware by Grace Thomas\n- **2022-06-01** | Closed a $1.8M pre-seed round led by several angels\n- **2022-09-20** | [Yara Singh](people/yara-singh-195) joins as formal advisor\n- **2023-01-11** | Launched private beta with 12 design partners\n- **2023-05-03** | Public launch of Resonance v1.0 with Slack and Teams integrations\n- **2023-08-15** | Reached $500K ARR milestone\n- **2024-02-22** | [Grace Thomas](people/grace-thomas-45) speaks at SaaStr Annual on reducing enterprise noise\n- **2024-07-09** | Shipped analytics dashboard for IT administrators\n- **2025-01-18** | Announced partnership with a major consulting firm for pilot deployment\n- **2025-04-30** | Beta launch of AI meeting summary feature",
"_facts": {
"type": "company",
"slug": "companies/resonance-45",
"name": "Resonance",
"category": "startup",
"industry": "enterprise SaaS",
"founded_year": 2022,
"founders": [
"people/grace-thomas-45"
],
"employees": [
"people/eric-singh-155"
],
"advisors": [
"people/yara-singh-195"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/sentinel-23",
"type": "company",
"title": "Sentinel",
"compiled_truth": "Sentinel is a consumer social startup founded in 2019 by [Paul Anderson](people/paul-anderson-23), who previously worked in product roles at several mid-stage companies before striking out on his own. The company operates in the increasingly crowded social space, though it's carved out a niche focused on what Anderson calls \"intentional social\" — essentially tools that help people maintain closer relationships with smaller circles rather than broadcasting to large audiences.\n\nThe core product is a mobile app that combines private group messaging with shared memory features. Users can create small groups (capped at 12 people) and the app automatically surfaces shared photos, past conversations, and anniversary reminders. It's not trying to compete with Instagram or TikTok — more like a utility for your actual close friends. The company has been deliberatly slow in scaling, preferring organic growth over paid acquisition.\n\nSentinel raised a seed round in late 2020, though exact figures haven't been disclosed publicly. The team remains small, hovering around 15 employees as of early 2024. [Julia Chen](people/julia-chen-181) serves as an advisor to the company, bringing her expertise in consumer product development and growth strategy. Her involvement reportedly began through a warm intro from a mutual investor.\n\nRecent moves include a pivot toward integrating AI-powered features — specifically, an assistant that helps users remember important dates and suggests conversation starters based on past interactions. Some users have praised this as genuinely useful; others find it slightly creepy. The company has been testing these features in closed beta since mid-2023.\n\nAnderson has been vocal about building a sustainable business rather than chasing hypergrowth. In interviews, he's mentioned that Sentinel may eventually pursue a subscription model rather than advertising, citing concerns about ad-driven incentives corrupting the product's core mission. Whether this philosophy can survive contact with investor expectations remains to be seen. The startup has mostly stayed under the radar, which seems intentional.",
"timeline": "- **2019-03-15** | Sentinel incorporated in Delaware by Paul Anderson\n- **2019-09-02** | First prototype launched to 50 beta users\n- **2020-11-18** | Closed seed funding round, terms undisclosed\n- **2021-06-07** | [Julia Chen](people/julia-chen-181) joined as formal advisor\n- **2022-02-14** | Crossed 100,000 registered users milestone\n- **2022-10-03** | Launched group memory feature called \"Moments\"\n- **2023-05-22** | [Paul Anderson](people/paul-anderson-23) spoke at Consumer Social Summit in SF\n- **2023-08-30** | Began closed beta for AI assistant features\n- **2024-01-12** | Expanded engineering team with three new hires\n- **2025-04-08** | Announced partnership with undisclosed messaging platform",
"_facts": {
"type": "company",
"slug": "companies/sentinel-23",
"name": "Sentinel",
"category": "startup",
"industry": "consumer social",
"founded_year": 2019,
"founders": [
"people/paul-anderson-23"
],
"employees": [
"people/rosa-wilson-133"
],
"advisors": [
"people/julia-chen-181"
]
}
}
@@ -1,14 +0,0 @@
{
"slug": "companies/sequoia-capital-1",
"type": "company",
"title": "Sequoia Capital",
"compiled_truth": "Sequoia Capital stands as one of the most legendary venture capital firms in Silicon Valley history, having backed companies that collectively represent trillions of dollars in market value. Founded in 1972 by Don Valentine, the firm has maintained its position at the apex of the VC world for over five decades. Their portfolio reads like a who's who of tech giants: Apple, Google, Cisco, Oracle, YouTube, Instagram, WhatsApp, and more recently Stripe and Airbnb.\n\nThe firm operates with a philosophy that emphasizes partnering with \"the crazies\" — founders with audacious visions who refuse to accept conventional wisdom. This approach has served them remarkably well, though it hasn't been without its spectacular failures. The FTX debacle in 2022 forced Sequoia to write down a $150 million investment to zero, a rare and very public miss that prompted some internal reflection on due dilligence processes.\n\nIn recent years, Sequoia has undergone significant structural changes. In 2021, they announced a radical restructuring that would transform the firm into a single registered investment adviser, allowing them to hold public stock positions indefinitely rather than distributing shares to LPs after IPOs. This was later partially reversed in 2023 when they split off their China and India operations into seperate entities — a move driven by geopolitical tensions and LP pressure.\n\nThe firm's current leadership includes Roelof Botha as the global managing partner, having taken over from Doug Leone. Botha, who previously served as CFO of PayPal, has been instrumental in deals involving companies like Unity and MongoDB. Their partnership extends across multiple stages, from their scout program to growth-stage investments.\n\nSequoia's relationship with firms like [Andreessen Horowitz](companies/andreessen-horowitz) has been characterized by both competition and mutual respect — they've co-invested on numerous deals while also fiercely competing for the best founders. The firm continues to be a dominant force in AI investing, having backed companies working with partners at [Y Combinator](companies/y-combinator) and other top accelerators. Their AI fund, launched in 2023, demonstrates their commitment to staying at the frontier of technological change.",
"timeline": "- **2021-06-15** | Sequoia announces radical restructuring into single permanent fund structure, shocking the VC industry\n- **2022-01-20** | Led $500M Series C round for AI startup alongside [Andreessen Horowitz](companies/andreessen-horowitz)\n- **2022-11-11** | Published memo to portfolio companies following FTX collapse, writing investment down to zero\n- **2023-03-08** | Roelof Botha promoted to sole global managing partner\n- **2023-06-22** | Announced separation of China and India/SEA operations into independent entities\n- **2024-02-14** | Closed new $2.5B early-stage fund focused on AI and climate tech\n- **2024-09-30** | Participated in seed round for [Y Combinator](companies/y-combinator) batch company building developer tools\n- **2025-01-18** | Hosted annual Base Camp event for seed-stage founders in Woodside\n- **2025-07-22** | Published influential research report on AI agent infrastructure opportunities\n- **2026-03-05** | Led $800M growth round for autonomous systems company at $12B valuation",
"_facts": {
"type": "company",
"slug": "companies/sequoia-capital-1",
"name": "Sequoia Capital",
"category": "vc",
"industry": "venture capital"
}
}
@@ -1,30 +0,0 @@
{
"slug": "companies/spire-46",
"type": "company",
"title": "Spire",
"compiled_truth": "Spire is a biotech startup founded in 2018 by [Linda Miller](people/linda-miller-46), a veteran researcher with deep expertise in synthetic biology and metabolic engineering. The company operates out of the Boston-Cambridge biotech corridor, where it has quietly built a reputation for innovative approaches to protein therapeutics. Unlike many flashier competitors, Spire has maintained a relatively low profile, preferring to let its science speak for itself.\n\nThe company's core technology platform focuses on engineered protein scaffolds that can be customized for various therapeutic applications, including oncology and rare genetic disorders. Their lead candidate, SPR-201, is currently in Phase I clinical trials for a rare metabolic condition affecting pediatric patients. Early data has been promising, though the team remains cautious about over-hyping preliminary results.\n\nSpire has attracted a notable group of investors including [Wendy Hernandez](people/wendy-hernandez-80), [Eric Martinez](people/eric-martinez-93), and [Rosa Nakamura](people/rosa-nakamura-94). The Series A round closed in late 2020, with subsequent bridge financing helping extend runway through the expensive clinical development phase. The company has been judicious with capital, maintaining a lean team of around 35 employees while outsourcing certain manufacturing and regulatory functions.\n\nOn the advisory side, Spire benefits from guidance from [David Kim](people/david-kim-186) and [Grace Singh](people/grace-singh-197), both of whom bring significant industry experiance to the table. David in particular has been instrumental in shaping the clinical strategy, drawing on his background in rare disease drug development.\n\nLinda Miller continues to serve as CEO, a somewhat unusual arrangement in biotech where scientific founders often transition to CSO roles as companies mature. However, her combination of scientific credibility and business acumen has made the dual role work. She's known for being intensley focused on execution and has built a culture that prioritizes rigor over hype.\n\nRecent months have seen Spire expanding its pipeline discussions with potential pharma partners, though nothing has been announced publicly. The company is also exploring applications of its platform technology in areas beyond its initial therapeutic focus, potentially setting up multiple shots on goal as it matures.",
"timeline": "- **2018-03-15** | Spire incorporated in Delaware by [Linda Miller](people/linda-miller-46), initial seed funding from angel investors\n- **2019-08-22** | Published landmark paper in Nature Biotechnology on novel protein scaffold approach\n- **2020-11-30** | Closed $28M Series A led by [Wendy Hernandez](people/wendy-hernandez-80) and [Eric Martinez](people/eric-martinez-93)\n- **2021-06-14** | [David Kim](people/david-kim-186) joins advisory board to help shape clinical development strategy\n- **2022-01-09** | SPR-201 receives FDA orphan drug designation for rare metabolic disorder\n- **2022-09-03** | Expanded lab facilities in Cambridge, added 12 new research positions\n- **2023-04-18** | IND application submitted for SPR-201, cleared by FDA within 30 days\n- **2024-02-11** | First patient dosed in Phase I trial for SPR-201\n- **2024-10-25** | [Rosa Nakamura](people/rosa-nakamura-94) participates in $15M bridge financing round\n- **2025-03-07** | Presented interim Phase I safety data at rare disease conference, well received by analysts",
"_facts": {
"type": "company",
"slug": "companies/spire-46",
"name": "Spire",
"category": "startup",
"industry": "biotech",
"founded_year": 2018,
"founders": [
"people/linda-miller-46"
],
"investors": [
"people/wendy-hernandez-80",
"people/eric-martinez-93",
"people/rosa-nakamura-94"
],
"employees": [
"people/will-kapoor-156"
],
"advisors": [
"people/david-kim-186",
"people/grace-singh-197"
]
}
}
@@ -1,28 +0,0 @@
{
"slug": "companies/talon-47",
"type": "company",
"title": "Talon",
"compiled_truth": "Talon is an edtech startup founded in 2020 by [Diana Thomas](people/diana-thomas-47), who saw an opportunity to reimagine how students engage with technical curriculum. The company's core product is an adaptive learning platform that uses machine learning to personalize coding education pathways for university students and bootcamp participants. Based in Austin, Texas, Talon has quietly built a reputation for its unusually high completion rates—reportedly 3x the industry average for online technical courses.\n\nThe founding story is straightforward. Diana had spent years frustrated by one-size-fits-all approaches to teaching programming. She bootstrapped the initial prototype while still working her day job, then went full-time in late 2020. Early traction came from partnerships with two regional coding bootcamps who were desperate for better retention tools. Word spread.\n\nInvestment came from [Sarah Williams](people/sarah-williams-92), who led a seed round in early 2022. Sarah's background in workforce development made her a natural fit, and she's remained actively involved in shaping Talon's go-to-market strategy. The company has since expanded to serve over 40 educational institutions, with particular strenght in community colleges looking to modernize their CS programs.\n\nOn the advisory side, [David Kim](people/david-kim-186) provides guidance on enterprise sales cycles, having scaled several B2B edtech companies himself. [Noah Williams](people/noah-williams-198) advises on curriculum design and learning science—his academic background complements Diana's more technical instincts. The advisory board meets quarterly, though informal check-ins happen more frequently.\n\nTalon's recent focus has been on expanding beyond pure coding education into adjacent technical skills: data literacy, basic cloud infrastructure, that sort of thing. There's also been internal discusson about whether to pursue K-12 markets, though Diana has been hesitant to dilute focus. The team remains lean at around 25 employees, mostly engineers and instructional designers. Revenue figures aren't public but insiders suggest ARR crossed $2M sometime in 2024.",
"timeline": "- **2020-06-15** | Diana Thomas incorporates Talon and begins building MVP\n- **2020-11-02** | First pilot partnership signed with Austin Coding Academy\n- **2022-02-18** | Seed round closes, led by [Sarah Williams](people/sarah-williams-92)\n- **2022-09-10** | [David Kim](people/david-kim-186) joins as formal advisor\n- **2023-03-22** | Talon platform launches publicly, signs 12 institutions in first quarter\n- **2023-08-14** | [Noah Williams](people/noah-williams-198) brought on to advise on learning science\n- **2024-01-29** | Company hits 40 institutional customers milestone\n- **2024-06-05** | Diana presents at ASU+GSV Summit on adaptive learning\n- **2025-02-11** | Talon announces expansion into data literacy curriculum\n- **2025-09-03** | Strategic partnership discussions begin with major community college system",
"_facts": {
"type": "company",
"slug": "companies/talon-47",
"name": "Talon",
"category": "startup",
"industry": "edtech",
"founded_year": 2020,
"founders": [
"people/diana-thomas-47"
],
"investors": [
"people/sarah-williams-92"
],
"employees": [
"people/rachel-thomas-157"
],
"advisors": [
"people/david-kim-186",
"people/noah-williams-198"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/tempo-24",
"type": "company",
"title": "Tempo",
"compiled_truth": "Tempo is a biotech startup founded in 2020 by [Quinten Lee](people/quinten-lee-24), focused on developing novel approaches to metabolic disease therapeutics. The company emerged from Lee's frustration with the slow pace of traditional drug discovery and his belief that computational biology could dramatically accelerate the identification of viable drug candidates.\n\nThe company operates out of a modest lab space in South San Francisco, though they've been reportedly looking at expanding into a larger facility given recent growth. Tempo's core platform combines machine learning with high-throughput screening to identify small molecule compounds that modulate metabolic pathways. Their initial focus has been on type 2 diabetes and obesity, though internal documents suggest they're exploring applications in fatty liver disease as well.\n\n[Yara Moore](people/yara-moore-174) serves as an advisor to the company, bringing her extensive experience in regulatory affairs and clinical development strategy. Her involvement has been particularly valuable as Tempo prepares for eventual IND-enabling studies. Moore's connections within the FDA have reportedly helped the team think more strategically about their development timeline.\n\nThe startup has remained relatively quiet compared to other biotech players in the metabolic space, preferring to let data speak rather than hype. Quinten has been deliberate about this approach, often saying in interviews that \"biotech has too much vaporware.\" This philosophy has attracted a certain type of investor—those who prefer substance over flash.\n\nTempo raised a seed round in early 2021 and has since closed a Series A, though exact figures haven't been publicly disclosed. The team has grown to approximately 25 people, mostly bench scientists and computational biologists. They've published a couple of papers in mid-tier journals, nothing splashy, but the work demonstrates a solid methodological foundation. Recent rumors suggest they've achieved some promissing preclinical results in mouse models, though the company hasn't confirmed this publically.",
"timeline": "- **2020-06-15** | Tempo incorporated in Delaware by [Quinten Lee](people/quinten-lee-24)\n- **2021-02-08** | Closed seed round, terms undisclosed\n- **2021-09-22** | [Yara Moore](people/yara-moore-174) formally joins as strategic advisor\n- **2022-04-11** | Published first platform paper in Journal of Computational Biology\n- **2022-11-30** | Moved into expanded South San Francisco lab facility\n- **2023-03-17** | Series A closed, reportedly oversubscribed\n- **2023-08-05** | Hired VP of Biology from Amgen\n- **2024-01-22** | Internal milestone: lead compound identified for T2D program\n- **2024-09-14** | Quinten Lee presented at JP Morgan Healthcare Conference (private session)\n- **2025-02-28** | Initiated IND-enabling studies for lead metabolic compound",
"_facts": {
"type": "company",
"slug": "companies/tempo-24",
"name": "Tempo",
"category": "startup",
"industry": "biotech",
"founded_year": 2020,
"founders": [
"people/quinten-lee-24"
],
"employees": [
"people/mia-liu-134"
],
"advisors": [
"people/yara-moore-174"
]
}
}
@@ -1,27 +0,0 @@
{
"slug": "companies/tessera-15",
"type": "company",
"title": "Tessera",
"compiled_truth": "Tessera is a fintech startup founded in 2024 by [Noah Kapoor](people/noah-kapoor-15), a serial entrepreneur with deep expertise in payments infrastructure and distributed systems. The company is building what it describes as \"programmable treasury rails\" — essentially a platform that lets mid-market companies automate complex cash management workflows without relying on legacy banking integrations. Think of it as Plaid meets Airflow, but for corporate finance teams who are tired of moving money through spreadsheets and manual wire transfers.\n\nThe founding team is lean but credible. Noah previously spent six years at Stripe, where he led a team focused on cross-border settlement optimization. Before that, he did a stint at a Series B payments company that got aquired by Block in 2021. He's known in fintech circles for his pragmatic approach to product development — shipping fast, iterating based on real customer feedback, and avoiding the trap of over-engineering.\n\nTessera raised a $4.2M seed round in late 2024, led by [Kate Lopez](people/kate-lopez-99), a partner at Foundry Ventures who has backed several successful fintech exits. The round included participation from a handful of angel investors, mostly former operators from Stripe, Ramp, and Modern Treasury. The company has been relatively quiet about its traction, though Noah has mentioned in a few podcast appearances that they have \"a handful of design partners\" actively using the platform.\n\nOn the advisory side, [Yara Singh](people/yara-singh-195) has been helping the team think through go-to-market strategy and enterprise sales motions. Yara's background in scaling B2B fintech products has been valuable as Tessera figures out how to position itself against incumbents like Kyriba and newer players like Treasure.\n\nThe company operates out of San Francisco, with a small remote-first team of about eight people. Noah has been vocal about keeping the team small until they nail product-market fit — a lesson he says he learned the hard way at his previous startup. Tessera's current focus is on onboarding its first ten paying customers and proving out unit economics before raising a Series A, likely in late 2025.",
"timeline": "- **2024-02-12** | Noah Kapoor incorporates Tessera in Delaware, begins recruiting co-founding engineers\n- **2024-04-08** | First prototype of treasury automation platform demoed to potential design partners\n- **2024-06-15** | [Kate Lopez](people/kate-lopez-99) leads $4.2M seed round; Foundry Ventures announces the investment\n- **2024-07-22** | [Yara Singh](people/yara-singh-195) joins as formal advisor, focusing on GTM strategy\n- **2024-09-03** | Tessera onboards first two design partners — both mid-market e-commerce companies\n- **2024-11-18** | Noah speaks at Fintech Devcon about \"rethinking treasury infrastructure for the API era\"\n- **2025-01-09** | Team grows to eight; hires head of engineering from Modern Treasury\n- **2025-03-14** | Closes first paying customer contract, $48K ARR\n- **2025-05-02** | Begins early conversations with Series A investors, targeting Q4 2025 raise",
"_facts": {
"type": "company",
"slug": "companies/tessera-15",
"name": "Tessera",
"category": "startup",
"industry": "fintech",
"founded_year": 2024,
"founders": [
"people/noah-kapoor-15"
],
"investors": [
"people/kate-lopez-99"
],
"employees": [
"people/gabe-wilson-125"
],
"advisors": [
"people/yara-singh-195"
]
}
}
@@ -1,24 +0,0 @@
{
"slug": "companies/umbra-48",
"type": "company",
"title": "Umbra",
"compiled_truth": "Umbra is a health tech startup founded in early 2025 by [Zoe Kim](people/zoe-kim-48), a serial entrepreneur with deep roots in digital therapeutics and wearable technology. The company operates in stealth mode for much of its first year, though insiders describe its focus as \"ambient health monitoring\" — a system that passively collects biometric and environmental data to surface early warning signs of chronic disease.\n\nThe founding thesis emerged from Kim's frustration with reactive healthcare models. She wanted to build something that could catch problems before they became crises, particulary for populations underserved by traditional primary care. Umbra's initial product combines low-power sensor hardware with an AI backend trained on longitudinal health data. The company has been tight-lipped about specifics, but demo videos leaked in mid-2025 showed a small wearable device syncing with ambient sensors placed around a home.\n\nAdvisory support comes from [Vera Rodriguez](people/vera-rodriguez-171), who brings credibility from her work in regulatory strategy and medical device commercialization. Rodriguez's involvement suggests Umbra is serious about FDA clearance and clinical validation, not just consumer wellness claims. Her network has reportedly helped the company secure early conversations with payer organizations interested in preventive care pilots.\n\nUmbra operates with a lean team — roughly twelve people as of late 2025, split between engineering, clinical research, and ops. They've raised a seed round, though the amount remains undisclosed. The company culture leans heavily on asynchronous work and documentation, a hallmark of Kim's previous ventures. Recruiting has focused on candidates with backgrounds in signal processing, embedded systems, and health informatics.\n\nThe competitive landscape is crowded, but Umbra differentiates itself by targeting B2B2C partnerships rather than direct-to-consumer sales. Early pilots with regional health systems are expected to begin in Q1 2026. Whether Umbra can execute on its ambitious vision remains to be seen, but the team's pedigree and early traction have attracted attention from health-focused VCs watching the space closely.",
"timeline": "- **2025-01-18** | Umbra incorporated in Delaware by [Zoe Kim](people/zoe-kim-48)\n- **2025-02-04** | [Vera Rodriguez](people/vera-rodriguez-171) joins as lead advisor\n- **2025-03-22** | Seed round closed, amount undisclosed\n- **2025-04-10** | First engineering hire — embedded systems lead from Oura\n- **2025-06-15** | Internal prototype v0.1 completed; early testing begins\n- **2025-08-07** | Demo video leaked on Twitter, sparking industry speculation\n- **2025-09-30** | Team reaches 12 full-time employees\n- **2025-11-12** | Preliminary conversations with two regional health systems for pilot programs\n- **2026-01-08** | Planned kickoff for first B2B2C pilot deployment",
"_facts": {
"type": "company",
"slug": "companies/umbra-48",
"name": "Umbra",
"category": "startup",
"industry": "health tech",
"founded_year": 2025,
"founders": [
"people/zoe-kim-48"
],
"employees": [
"people/julia-garcia-158"
],
"advisors": [
"people/vera-rodriguez-171"
]
}
}

Some files were not shown because too many files have changed in this diff Show More